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 |
|---|---|---|---|---|---|
#
# 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.
#
# Copyright (c) 2016 by Delphix. All rights reserved.
#
# Program Name : dx_get_js_datasource.pl
# Description : Get Delphix Engine timeflow bookmarks
# Author : Marcin Przepiorowski
# Created : 02 Mar 2016 (v2.2.3)
#
use strict;
use warnings;
use JSON;
use Getopt::Long qw(:config no_ignore_case no_auto_abbrev); #avoids conflicts with ex host and help
use File::Basename;
use Pod::Usage;
use FindBin;
use Data::Dumper;
my $abspath = $FindBin::Bin;
use lib '../lib';
use Engine;
use Formater;
use Toolkit_helpers;
use JS_template_obj;
use JS_datasource_obj;
use Databases;
my $version = $Toolkit_helpers::version;
GetOptions(
'help|?' => \(my $help),
'd|engine=s' => \(my $dx_host),
'template_name=s' => \(my $template_name),
'datasource_name=s' => \(my $datasource_name),
'dbname=s' => \(my $dbname),
'format=s' => \(my $format),
'group=s' => \(my $group),
'all' => (\my $all),
'version' => \(my $print_version),
'dever=s' => \(my $dever),
'nohead' => \(my $nohead),
'debug:i' => \(my $debug),
'configfile|c=s' => \(my $config_file)
) or pod2usage(-verbose => 1, -input=>\*DATA);
pod2usage(-verbose => 2, -input=>\*DATA) && exit if $help;
die "$version\n" if $print_version;
my $engine_obj = new Engine ($dever, $debug);
$engine_obj->load_config($config_file);
if (defined($all) && defined($dx_host)) {
print "Option all (-all) and engine (-d|engine) are mutually exclusive \n";
pod2usage(-verbose => 1, -input=>\*DATA);
exit (1);
}
# this array will have all engines to go through (if -d is specified it will be only one engine)
my $engine_list = Toolkit_helpers::get_engine_list($all, $dx_host, $engine_obj);
my $output = new Formater();
$output->addHeader(
{'Appliance', 20},
{'Datasource name', 20},
{'Template name', 30},
{'Database name', 50},
);
my $ret = 0;
for my $engine ( sort (@{$engine_list}) ) {
# main loop for all work
if ($engine_obj->dlpx_connect($engine)) {
print "Can't connect to Dephix Engine $dx_host\n\n";
$ret = $ret + 1;
next;
};
my $jstemplates = new JS_template_obj ($engine_obj, $debug );
my $db = new Databases ( $engine_obj , $debug);
my $groups = new Group_obj($engine_obj, $debug);
my $db_obj;
my $template_obj;
if (defined($dbname)) {
my $db_list = Toolkit_helpers::get_dblist_from_filter(undef, $group, undef, $dbname, $db, $groups, undef, undef, undef, undef, undef, undef, undef, $debug);
if (! defined($db_list)) {
print "There is no DB selected to process on $engine . Please check filter definitions. \n";
$ret = $ret + 1;
next;
}
if ( ( scalar (@{$db_list} ) < 1 ) ) {
print "Can't find database $dbname \n";
$ret = $ret + 1;
next;
}
if ( ( scalar (@{$db_list} ) > 1 ) ) {
print "More than one database found. Please use dbname and group to select a database - $dbname \n";
$ret = $ret + 1;
next;
}
$db_obj = $db_list->[0];
}
if (defined($template_name)) {
$template_obj = $jstemplates->getJSTemplateByName($template_name);
if (! defined($template_obj)) {
print "Template name not found\n";
$ret = $ret + 1;
next;
}
}
my $jsdatasources = new JS_datasource_obj ( $engine_obj , $template_obj, $db_obj);
for my $ds (@{$jsdatasources->getJSDataSourceList()}) {
my $temp_cont = $jstemplates->getName($jsdatasources->getJSTemplate($ds));
if (!defined($temp_cont)) {
# do not display JS container DB's
next;
}
my $display_db_name = $groups->getName($db->getDB($jsdatasources->getJSDBContainer($ds))->getGroup()). " / " . $db->getDB($jsdatasources->getJSDBContainer($ds))->getName() ;
$output->addLine(
$engine,
$jsdatasources->getName($ds),
$temp_cont,
$display_db_name
);
}
}
Toolkit_helpers::print_output($output, $format, $nohead);
exit $ret;
__DATA__
=head1 SYNOPSIS
dx_get_js_datasource [ -engine|d <delphix identifier> | -all ] [ -configfile file ][-template_name template_name]
[-datasource_name datasource_name]
[-dbname dbname]
[-group group]
[-format csv|json ]
[-help|? ] [ -debug ]
=head1 DESCRIPTION
Get the list of Jet Stream data stores from Delphix Engine.
=head1 ARGUMENTS
Delphix Engine selection - if not specified a default host(s) from dxtools.conf will be used.
=over 10
=item B<-engine|d>
Specify Delphix Engine name from dxtools.conf file
=item B<-all>
Display databases on all Delphix appliance
=item B<-configfile file>
Location of the configuration file.
A config file search order is as follow:
- configfile parameter
- DXTOOLKIT_CONF variable
- dxtools.conf from dxtoolkit location
=back
=head2 Options
=over 4
=item B<-datasource_name datasource_name>
Display data source with name datasource_name
=item B<-template_name template_name>
Display data sources for template_name
=item B<-dbname dbname>
Display data sources for database name dbname
=item B<-group groupname>
Display data sources for database name dbname and group groupname
=back
=head1 OPTIONS
=over 3
=item B<-format>
Display output in csv or json format
If not specified pretty formatting is used.
=item B<-help>
Print this screen
=item B<-debug>
Turn on debugging
=item B<-nohead>
Turn off header output
=back
=head1 EXAMPLES
List of data sources for database called Oracle dsource
dx_get_js_datasources -d Landshark5 -dbname "Oracle dsource"
Appliance Datasource name Template name Database name
-------------------- -------------------- -------------------- -------------------------------------------
Landshark5 oracle test Sources / Oracle dsource
=cut
| delphix/dxtoolkit | bin/dx_get_js_datasources.pl | Perl | apache-2.0 | 6,432 |
package OpenXPKI::Test::CertHelper::Workflow;
use Moose;
use utf8;
=head1 NAME
OpenXPKI::Test::CertHelper::Workflow - Test helper that creates certificates
using OpenXPKI workflows
=head1 DESCRIPTION
This class is not intended for direct use. Please use the class methods in
L<OpenXPKI::Test::CertHelper> instead.
=cut
# Core modules
use File::Basename;
# CPAN modules
use Test::More;
# Project modules
use OpenXPKI::Serialization::Simple;
################################################################################
# Constructor attributes
#
=head2 new
Constructor.
Named parameters:
=over
=item * B<tester> - Instance of L<OpenXPKI::Test::More> (required)
=item * B<hostname> - Hostname for certificate (I<Str>, required)
=item * B<application_name> - Application name (I<Str>, required for client profile)
=item * B<hostname2> - List of additional hostnames for the certificate (I<ArrayRef[Str]>, optional for server profile)
=item * B<profile> - Certificate profile (I<Str>, optional, default: I18N_OPENXPKI_PROFILE_TLS_SERVER)
=item * B<requestor_gname> - Surname of person requesting cert (I<Str>, optional)
=item * B<requestor_name> - Name of person requesting cert (I<Str>, optional)
=item * B<requestor_email> - Email of person requesting cert (I<Str>, optional)
=item * B<notbefore> - Sets the "valid from" date of the cert (I<Int>, optional)
=item * B<notafter> - Sets the "valid to" date of the cert (I<Int>, optional)
=back
=cut
has tester => (
is => 'rw',
isa => 'OpenXPKI::Test::More',
required => 1,
);
has hostname => (
is => 'rw',
isa => 'Str',
required => 1,
);
has application_name => (
is => 'rw',
isa => 'Str',
default => "Joust",
);
has hostname2 => (
is => 'rw',
isa => 'ArrayRef[Str]',
default => sub { [] },
);
has profile => (
is => 'rw',
isa => 'Str',
default => "I18N_OPENXPKI_PROFILE_TLS_SERVER",
);
has requestor_gname => (
is => 'rw',
isa => 'Str',
default => "Andreas",
);
has requestor_name => (
is => 'rw',
isa => 'Str',
default => "Anders",
);
has requestor_email => (
is => 'rw',
isa => 'Str',
default => "andreas.anders\@mycompany.local",
);
has notbefore => (
is => 'rw',
isa => 'Int',
);
has notafter => (
is => 'rw',
isa => 'Int',
);
################################################################################
# METHODS
#
=head1 Methods
=head2 create_cert
Runs a L<subtest|Test::More/subtest> that creates a certificate via workflow
I<certificate_signing_request_v2> and returns a HashRef with some certificate
info.
=cut
sub create_cert {
my $self = shift;
my $test = $self->tester;
my $serializer = OpenXPKI::Serialization::Simple->new();
my $is_server_profile = $self->profile eq "I18N_OPENXPKI_PROFILE_TLS_SERVER";
my $is_client_profile = $self->profile eq "I18N_OPENXPKI_PROFILE_TLS_CLIENT";
my %cert_subject_parts = (
# IP addresses instead of host names will make DNS lookups fail quicker
hostname => $self->hostname,
$is_server_profile ? (
hostname2 => $self->hostname2,
port => 8080,
) : (),
$is_client_profile ? (
application_name => $self->application_name,
) : (),
);
subtest "Create certificate (hostname ".$self->hostname.")" => sub {
plan tests => 14 + ($is_server_profile ? 2 : 0);
#plan tests => 16 + ($self->notbefore ? 2 : 0);
$test->create_ok('certificate_signing_request_v2', {
cert_profile => $self->profile,
cert_subject_style => "00_basic_style",
}, 'Create workflow: certificate signing request (hostname: '.$cert_subject_parts{hostname}.')')
or die(explain($test->get_msg));
$test->state_is('SETUP_REQUEST_TYPE') or die(explain($test->get_msg));
$test->execute_ok('csr_provide_server_key_params', {
key_alg => "rsa",
enc_alg => 'aes256',
key_gen_params => $serializer->serialize( { KEY_LENGTH => 2048 } ),
password_type => 'client',
csr_type => 'pkcs10'
}) or die(explain($test->get_msg));
$test->state_is('ENTER_KEY_PASSWORD') or die(explain($test->get_msg));
$test->execute_ok('csr_ask_client_password', {
_password => "m4#bDf7m3abd",
}) or die(explain($test->get_msg));
$test->state_is('ENTER_SUBJECT') or die(explain($test->get_msg));
$test->execute_ok('csr_edit_subject', {
cert_subject_parts => $serializer->serialize( \%cert_subject_parts )
}) or die(explain($test->get_msg));
if ($is_server_profile) {
$test->state_is('ENTER_SAN') or die(explain($test->get_msg));
$test->execute_ok('csr_edit_san', {
cert_san_parts => $serializer->serialize( { } )
}) or die(explain($test->get_msg));
}
$test->state_is('ENTER_CERT_INFO') or die(explain($test->get_msg));
$test->execute_ok('csr_edit_cert_info', {
cert_info => $serializer->serialize( {
requestor_gname => $self->requestor_gname,
requestor_name => $self->requestor_name,
requestor_email => $self->requestor_email,
} )
}) or die(explain($test->get_msg));
$test->state_is('SUBJECT_COMPLETE') or die(explain($test->get_msg));
# Test FQDNs should not validate so we need a policy exception request
# (on rare cases the responsible router might return a valid address, so we check)
my $msg = $test->get_client->send_receive_command_msg('get_workflow_info', { ID => $test->get_wfid });
my $actions = $msg->{PARAMS}->{STATE}->{option};
my $intermediate_state;
if (grep { /^csr_enter_policy_violation_comment$/ } @$actions) {
diag "Test FQDNs do not resolve - handling policy violation" if $ENV{TEST_VERBOSE};
$test->execute_ok( 'csr_enter_policy_violation_comment', { policy_comment => 'This is just a test' } )
or die(explain($test->get_msg));
$intermediate_state ='PENDING_POLICY_VIOLATION';
}
else {
diag "For whatever reason test FQDNs do resolve - submitting request" if $ENV{TEST_VERBOSE};
$test->execute_ok( 'csr_submit' ) or die(explain($test->get_msg));
$intermediate_state ='PENDING';
}
$test->state_is($intermediate_state) or die(explain($test->get_msg));
# if ($self->notbefore) {
# $test->execute_ok('csr_edit_validity', {
# notbefore => $self->notbefore,
# notafter => $self->notafter,
# });
# $test->state_is( ??? );
# }
$test->execute_ok('csr_approve_csr') or die(explain($test->get_msg));
$test->state_is('SUCCESS') or die(explain($test->get_msg));
};
return {
req_key => $test->param('csr_serial'),
identifier => $test->param('cert_identifier'),
profile => $test->param('cert_profile'),
};
}
__PACKAGE__->meta->make_immutable;
| aleibl/openxpki | qatest/lib/OpenXPKI/Test/CertHelper/Workflow.pm | Perl | apache-2.0 | 7,145 |
package Paws::EMR::SetTerminationProtection;
use Moose;
has JobFlowIds => (is => 'ro', isa => 'ArrayRef[Str|Undef]', required => 1);
has TerminationProtected => (is => 'ro', isa => 'Bool', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'SetTerminationProtection');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::EMR::SetTerminationProtection - Arguments for method SetTerminationProtection on Paws::EMR
=head1 DESCRIPTION
This class represents the parameters used for calling the method SetTerminationProtection on the
Amazon Elastic MapReduce service. Use the attributes of this class
as arguments to method SetTerminationProtection.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to SetTerminationProtection.
As an example:
$service_obj->SetTerminationProtection(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> JobFlowIds => ArrayRef[Str|Undef]
A list of strings that uniquely identify the clusters to protect. This
identifier is returned by RunJobFlow and can also be obtained from
DescribeJobFlows .
=head2 B<REQUIRED> TerminationProtected => Bool
A Boolean that indicates whether to protect the cluster and prevent the
Amazon EC2 instances in the cluster from shutting down due to API
calls, user intervention, or job-flow error.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method SetTerminationProtection in L<Paws::EMR>
=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/EMR/SetTerminationProtection.pm | Perl | apache-2.0 | 2,122 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Resources::NetworkSettings;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
targetContentNetwork => $args->{targetContentNetwork},
targetGoogleSearch => $args->{targetGoogleSearch},
targetPartnerSearchNetwork => $args->{targetPartnerSearchNetwork},
targetSearchNetwork => $args->{targetSearchNetwork}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Resources/NetworkSettings.pm | Perl | apache-2.0 | 1,255 |
package Paws::EMR::InstanceGroupStatus;
use Moose;
has State => (is => 'ro', isa => 'Str');
has StateChangeReason => (is => 'ro', isa => 'Paws::EMR::InstanceGroupStateChangeReason');
has Timeline => (is => 'ro', isa => 'Paws::EMR::InstanceGroupTimeline');
1;
### main pod documentation begin ###
=head1 NAME
Paws::EMR::InstanceGroupStatus
=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::EMR::InstanceGroupStatus object:
$service_obj->Method(Att1 => { State => $value, ..., Timeline => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::EMR::InstanceGroupStatus object:
$result = $service_obj->Method(...);
$result->Att1->State
=head1 DESCRIPTION
The details of the instance group status.
=head1 ATTRIBUTES
=head2 State => Str
The current state of the instance group.
=head2 StateChangeReason => L<Paws::EMR::InstanceGroupStateChangeReason>
The status change reason details for the instance group.
=head2 Timeline => L<Paws::EMR::InstanceGroupTimeline>
The timeline of the instance group status over time.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::EMR>
=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/EMR/InstanceGroupStatus.pm | Perl | apache-2.0 | 1,687 |
#!/usr/bin/perl
require "/perfstat/build/serialize/create/ServiceConfig.pl";
#add create new service
$service = Service->new( RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288",
rrdStep => "300",
serviceName => "socket",
);
#add metric 0
$obj = Metric->new( rrdIndex => 0,
metricName => "activeOpens",
friendlyName => "Active Open Connections",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 100,
critThreshold => 500,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add metric 1
$obj = Metric->new( rrdIndex => 1,
metricName => "passiveOpens",
friendlyName => "Passive Open Connections",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 0,
warnThreshold => 100,
critThreshold => 500,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add metric 2
$obj = Metric->new( rrdIndex => 2,
metricName => "estConnections",
friendlyName => "Established Connections",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 100,
critThreshold => 300,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#print out this service
print ("Ref: ref($service)\n");
$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
$rrdStep = $service->getRRDStep();
$lastUpdate = $service->getLastUpdate();
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
print ("rrdStep: $rrdStep\n");
print ("Last Update: $lastUpdate\n");
#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$metricObject = $service->{metricArray}->[$counter];
$rrdIndex = $metricObject->getRRDIndex();
$rrdDST = $metricObject->getRRDDST();
$rrdHeartbeat = $metricObject->getRRDHeartbeat();
$rrdMin = $metricObject->getRRDMin();
$rrdMax = $metricObject->getRRDMax();
$metricName = $metricObject->getMetricName();
$friendlyName = $metricObject->getFriendlyName();
$status = $metricObject->getStatus();
$hasEvents = $metricObject->getHasEvents();
$warnThreshold = $metricObject->getWarnThreshold();
$critThreshold = $metricObject->getCritThreshold();
$thresholdUnit = $metricObject->getThresholdUnit();
print ("rrdIndex: $rrdIndex\n");
print ("rrdDST: $rrdDST\n");
print ("rrdHeartbeat: $rrdHeartbeat\n");
print ("rrdMin: $rrdMin\n");
print ("rrdMax: $rrdMax\n");
print ("metricName: $metricName\n");
print ("friendlyName: $friendlyName\n");
print ("status: $status\n");
print ("hasEvents: $hasEvents\n");
print ("warnThreshold: $warnThreshold\n");
print ("critThreshold: $critThreshold\n");
print ("threshUnit: $thresholdUnit\n\n");
}
#print out this services graphs
$arrayLength = $service->getGraphArrayLength();
print ("graph Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$graphObject = $service->{graphArray}->[$counter];
$name = $graphObject->getName();
$title = $graphObject->getTitle();
$y_axis = $graphObject->getYaxis();
$legend = $graphObject->getLegend();
$text = $graphObject->getText();
print ("name: $name\n");
print ("title: $title\n");
print ("y_axis: $y_axis\n");
print ("legend: $legend\n");
print ("text: $text\n");
$arrayLength2 = $graphObject->getOptionsArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("option: $graphObject->{optionsArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getDefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("def: $graphObject->{defArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getCdefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("cdef: $graphObject->{cdefArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getLineArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("line: $graphObject->{lineArray}->[$counter2]\n");
}
}
#Store the service
$service->store("$perfhome/etc/configs/WinNT/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
| ktenzer/perfstat | misc/serialize/create/WindowsNT/022404/socket.pl | Perl | apache-2.0 | 4,464 |
#!/usr/bin/perl -w
use warnings;
use strict;
use 5.010;
use Time::Piece;
use IO::Handle;
use Locale::Currency::Format;
# Works with Firefox version 43
# https://ftp.mozilla.org/pub/firefox/releases/43.0/win32/en-US/
# ProvidentAvp1.pl
# Input file: ARGV[0] = Sales Report in .CSV format
# Output file: ProvidentAvpFile.html - the selection of products for each customer
#
if (open(AM_INPUT_FILE,$ARGV[0]) == 0) {
print "Error opening input AutoManager report file: ",$ARGV[0],"\n";
exit -1;
}
my $vin;
my $mileage;
my $lastname;
my $firstname;
my $address;
my $city;
my $zip;
my $saledate;
my $homephone;
my $cellphone;
my $vehicle;
my $state;
my $price;
my $myTodayFormat = localtime->strftime('%Y_%m_%d');
mkdir $myTodayFormat;
my $avpHtmlFilename = sprintf("%s\\ProvidentAvpFile.html",$myTodayFormat);
my $filename = sprintf(">%s",$avpHtmlFilename);
if (open(HTML_OUTPUT_FILE,$filename) == 0) {
print "Error opening: %s",$filename,"\n";
exit -1;
}
while (<AM_INPUT_FILE>)
{
chomp;
($vin,$mileage,$firstname,$lastname,$address,$city,$state,$zip,$saledate,$homephone,$cellphone,$price,$vehicle) = split(",");
if (length($vin) ne 17)
{
last;
}
if (!length($mileage) || !length($firstname) || !length($lastname) || !length($address) || !length($city) || !length($state) || !length($zip) || !length($saledate) || !length($price) || !length($vehicle))
{
print "Error found in entry: VIN: ",$vin, " Firstname: ",$firstname, " Lastname: ",$lastname, " Mileage: ",$mileage, " Price: ",$price, " Zip: ",$zip,"\n";
print HTML_OUTPUT_FILE "Error found in entry: VIN: ",$vin, " Firstname: ",$firstname, " Lastname: ",$lastname, " Mileage: ",$mileage, " Price: ",$price, " Zip: ",$zip,"\n";
exit;
}
}
close (AM_INPUT_FILE);
if (open(AM_INPUT_FILE,$ARGV[0]) == 0) {
print "Error opening input AutoManager report file: ",$ARGV[0],"\n";
exit -1;
}
print HTML_OUTPUT_FILE "<html>\n";
print HTML_OUTPUT_FILE "<body>\n";
print HTML_OUTPUT_FILE "<title>AVP eXpress</title>\n";
print HTML_OUTPUT_FILE "<div style=\"display:block;text-align:left\">\n";
print HTML_OUTPUT_FILE "<a href=\"http://new.assuredvehicleprotection.com/Login.aspx\" imageanchor=1>\n";
print HTML_OUTPUT_FILE "<img align=\"left\" src=\"ProvidentAvp.png\" border=0></a><h1><I>AVP eXpress</I></h1><br>\n";
print HTML_OUTPUT_FILE "<form method=\"GET\" action=\"http://localhost/ProvidentAvpXpress/ProvidentAvp2.pl\">\n";
print HTML_OUTPUT_FILE "<head><style>\n";
print HTML_OUTPUT_FILE "table { width:100%;}\n";
print HTML_OUTPUT_FILE "th, td { padding: 10px;}\n";
print HTML_OUTPUT_FILE "table#table01 tr:nth-child(even) { background-color: #eee; }\n";
print HTML_OUTPUT_FILE "table#table01 tr:nth-child(odd) { ba084B8Ackground-color: #fff; }\n";
print HTML_OUTPUT_FILE "table#table01 th { background-color: #084B8A; color: white; }\n";
print HTML_OUTPUT_FILE "</style></head>\n";
print HTML_OUTPUT_FILE "<style TYPE=\"text/css\">";
print HTML_OUTPUT_FILE "<!--\n";
print HTML_OUTPUT_FILE "TD{font-family: Arial; font-size: 10pt;}\n";
print HTML_OUTPUT_FILE "TH{font-family: Arial; font-size: 10pt;}\n";
print HTML_OUTPUT_FILE "--->\n";
print HTML_OUTPUT_FILE "</style>\n";
print HTML_OUTPUT_FILE "<td width=\"3%\" align=\"center\" bgcolor=\"#F3F781\"><input type=\"radio\" name=\"cust_product\" value=\"Warranty\" checked>Warranty</td> ";
print HTML_OUTPUT_FILE "<td width=\"4%\" align=\"center\" bgcolor=\"#F3F781\"><input type=\"radio\" name=\"cust_product\" value=\"GAP\">GAP</td><br>\n";
print HTML_OUTPUT_FILE "<br><br>";
print HTML_OUTPUT_FILE "<table border=5 id=\"table01\" >\n";
print HTML_OUTPUT_FILE "<tr><th>Entry</th><th>Select</th><th>Warranty (months)</th><th>Warranty (mileage)</th><th>Warranty (deductible)</th><th>High Mileage</th><th>Sales Date</th><th>VIN</th><th>Odometer</th><th>Name</th><th>Sales Price</th><th>Vehicle</th></tr>\n";
my $loopIteration = 0;
while (<AM_INPUT_FILE>)
{
chomp;
($vin,$mileage,$firstname,$lastname,$address,$city,$state,$zip,$saledate,$homephone,$cellphone,$price,$vehicle) = split(",");
print $loopIteration, " ", $vin, "\n";
if (length($vin) ne 17)
{
last;
}
$firstname =~ s/^ *//;
$firstname = sprintf("%s",ucfirst(lc($firstname)));
$lastname = sprintf("%s",ucfirst(lc($lastname)));
$vehicle = uc($vehicle);
my $phone = $cellphone;
if (length $phone < 10)
{
$phone = $homephone;
}
if (!length($mileage) || !length($firstname) || !length($lastname) || !length($address) || !length($city) || !length($state) || !length($zip) || !length($saledate) || !length($price) || !length($vehicle))
{
print "Error found in entry: VIN: ",$vin, " Firstname: ",$firstname, " Lastname: ",$lastname,"\n";
exit;
}
my $formatted_price = currency_format('usd',$price,FMT_SYMBOL);
my $formatted_mileage = $mileage;
$formatted_mileage =~ s/(?<=\d)(?=(?:\d\d\d)+\b)/,/g;
print HTML_OUTPUT_FILE "<tr>\n";
print HTML_OUTPUT_FILE "<td width=\"1%\" align=\"center\">",$loopIteration+1,"</td>\n";
print HTML_OUTPUT_FILE "<td width=\"1%\" align=\"center\" bgcolor=\"#F3F781\"><input type=\"checkbox\" name=\"cust_",$loopIteration,"_cb\" value=\"yes\" checked></td>\n";
print HTML_OUTPUT_FILE "<td width=\"7%\" align=\"center\" bgcolor=\"#04B431\"><label for=\"months\"></label><select id=\"months\" name=\"cust_",$loopIteration,"_product_months\"><option value=\"3\">3</option><option value=\"12\">12</option><option value=\"18\">18</option><option value=\"24\">24</option><option value=\"36\">36</option><option value=\"48\">48</option><option value=\"60\">60</option></select></td>\n";
print HTML_OUTPUT_FILE "<td width=\"7%\" align=\"center\" bgcolor=\"#04B431\"><label for=\"mileage\"></label><select id=\"mileage\" name=\"cust_",$loopIteration,"_product_mileage\"><option value=\"12000\">12,000</option><option value=\"18000\">18,000</option><option value=\"24000\">24,000</option><option value=\"36000\">36,000</option><option value=\"48000\">48,000</option><option value=\"50000\">50,000</option><option value=\"60000\">60,000</option></select></td>\n";
print HTML_OUTPUT_FILE "<td width=\"7%\" align=\"center\" bgcolor=\"#04B431\"><label for=\"deductible\"></label><select id=\"deductible\" name=\"cust_",$loopIteration,"_product_deductible\"><option value=\"0\">\$0</option><option value=\"50\">\$50</option><option value=\"100\">\$100</option><option value=\"200\">\$200</option></select></td>\n";
print HTML_OUTPUT_FILE "<td width=\"7%\" align=\"center\" bgcolor=\"#04B431\"><label for=\"high_mileage\"></label><select id=\"high_mileage\" name=\"cust_",$loopIteration,"_high_mileage\"><option value=\"No\">No</option><option value=\"Yes\">Yes</option></select></td>\n";
#print HTML_OUTPUT_FILE "<td width=\"4%\" align=\"center\" bgcolor=\"#C89600\"><input type=\"checkbox\" name=\"cust_",$loopIteration,"_high_mileage\" value=\"yes\"></td>\n";
print HTML_OUTPUT_FILE "<td width=\"7%\" align=\"center\">",$saledate,"</td>\n";
print HTML_OUTPUT_FILE "<td align=\"center\">",$vin,"</td>\n";
print HTML_OUTPUT_FILE "<td align=\"left\">",$formatted_mileage,"</td>\n";
print HTML_OUTPUT_FILE "<td align=\"left\">",uc($firstname)," ",uc($lastname),"</td>\n";
print HTML_OUTPUT_FILE "<td align=\"center\">",$formatted_price,"</td>\n";
print HTML_OUTPUT_FILE "<td align=\"left\">",$vehicle,"</td>\n";
print HTML_OUTPUT_FILE "</tr>\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_vin\" value=\"",$vin,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_mileage\" value=\"",$mileage,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_firstname\" value=\"",$firstname,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_lastname\" value=\"",$lastname,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_address\" value=\"",$address,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_city\" value=\"",$city,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_state\" value=\"",$state,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_zip\" value=\"",$zip,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_saledate\" value=\"",$saledate,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_phone\" value=\"",$phone,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_price\" value=\"",$price,"\">\n";
print HTML_OUTPUT_FILE "<input type=\"hidden\" name=\"cust_",$loopIteration,"_vehicle\" value=\"",$vehicle,"\">\n";
$loopIteration++;
}
print HTML_OUTPUT_FILE "</table>\n";
print HTML_OUTPUT_FILE "<b>Number of Sales: <input type=\"text\" name=\"num_accounts\" value=\"",$loopIteration,"\" size=4 style=\"border:none\" readonly></b><br>\n";
print HTML_OUTPUT_FILE "<br><input type=\"submit\" value=\"Submit Accounts\" style=\"height:30px; width:150px\"><br><br><br>\n";
print HTML_OUTPUT_FILE "</form>\n";
print HTML_OUTPUT_FILE "</body>\n";
print HTML_OUTPUT_FILE "</html>\n";
close(AM_INPUT_FILE);
close(HTML_OUTPUT_FILE);
| familymcqueens/ProvidentAvpXpress | ProvidentAvp1.pl | Perl | apache-2.0 | 9,335 |
=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.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Analysis::Runnable::BestPmatch -
=head1 SYNOPSIS
=head1 DESCRIPTION
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::Runnable::BestPmatch;
use strict;
use warnings;
use Bio::EnsEMBL::Analysis::Runnable;
use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils qw(id coord_string);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::Analysis::Runnable);
sub new {
my ($class,@args) = @_;
my $self = $class->SUPER::new(@args);
my ($pafs, $min_coverage) = rearrange(['PROTEIN_HITS', 'MIN_COVERAGE'], @args);
###SETTING DEFAULTS###
$self->min_coverage(25);
#######################
$self->protein_hits($pafs);
$self->min_coverage($min_coverage);
return $self;
}
sub protein_hits{
my ($self, $ref) = @_;
if($ref){
if(ref($ref) ne "ARRAY"){
throw("Runnable::BestPmatch Must pass protein hits an array ref not ".$ref);
}
$self->{protein_hits} = $ref;
}
return $self->{protein_hits};
}
sub min_coverage{
my ($self, $arg) = @_;
if($arg){
$self->{'min_coverage'} = $arg;
}
return $self->{'min_coverage'};
}
sub protein_hash{
my ($self, $hash) = @_;
if(!$self->{'_proteins'}){
$self->{'_proteins'} = {};
}
if($hash){
throw("Must pass protein_hash a hashref not ".$hash)
if(ref($hash) ne 'HASH');
$self->{'_proteins'} = $hash;
}
return $self->{'_proteins'};
}
sub run{
my ($self) = @_;
my %prots;
foreach my $hit(@{$self->protein_hits}){
push (@{$prots{$hit->hseqname}}, $hit);
}
$self->protein_hash(\%prots);
my $hits = $self->prune_hits;
my %unique;
foreach my $hit(@$hits){
my $string = id($hit)."-".coord_string($hit);
if(!$unique{$string}){
$hit->analysis($self->analysis);
$unique{$string} = $hit;
}
}
my @output = values(%unique);
$self->output(\@output);
}
sub prune_hits{
my ($self, $hits) = @_;
$hits = $self->protein_hits if(!$hits);
my @chosen;
my %prots = %{$self->protein_hash};
PROTEIN:foreach my $p(keys(%{$self->protein_hash})){
my $allhits = $prots{$p};
my @sorted = sort {$b->score <=> $a->score} @$allhits;
my $first = shift(@sorted);
my $score_boundary = $first->score() - 2;
my $lower_threshold = $self->min_coverage;
next PROTEIN if $first->score < $lower_threshold;
push(@chosen, $first);
PRUNE:foreach my $hit(@sorted){
last PRUNE if($hit->score < $score_boundary);
last PRUNE if($hit->score < $lower_threshold);
push(@chosen, $hit);
}
}
return \@chosen;
}
1;
| mn1/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/BestPmatch.pm | Perl | apache-2.0 | 3,546 |
# OpenXPKI::Server::Workflow::Condition::WorkflowContextBulk
# Written by Martin Bartosch for the OpenXPKI project 2009
# Copyright (c) 2009 by The OpenXPKI Project
package OpenXPKI::Server::Workflow::Condition::WorkflowContextBulk;
use strict;
use warnings;
use base qw( Workflow::Condition );
use DateTime;
use Workflow::Exception qw( condition_error configuration_error );
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Debug;
use English;
use Data::Dumper;
my @parameters = qw(
context_keys
context_value
condition
);
__PACKAGE__->mk_accessors(@parameters);
sub _init {
my ( $self, $params ) = @_;
# propagate workflow condition parametrisation to our object
foreach my $arg (@parameters) {
if ( defined $params->{$arg} ) {
$self->$arg( $params->{$arg} );
}
}
if ( !( defined $self->context_keys() && defined $self->condition() ) ) {
##! 16: 'error: no conditions defined'
configuration_error
"Missing parameters in ",
"declaration of condition ", $self->name;
}
}
sub evaluate {
##! 1: 'start'
my ( $self, $workflow ) = @_;
my $context = $workflow->context();
my $pki_realm = CTX('session')->data->pki_realm;
my @keys = ();
foreach my $arg (@parameters) {
if ( $arg eq 'context_keys' ) {
@keys = split( /\s*,\s*/, $self->context_keys() );
}
else {
# access workflow context instead of literal value if value starts
# with a $
if ( defined $self->$arg()
&& ( $self->$arg() =~ m{ \A \$ (.*) }xms ) )
{
my $wf_key = $1;
$self->$arg( $context->param($wf_key) );
}
}
##! 64: 'param: ' . $arg . '; value: ' . $self->$arg()
}
# my $context_key = $self->context_key();
my $condition = $self->condition();
# my $ok = 1; # assume everything is ok, just one nok causes failure
if ( $condition eq 'exists' ) {
foreach my $context_key (@keys) {
my $context_value = $context->param($context_key);
if ( !defined $context_value ) {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_CONTEXT_VALUE_DOES_NOT_EXIST';
}
}
}
elsif ( $condition eq 'notnull' ) {
foreach my $context_key (@keys) {
my $context_value = $context->param($context_key);
if ( !defined $context_value || ( $context_value eq '' ) ) {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_CONTEXT_VALUE_EMPTY';
}
}
}
elsif ( $condition eq 'equals' ) {
if ( my $context_value_expected = $self->context_value() ) {
foreach my $context_key (@keys) {
my $context_value_got = $context->param($context_key);
if ( $context_value_got ne $context_value_expected ) {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_CONTEXT_EQUALITY_MISMATCH';
}
}
} else {
my $context_value_expected = $context->param($keys[0]);
for (my $i = 1; $i < scalar @keys; $i++) {
my $context_value_got = $context->param($keys[$i]);
if ( $context_value_got ne $context_value_expected ) {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_CONTEXT_EQUALITY_MISMATCH';
}
}
}
}
elsif ( $condition eq 'regex' ) {
foreach my $context_key (@keys) {
my $context_value = $context->param($context_key);
my $regex = qr/$self->context_value()/ms;
if ( $context_value =~ /$regex/ ) {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_CONTEXT_REGEX_MISMATCH';
}
}
}
else {
condition_error
'I18N_OPENXPKI_SERVER_WORKFLOW_CONDITION_WORKFLOWCONTEXT_INVALID_CONDITION';
}
return 1;
}
1;
__END__
=head1 NAME
OpenXPKI::Server::Workflow::Condition::WorkflowContextBulk
=head1 SYNOPSIS
<condition
name="private_key_not_empty"
class="OpenXPKI::Server::Workflow::Condition::WorkflowContextBulk">
<param name="context_keys" value="private_key1,private_key2,..."/>
<param name="condition" value="exists"/>
</condition>
<condition
name="profile_contains_encryption"
class="OpenXPKI::Server::Workflow::Condition::WorkflowContextBulk">
<param name="context_keys" value="cert_profile1,cert_profile2"/>
<param name="condition" value="regex"/>
<param name="context_value" value=".*ENCRYPTION.*"/>
</condition>
=head1 DESCRIPTION
Checks if the specified context entry exists, is not empty or matches
a given string or regex.
Parameters:
context_keys: checks are applied to this context key
condition: type of check: 'exists', 'notnull', 'regex', 'equals'
context_value: comparison value for regex or equals check
Note: if parameters specified start with a '$', the corresponding workflow
context parameter is referenced instead of the literal string.
Note: using the condition 'equals' when omitting the 'context_value' will
cause the values of the context parameters named in 'context_keys' to be
compared with each other.
| stefanomarty/openxpki | core/server/OpenXPKI/Server/Workflow/Condition/WorkflowContextBulk.pm | Perl | apache-2.0 | 5,563 |
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#
# vim: set ts=2 sw=2 tw=0:
# vim: set expandtab:
package Rex::Cron;
use strict;
use warnings;
our $VERSION = '0.56.1'; # VERSION
use Rex::Commands::Gather;
sub create {
my ($class) = @_;
my $type = "Linux";
if ( operating_system_is("SunOS") ) {
$type = "SunOS";
}
my $klass = "Rex::Cron::$type";
eval "use $klass;";
if ($@) {
die("Error creating cron class: $klass\n$@");
}
return $klass->new;
}
1;
| gitpan/Rex | lib/Rex/Cron.pm | Perl | apache-2.0 | 480 |
package Google::Ads::AdWords::v201809::CampaignService::CampaignServiceInterfacePort;
use strict;
use warnings;
use Class::Std::Fast::Storable;
use Scalar::Util qw(blessed);
use base qw(SOAP::WSDL::Client::Base);
# only load if it hasn't been loaded before
require Google::Ads::AdWords::v201809::TypeMaps::CampaignService
if not Google::Ads::AdWords::v201809::TypeMaps::CampaignService->can('get_class');
sub START {
$_[0]->set_proxy('https://adwords.google.com/api/adwords/cm/v201809/CampaignService') if not $_[2]->{proxy};
$_[0]->set_class_resolver('Google::Ads::AdWords::v201809::TypeMaps::CampaignService')
if not $_[2]->{class_resolver};
$_[0]->set_prefix($_[2]->{use_prefix}) if exists $_[2]->{use_prefix};
}
sub get {
my ($self, $body, $header) = @_;
die "get must be called as object method (\$self is <$self>)" if not blessed($self);
return $self->SUPER::call({
operation => 'get',
soap_action => '',
style => 'document',
body => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::get )],
},
header => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::RequestHeader )],
},
headerfault => {
}
}, $body, $header);
}
sub mutate {
my ($self, $body, $header) = @_;
die "mutate must be called as object method (\$self is <$self>)" if not blessed($self);
return $self->SUPER::call({
operation => 'mutate',
soap_action => '',
style => 'document',
body => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::mutate )],
},
header => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::RequestHeader )],
},
headerfault => {
}
}, $body, $header);
}
sub mutateLabel {
my ($self, $body, $header) = @_;
die "mutateLabel must be called as object method (\$self is <$self>)" if not blessed($self);
return $self->SUPER::call({
operation => 'mutateLabel',
soap_action => '',
style => 'document',
body => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::mutateLabel )],
},
header => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::RequestHeader )],
},
headerfault => {
}
}, $body, $header);
}
sub query {
my ($self, $body, $header) = @_;
die "query must be called as object method (\$self is <$self>)" if not blessed($self);
return $self->SUPER::call({
operation => 'query',
soap_action => '',
style => 'document',
body => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::query )],
},
header => {
'use' => 'literal',
namespace => 'http://schemas.xmlsoap.org/wsdl/soap/',
encodingStyle => '',
parts => [qw( Google::Ads::AdWords::v201809::CampaignService::RequestHeader )],
},
headerfault => {
}
}, $body, $header);
}
1;
__END__
=pod
=head1 NAME
Google::Ads::AdWords::v201809::CampaignService::CampaignServiceInterfacePort - SOAP Interface for the CampaignService Web Service
=head1 SYNOPSIS
use Google::Ads::AdWords::v201809::CampaignService::CampaignServiceInterfacePort;
my $interface = Google::Ads::AdWords::v201809::CampaignService::CampaignServiceInterfacePort->new();
my $response;
$response = $interface->get();
$response = $interface->mutate();
$response = $interface->mutateLabel();
$response = $interface->query();
=head1 DESCRIPTION
SOAP Interface for the CampaignService web service
located at https://adwords.google.com/api/adwords/cm/v201809/CampaignService.
=head1 SERVICE CampaignService
=head2 Port CampaignServiceInterfacePort
=head1 METHODS
=head2 General methods
=head3 new
Constructor.
All arguments are forwarded to L<SOAP::WSDL::Client|SOAP::WSDL::Client>.
=head2 SOAP Service methods
Method synopsis is displayed with hash refs as parameters.
The commented class names in the method's parameters denote that objects
of the corresponding class can be passed instead of the marked hash ref.
You may pass any combination of objects, hash and list refs to these
methods, as long as you meet the structure.
List items (i.e. multiple occurences) are not displayed in the synopsis.
You may generally pass a list ref of hash refs (or objects) instead of a hash
ref - this may result in invalid XML if used improperly, though. Note that
SOAP::WSDL always expects list references at maximum depth position.
XML attributes are not displayed in this synopsis and cannot be set using
hash refs. See the respective class' documentation for additional information.
=head3 get
Returns the list of campaigns that meet the selector criteria. @param serviceSelector the selector specifying the {@link Campaign}s to return. @return A list of campaigns. @throws ApiException if problems occurred while fetching campaign information.
Returns a L<Google::Ads::AdWords::v201809::CampaignService::getResponse|Google::Ads::AdWords::v201809::CampaignService::getResponse> object.
$response = $interface->get( {
serviceSelector => $a_reference_to, # see Google::Ads::AdWords::v201809::Selector
},,
);
=head3 mutate
Adds, updates, or removes campaigns. <p class="note"><b>Note:</b> {@link CampaignOperation} does not support the <code>REMOVE</code> operator. To remove a campaign, set its {@link Campaign#status status} to {@code REMOVED}.</p> @param operations A list of unique operations. The same campaign cannot be specified in more than one operation. @return The list of updated campaigns, returned in the same order as the <code>operations</code> array. @throws ApiException if problems occurred while updating campaign information.
Returns a L<Google::Ads::AdWords::v201809::CampaignService::mutateResponse|Google::Ads::AdWords::v201809::CampaignService::mutateResponse> object.
$response = $interface->mutate( {
operations => $a_reference_to, # see Google::Ads::AdWords::v201809::CampaignOperation
},,
);
=head3 mutateLabel
Adds labels to the {@linkplain Campaign campaign} or removes {@linkplain Label label}s from the {@linkplain Campaign campaign}. <p>Add - Apply an existing label to an existing {@linkplain Campaign campaign}. The {@code campaignId} must reference an existing {@linkplain Campaign}. The {@code labelId} must reference an existing {@linkplain Label label}. <p>Remove - Removes the link between the specified {@linkplain Campaign campaign} and {@linkplain Label label}. @param operations the operations to apply. @return a list of {@linkplain CampaignLabel}s where each entry in the list is the result of applying the operation in the input list with the same index. For an add operation, the returned CampaignLabel contains the CampaignId and the LabelId. In the case of a remove operation, the returned CampaignLabel will only have CampaignId. @throws ApiException when there are one or more errors with the request.
Returns a L<Google::Ads::AdWords::v201809::CampaignService::mutateLabelResponse|Google::Ads::AdWords::v201809::CampaignService::mutateLabelResponse> object.
$response = $interface->mutateLabel( {
operations => $a_reference_to, # see Google::Ads::AdWords::v201809::CampaignLabelOperation
},,
);
=head3 query
Returns the list of campaigns that match the query. @param query The SQL-like AWQL query string. @return A list of campaigns. @throws ApiException if problems occur while parsing the query or fetching campaign information.
Returns a L<Google::Ads::AdWords::v201809::CampaignService::queryResponse|Google::Ads::AdWords::v201809::CampaignService::queryResponse> object.
$response = $interface->query( {
query => $some_value, # string
},,
);
=head1 AUTHOR
Generated by SOAP::WSDL on Thu Sep 20 11:08:49 2018
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/CampaignService/CampaignServiceInterfacePort.pm | Perl | apache-2.0 | 9,165 |
# 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::ConversionActionCountingTypeEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
ONE_PER_CLICK => "ONE_PER_CLICK",
MANY_PER_CLICK => "MANY_PER_CLICK"
];
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Enums/ConversionActionCountingTypeEnum.pm | Perl | apache-2.0 | 859 |
=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 Bio::EnsEMBL::Production::Pipeline::FileDump::Assembly_Chain;
use strict;
use warnings;
use feature 'say';
use base qw(Bio::EnsEMBL::Production::Pipeline::FileDump::Base_Filetype);
use File::Spec::Functions qw/catdir/;
use JSON;
use Path::Tiny;
sub param_defaults {
my ($self) = @_;
return {
%{$self->SUPER::param_defaults},
data_type => 'assembly_mapping',
file_type => 'chain',
ucsc => 1,
};
}
sub fetch_input {
my ($self) = @_;
my $overwrite = $self->param_required('overwrite');
my $output_dir = $self->param_required('output_dir');
my $data_type = $self->param_required('data_type');
my $chain_dir = catdir($output_dir, $data_type);
if (-e $chain_dir) {
if (! $overwrite) {
$self->complete_early('Files exist and will not be overwritten');
}
}
$self->param('chain_dir', $chain_dir);
}
sub run {
my ($self) = @_;
my $file_type = $self->param_required('file_type');
my $web_dir = $self->param_required('web_dir');
my $species_name = $self->param_required('species_name');
my $chain_dir = $self->param_required('chain_dir');
my $dba = $self->dba;
my $liftovers = $self->liftover_config($dba);
if (scalar(@{$liftovers})) {
path($chain_dir)->mkpath();
$self->param('ucsc_name_cache', {});
foreach my $liftover (@{$liftovers}) {
my ($from, $to) = @$liftover;
my $filename = $self->generate_custom_filename(
$chain_dir, "${from}_to_${to}", $file_type);
if (defined $filename) {
my $mappings = $self->liftover_mappings($dba, $from, $to);
if (scalar(@$mappings)) {
$self->write_mappings($dba, $from, $to, $mappings, $filename);
}
}
my $reverse_filename = $self->generate_custom_filename(
$chain_dir, "${to}_to_${from}", $file_type);
if (defined $reverse_filename) {
my $reverse_mappings = $self->reverse_liftover_mappings($dba, $from, $to);
if (scalar(@$reverse_mappings)) {
$self->write_mappings($dba, $to, $from, $reverse_mappings, $reverse_filename);
}
}
}
} else {
$self->complete_early('Species does not have liftover mappings');
}
$dba->dbc->disconnect_if_idle();
}
sub liftover_config {
my ($self, $dba) = @_;
my $mca = $dba->get_adaptor('MetaContainer');
my $mappings = $mca->list_value_by_key('liftover.mapping');
return [ map { $_ =~ /.+:(.+)#.+:(.+)/; [$1, $2] } @{$mappings} ];
}
sub liftover_mappings {
my ($self, $dba, $from, $to) = @_;
my $sql = get_sql(
['sr1.name as asm_name',
'sr1.length as asm_length',
'sr2.name as cmp_name',
'sr2.length as cmp_length',
'asm.asm_start',
'asm.asm_end',
'asm.cmp_start',
'asm.cmp_end'
],
'order by cs2.version, sr2.name, asm.cmp_start'
);
return $dba->dbc->sql_helper->execute(
-SQL => $sql,
-PARAMS => [$from, $to],
-USE_HASHREFS => 1
);
}
sub reverse_liftover_mappings {
my ($self, $dba, $from , $to) = @_;
my $sql = get_sql(
['sr1.name as cmp_name',
'sr1.length as cmp_length',
'sr2.name as asm_name',
'sr2.length as asm_length',
'asm.cmp_start as asm_start',
'asm.cmp_end as asm_end',
'asm.asm_start as cmp_start',
'asm.asm_end as cmp_end'
],
'order by cs2.version, sr2.name, asm.cmp_start'
);
return $dba->dbc->sql_helper->execute(
-SQL => $sql,
-PARAMS => [$from, $to],
-USE_HASHREFS => 1
);
}
sub get_sql {
my ($columns, $order_by) = @_;
my $select = join(q{, },
@{$columns},
'asm.ori',
'(asm.asm_end - asm.asm_start)+1 as length'
);
my $sql = qq/
SELECT ${select} FROM
coord_system cs1 INNER JOIN
seq_region sr1 ON (cs1.coord_system_id = sr1.coord_system_id) INNER JOIN
assembly asm ON (sr1.seq_region_id = asm.asm_seq_region_id) INNER JOIN
seq_region sr2 ON (sr2.seq_region_id = asm.cmp_seq_region_id) INNER JOIN
coord_system cs2 ON (sr2.coord_system_id = cs2.coord_system_id)
WHERE cs1.version = ? AND cs2.version = ?
$order_by
/;
return $sql;
}
sub write_mappings {
my ($self, $dba, $from, $to, $mappings, $filename) = @_;
my $chains = $self->build_chain_mappings($mappings);
my $ucsc_chains = [];
if ($self->param('ucsc')) {
$ucsc_chains = $self->create_ucsc_chains($dba, $chains);
}
my $fh = path($filename)->filehandle('>');
print_chains($self, $fh, $chains);
print_chains($self, $fh, $ucsc_chains) if @{$ucsc_chains};
}
sub build_chain_mappings {
my ($self, $assembly_mappings) = @_;
my @chain_mappings;
my ($t_name, $t_size, $t_strand, $t_start, $t_end);
my ($q_name, $q_size, $q_strand, $q_start, $q_end);
my $chain_id = 1;
my @chain_gaps;
my $length = scalar(@{$assembly_mappings});
for (my $i = 0; $i < $length; $i++) {
my $current = $assembly_mappings->[$i];
my $next = ($i+1 != $length) ? $assembly_mappings->[$i+1] : undef;
my $ori = $current->{ori};
my ($asm_diff, $cmp_diff);
if($next) {
$asm_diff = ($next->{asm_start} - $current->{asm_end})-1;
# Rev strands means the next cmp region has a lower start than the
# current end (because it's running in reverse). Rember length in 1-based
# coords always is (high-low)-1
$cmp_diff = ($ori == 1) ? ($next->{cmp_start} - $current->{cmp_end})-1 : ($current->{cmp_start} - $next->{cmp_end})-1;
}
if(! $t_name) {
# Reset variables to current
@chain_gaps = ();
$chain_id++;
($t_name, $t_size, $t_strand, $t_start) = ($current->{asm_name}, $current->{asm_length}, 1, $current->{asm_start});
($q_name, $q_size, $q_strand) = ($current->{cmp_name}, $current->{cmp_length}, $current->{ori});
$q_start = ($ori == 1) ? $current->{cmp_start} : $current->{cmp_end};
}
# Block that decides we need to start a new chain definition
# Can mean we have run out of mappings, we are into a new chromsome (both source and target)
# or strand has swapped.
# Final reason is we've had an out-of-order meaning a negative gap was produced
# (we're going backwards). In any situation this means the chain is finished
if( ! defined $next ||
$t_name ne $next->{asm_name} ||
$q_name ne $next->{cmp_name} || # we can switch target chromosomes. e.g. cross chromsome mappings in mouse NCBI37->GRCm38
$ori != $next->{ori} ||
$asm_diff < 0 ||
$cmp_diff < 0) {
# Add the last gap on which is just the length of this alignment
push(@chain_gaps, [$current->{length}]);
# Set the ends of the chain since this is the last block
$t_end = $current->{asm_end};
$q_end = ($ori == 1) ? $current->{cmp_end} : $current->{cmp_start};
#If strand was negative we need to represent all data as reverse complemented regions
if($q_strand == -1) {
$q_start = ($q_size - $q_start)+1;
$q_end = ($q_size - $q_end)+1;
}
# Convert to UCSC formats (0-based half-open intervals and +/- strands)
$t_start--;
$q_start--;
$t_strand = ($t_strand == 1) ? '+' : '-';
$q_strand = ($q_strand == 1) ? '+' : '-';
# Store the chain
my $chain_score = 1;
push(@chain_mappings, {
header => ['chain', $chain_score, $t_name, $t_size, $t_strand, $t_start, $t_end, $q_name, $q_size, $q_strand, $q_start, $q_end, $chain_id],
gaps => [@chain_gaps]
});
if(! defined $next) {
last;
}
# Clear variables
($t_name, $t_size, $t_strand, $t_start) = ();
($q_name, $q_size, $q_strand, $q_start) = ();
}
push(@chain_gaps, [$current->{length}, $asm_diff, $cmp_diff]);
}
return \@chain_mappings;
}
sub create_ucsc_chains {
my ($self, $dba, $chains) = @_;
my @new_chains;
foreach my $chain_def (@{$chains}) {
my $ensembl_name = $chain_def->{header}->[2];
my $target_name = $self->ensembl_to_ucsc_name($dba, $ensembl_name);
next if $ensembl_name eq $target_name;
my $new_chain_def = decode_json(encode_json($chain_def)); # quick clone
$new_chain_def->{header}[2] = $target_name;
push(@new_chains, $new_chain_def);
}
return \@new_chains;
}
sub ensembl_to_ucsc_name {
my ($self, $dba, $ensembl_name) = @_;
my $ucsc_name_cache = $self->param('ucsc_name_cache');
return $$ucsc_name_cache{$ensembl_name} if exists $$ucsc_name_cache{$ensembl_name};
my $ucsc_name = $ensembl_name;
my $slice = $dba->get_adaptor('Slice')->fetch_by_region(undef, $ensembl_name);
my $synonyms = $slice->get_all_synonyms('UCSC');
if (@{$synonyms}) {
$ucsc_name = $synonyms->[0]->name();
} else {
if ($slice->is_chromosome) {
if ($ensembl_name eq 'MT') {
$ucsc_name = 'chrM';
} elsif ($slice->is_reference) {
$ucsc_name = 'chr'.$ensembl_name;
}
}
}
$$ucsc_name_cache{$ensembl_name} = $ucsc_name;
$self->param('ucsc_name_cache', $ucsc_name_cache);
return $ucsc_name;
}
sub print_chains {
my ($self, $fh, $chains) = @_;
while(my $chain_def = shift @{$chains}) {
my $header = $chain_def->{header};
my $gaps = $chain_def->{gaps};
say $fh join(q{ }, @{$header});
foreach my $gap (@{$gaps}) {
say $fh join(q{ }, @{$gap});
}
print $fh "\n";
}
}
1;
| Ensembl/ensembl-production | modules/Bio/EnsEMBL/Production/Pipeline/FileDump/Assembly_Chain.pm | Perl | apache-2.0 | 10,016 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
# Ensembl module for Bio::EnsEMBL::Variation::DBSQL::VariationFeatureAdaptor
#
#
=head1 NAME
Bio::EnsEMBL::Variation::DBSQL::VariationFeatureAdaptor
=head1 SYNOPSIS
$registry = 'Bio::EnsEMBL::Registry';
$registry->load_registry_from_db(-host => 'ensembldb.ensembl.org', -user => 'anonymous');
my $vfa = $registry->get_adaptor('human', 'variation', 'variationfeature');
my $sa = $registry->get_adaptor('human', 'core', 'slice');
my $va = $registry->get_adaptor('human', 'variation', 'variation');
# Get a VariationFeature by its internal identifier
my $vf = $va->fetch_by_dbID(145);
# Include the variations that have been flagged as failed
$vfa->db->include_failed_variations(1);
# Get all VariationFeatures in a region
my $slice = $sa->fetch_by_region('chromosome', 'X', 1e6, 2e6);
foreach my $vf ( @{ $vfa->fetch_all_by_Slice($slice) } ) {
print $vf->start(), '-', $vf->end(), ' ', $vf->allele_string(), "\n";
}
# Fetch all genome hits for a particular variation
my $v = $va->fetch_by_name('rs56');
foreach my $vf ( @{ $vfa->fetch_all_by_Variation($v) } ) {
print $vf->seq_region_name(), $vf->seq_region_start(), '-',
$vf->seq_region_end(), "\n";
}
=head1 DESCRIPTION
This adaptor provides database connectivity for VariationFeature objects.
Genomic locations of variations can be obtained from the database using this
adaptor. See the base class BaseFeatureAdaptor for more information.
By default, the 'fetch_all_by_...'-methods will not return variations
that have been flagged as failed in the Ensembl QC. This behaviour can be modified
by setting the include_failed_variations flag in Bio::EnsEMBL::Variation::DBSQL::DBAdaptor.
=head1 METHODS
=cut
use strict;
use warnings;
package Bio::EnsEMBL::Variation::DBSQL::VariationFeatureAdaptor;
use Bio::EnsEMBL::Variation::Allele;
use Bio::EnsEMBL::Variation::VariationFeature;
use Bio::EnsEMBL::Variation::DBSQL::BaseAdaptor;
use Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor;
use Bio::EnsEMBL::Utils::Scalar qw(assert_ref);
use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp);
use Bio::EnsEMBL::Utils::Exception qw(throw deprecate warning);
use Bio::EnsEMBL::Utils::Iterator;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Variation::Utils::Constants qw(%OVERLAP_CONSEQUENCES);
use Bio::EnsEMBL::Variation::Utils::Sequence qw(get_hgvs_alleles trim_sequences);
use Bio::SeqUtils;
our @ISA = ('Bio::EnsEMBL::Variation::DBSQL::BaseAdaptor', 'Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor');
our $MAX_VARIATION_SET_ID = 64;
our $DEBUG =0;
## Used for the itterator function
my $DEFAULT_ITERATOR_CACHE_SIZE = 10_000;
sub store {
my ($self, $vf) = @_;
my $dbh = $self->dbc->db_handle;
# look up source_id
if(!defined($vf->{_source_id})) {
my $sth = $dbh->prepare(q{
SELECT source_id FROM source WHERE name = ?
});
$sth->execute($vf->{source}->name);
my $source_id;
$sth->bind_columns(\$source_id);
$sth->fetch();
$sth->finish();
$vf->{_source_id} = $source_id;
}
if( defined $vf->{evidence}){
## store these by attrib id to allow differnt values in different species
my $aa = $self->db->get_AttributeAdaptor;
foreach my $ev_term( @{$vf->{evidence}} ){
my $ev_class_id = $aa->attrib_id_for_type_value('evidence',$ev_term);
push @{$vf->{evidence_attribs}}, $ev_class_id;
}
}
throw("No source ID found for source name ", $vf->{source}->name)
unless defined($vf->{_source_id});
my $sth = $dbh->prepare(q{
INSERT INTO variation_feature (
seq_region_id,
seq_region_start,
seq_region_end,
seq_region_strand,
variation_id,
allele_string,
variation_name,
map_weight,
flags,
source_id,
consequence_types,
variation_set_id,
class_attrib_id,
somatic,
minor_allele,
minor_allele_freq,
minor_allele_count,
alignment_quality,
evidence_attribs
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
});
$sth->execute(
defined($vf->{seq_region_id}) ? $vf->{seq_region_id} : $vf->slice->get_seq_region_id,
$vf->{slice} ? $vf->seq_region_start : $vf->{start},
$vf->{slice} ? $vf->seq_region_end : $vf->{end},
$vf->strand,
$vf->variation ? $vf->variation->dbID : $vf->{_variation_id},
$vf->allele_string,
$vf->variation_name,
$vf->map_weight || 1,
$vf->{flags},
$vf->{source} ? $vf->{source}->dbID : $vf->{_source_id},
$vf->{slice} ? (join ",", @{$vf->consequence_type('SO')}) : 'intergenic_variant',
$vf->{variation_set_id} || '',
$vf->{class_attrib_id} || ( $vf->{class_SO_term} && $self->db->get_AttributeAdaptor->attrib_id_for_type_value('SO_term', $vf->{class_SO_term}) ) || 18,
$vf->is_somatic,
$vf->minor_allele,
$vf->minor_allele_frequency,
$vf->minor_allele_count,
$vf->flank_match,
$vf->{evidence_attribs} ? (join ",", @{$vf->{evidence_attribs}}) : undef
);
$sth->finish;
# get dbID
my $dbID = $dbh->last_insert_id(undef, undef, 'variation_feature', 'variation_feature_id');
$vf->{dbID} = $dbID;
$vf->{adaptor} = $self;
}
=head2 update
Arg [1] : Bio::EnsEMBL:VariationFeature
Example : $variation_feature_adaptor->update( $variation_feature )};
Description: Updates the given $variation_feature in the database,
storing ancy changes that may have been made.
Returntype : Bool
Exceptions :
Caller :
Status : Experimental
=cut
sub update {
my ($self, $vf) = @_;
my $dbh = $self->dbc->db_handle;
# look up source_id
if(!defined($vf->{_source_id})) {
my $sth = $dbh->prepare(q{
SELECT source_id FROM source WHERE name = ?
});
$sth->execute($vf->{source}->name);
my $source_id;
$sth->bind_columns(\$source_id);
$sth->fetch();
$sth->finish();
$vf->{_source_id} = $source_id;
}
throw("No source ID found for source name ", $vf->{source}->name)
unless defined($vf->{_source_id});
my $sth = $dbh->prepare(q{
UPDATE variation_feature SET
seq_region_id = ?,
seq_region_start = ?,
seq_region_end = ?,
seq_region_strand = ?,
variation_id = ?,
allele_string = ?,
variation_name = ?,
map_weight = ?,
flags = ?,
source_id = ?,
consequence_types = ?,
variation_set_id = ?,
class_attrib_id = ?,
somatic = ?,
minor_allele = ?,
minor_allele_freq = ?,
minor_allele_count = ?,
alignment_quality = ?
WHERE variation_feature_id = ?
});
$sth->execute(
defined($vf->{seq_region_id}) ?
$vf->{seq_region_id} : $vf->slice->get_seq_region_id,
$vf->{slice} ? $vf->seq_region_start : $vf->{start},
$vf->{slice} ? $vf->seq_region_end : $vf->{end},
$vf->strand,
$vf->variation ? $vf->variation->dbID : $vf->{_variation_id},
$vf->allele_string,
$vf->variation_name,
$vf->map_weight || 1,
$vf->{flags},
$vf->{source} ? $vf->{source}->dbID : $vf->{_source_id},
$vf->{slice} ?
(join ",", @{$vf->consequence_type('SO')}) : 'intergenic_variant',
$vf->{variation_set_id} || '',
$vf->{class_attrib_id} ||
$vf->adaptor->db->get_AttributeAdaptor->
attrib_id_for_type_value('SO_term', $vf->{class_SO_term}) || 18,
$vf->is_somatic,
$vf->minor_allele,
$vf->minor_allele_frequency,
$vf->minor_allele_count,
$vf->flank_match,
$vf->dbID
);
$sth->finish;
}
=head2 fetch_all
Description: Returns a listref of all germline variation features
Returntype : listref of VariationFeatures
Status : Stable
=cut
sub fetch_all {
my $self = shift;
my $constraint = 'vf.somatic = 0';
return $self->generic_fetch($constraint);
}
=head2 fetch_all_somatic
Description: Returns a listref of all somatic variation features
Returntype : listref of VariationFeatures
Status : Stable
=cut
sub fetch_all_somatic {
my $self = shift;
my $constraint = 'vf.somatic = 1';
return $self->generic_fetch($constraint);
}
=head2 fetch_all_by_Slice_constraint
Arg [1] : Bio::EnsEMBL::Slice $slice
the slice from which to obtain features
Arg [2] : (optional) string $constraint
An SQL query constraint (i.e. part of the WHERE clause)
Description: Returns a listref of germline variation features created
from the database which are on the Slice defined by $slice
and fulfill the SQL constraint defined by $constraint.
Returntype : listref of VariationFeatures
Exceptions : thrown if $slice is not defined
Caller : Bio::EnsEMBL::Slice
Status : Stable
=cut
sub fetch_all_by_Slice_constraint {
my ($self, $slice, $constraint) = @_;
# by default, filter out somatic mutations
my $somatic_constraint = 'vf.somatic = 0';
if ($constraint) {
$constraint .= " AND $somatic_constraint";
}
else {
$constraint = $somatic_constraint;
}
# Add the constraint for failed variations
$constraint .= " AND vf.display = 1 " unless $self->db->include_failed_variations();
return $self->SUPER::fetch_all_by_Slice_constraint($slice, $constraint);
}
sub fetch_all_by_Slice_constraint_with_Variations {
my $self = shift;
$self->{_get_variations} = 1;
my $vfs = $self->fetch_all_by_Slice_constraint(@_);
$self->{_get_variations} = 0;
return $vfs;
}
sub fetch_all_by_Slice_constraint_with_TranscriptVariations {
my $self = shift;
$self->{_get_transcript_variations} = 1;
my $vfs = $self->fetch_all_by_Slice_constraint(@_);
$self->{_get_transcript_variations} = 0;
return $vfs;
}
sub fetch_all_somatic_by_Slice_constraint_with_TranscriptVariations {
my $self = shift;
$self->{_get_transcript_variations} = 1;
my $vfs = $self->fetch_all_somatic_by_Slice_constraint(@_);
$self->{_get_transcript_variations} = 0;
return $vfs;
}
=head2 fetch_all_somatic_by_Slice_constraint
Arg [1] : Bio::EnsEMBL::Slice $slice
the slice from which to obtain features
Arg [2] : (optional) string $constraint
An SQL query constraint (i.e. part of the WHERE clause)
Description: Returns a listref of somatic variation features created
from the database which are on the Slice defined by $slice
and fulfill the SQL constraint defined by $constraint.
Returntype : listref of VariationFeatures
Exceptions : thrown if $slice is not defined
Caller : Bio::EnsEMBL::Slice
Status : Stable
=cut
sub fetch_all_somatic_by_Slice_constraint {
my ($self, $slice, $constraint) = @_;
my $somatic_constraint = 'vf.somatic = 1';
if ($constraint) {
$constraint .= " AND $somatic_constraint";
}
else {
$constraint = $somatic_constraint;
}
return $self->SUPER::fetch_all_by_Slice_constraint($slice, $constraint);
}
=head2 fetch_all_by_Slice
Arg [1] : Bio::EnsEMBL::Slice $slice
the slice from which to obtain features
Example : my $vfs = $vfa->fetch_all_by_Slice($slice);
Description: Retrieves all variation features on the given Slice.
NOTE: only germline variations will be returned, if you want
somatic mutations use the fetch_all_somatic_by_Slice method.
Returntype : listref of Bio::EnsEMBL::VariationFeatures
Exceptions : none
Caller : Bio::EnsEMBL::Slice
Status : Stable
=cut
sub fetch_all_by_Slice {
my ($self, $slice) = @_;
return $self->fetch_all_by_Slice_constraint($slice, '');
}
=head2 fetch_all_somatic_by_Slice
Arg [1] : Bio::EnsEMBL::Slice $slice
the slice from which to obtain features
Example : my $svfs = $vfa->fetch_all_somatic_by_Slice($slice);
Description: Retrieves a list of variation features representing somatic mutations on the given Slice.
Returntype : listref of Bio::EnsEMBL::VariationFeatures
Exceptions : none
Caller : Bio::EnsEMBL::Slice
Status : Stable
=cut
sub fetch_all_somatic_by_Slice {
my ($self, $slice) = @_;
return $self->fetch_all_somatic_by_Slice_constraint($slice, '');
}
=head2 fetch_all_somatic_by_Slice_Source
Arg [1] : Bio::EnsEMBL::Slice $slice the slice from which to obtain features
Arg [2] : Bio::EnsEMBL::Variation::Source $source only return somatic mutations for the given source
Example : my $vfs = $vfa->fetch_all_somatic_by_Slice_Source($slice, $source);
Description: Retrieves a list of variation features representing somatic mutations on the given Slice for a given source.
Returntype : listref of Bio::EnsEMBL::VariationFeatures
Exceptions : throw on incorrect argument
Caller : Bio::EnsEMBL::Slice
Status : Stable
=cut
sub fetch_all_somatic_by_Slice_Source {
my ($self, $slice, $source) = @_;
if (!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
if (!ref($source) || !$source->isa('Bio::EnsEMBL::Variation::Source')) {
throw('Bio::EnsEMBL::Variation::Source arg expected');
}
if (!$source->dbID()) {
warning("Source does not have dbID, cannot retrieve s variants");
return [];
}
my $constraint = 'vf.source_id = ' . $source->dbID;
return $self->fetch_all_somatic_by_Slice_constraint($slice, $constraint);
}
=head2 fetch_all_by_Variation
Arg [1] : Bio::EnsEMBL:Variation::Variation $var
Example : my @vfs = @{$vfa->fetch_all_by_Variation($var)};
Description: Retrieves all variation features for a given variation. Most
variations should only hit the genome once and only a return
a single variation feature.
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_by_Variation {
my $self = shift;
my $var = shift;
if(!ref($var) || !$var->isa('Bio::EnsEMBL::Variation::Variation')) {
throw('Bio::EnsEMBL::Variation::Variation arg expected');
}
if(!defined($var->dbID())) {
throw("Variation arg must have defined dbID");
}
return $self->generic_fetch("vf.variation_id = ".$var->dbID());
}
=head2 fetch_all_genotyped_by_Slice
Arg [1] : Bio::EnsEMBL:Variation::Slice $slice
Example : my @vfs = @{$vfa->fetch_all_genotyped_by_Slice($slice)};
Description: Retrieves all variation features that have been gentoyped for a given slice.
Most variations should only hit the genome once and only a return
a single variation feature.
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_genotyped_by_Slice{
my $self = shift;
my $slice = shift;
my $constraint = "vf.flags & 1 AND vf.somatic = 0";
#call the method fetch_all_by_Slice_constraint with the genotyped constraint
return $self->fetch_all_by_Slice_constraint($slice,$constraint);
}
sub _internal_fetch_all_with_phenotype_by_Slice{
my $self = shift;
my $slice = shift;
my $v_source = shift;
my $p_source = shift;
my $phenotype = shift;
my $constraint = shift;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
my $extra_sql = '';
my $extra_sql_in = '';
my $extra_table = '';
if(defined $v_source) {
$extra_sql .= qq{ AND s.name = '$v_source' };
}
if(defined $p_source) {
$extra_sql_in .= qq{ AND pf.source_id = ps.source_id AND ps.name = '$p_source' };
$extra_table .= qq{, source ps};
}
if(defined $phenotype) {
if($phenotype =~ /^[0-9]+$/) {
$extra_sql_in .= qq{ AND pf.phenotype_id = $phenotype };
}
else {
$extra_sql_in .= qq{ AND pf.phenotype_id = p.phenotype_id
AND (p.name = '$phenotype' OR p.description LIKE '%$phenotype%')
};
$extra_table .= qq{, phenotype p};
}
}
if ($constraint) {
$extra_sql .= qq{ AND $constraint };
}
# Add the constraint for failed variations
$extra_sql .= " AND vf.display = 1 " unless $self->db->include_failed_variations();
my $cols = join ",", $self->_columns();
my $sth = $self->prepare(qq{
SELECT $cols
FROM (variation_feature vf, phenotype_feature pf,
source s $extra_table) # need to link twice to source
WHERE vf.seq_region_id = pf.seq_region_id
AND vf.seq_region_start = pf.seq_region_start
AND vf.seq_region_end = pf.seq_region_end
AND vf.variation_name = pf.object_id
$extra_sql_in
AND vf.source_id = s.source_id
$extra_sql
AND vf.seq_region_id = ?
AND vf.seq_region_end >= ?
AND vf.seq_region_start <= ?
GROUP BY vf.variation_feature_id
});
$sth->execute($slice->get_seq_region_id, $slice->start, $slice->end);
return $self->_objs_from_sth($sth, undef, $slice);
}
=head2 fetch_all_with_maf_by_Slice
Arg [1] : Bio::EnsEMBL:Variation::Slice $slice
Arg [2] : float $threshold_frequency [optional]
Arg [3] : int $greater_than_threshold [optional]
Example : my @vfs = @{$vfa->fetch_all_with_maf_by_Slice($slice,$maximum_frequency)};
Description: Retrieves all germline variation features associated with a minor
allele frequency (MAF) for a given slice.
The optional $threshold_frequency argument can be used to
retrieve only variation features with a MAF lesser or equal than
$threshold_frequency will be returned by default.
To retrieve the MAF greater than the $threshold_frequency argument, the optional
flag $greater_than_threshold must me populated (with the value 1 for instance).
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_with_maf_by_Slice {
my $self = shift;
my ($slice, $freq, $greater_than_freq) = @_;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
my $maf_col = 'vf.minor_allele_freq';
# Add the MAF constraint
my $constraint = " $maf_col IS NOT NULL ";
# Add the MAF threshold constraint
if(defined $freq) {
# adjust frequency if given a percentage
$freq /= 100 if $freq > 1;
if ($freq > 0.5) {
throw("The maximum value of the minor allele frequency parameter should to be lesser than 0.5 (the value provided is $freq).");
}
my $operator = ($greater_than_freq) ? '>' : '<=';
$constraint .= " AND $maf_col $operator $freq ";
}
# Add the constraint for failed variations
$constraint .= " AND vf.display = 1 " unless $self->db->include_failed_variations();
# Get the VariationFeatures by calling fetch_all_by_Slice_constraint
my $vfs = $self->fetch_all_by_Slice_constraint($slice,$constraint);
return $vfs;
}
=head2 fetch_all_with_phenotype_by_Slice
Arg [1] : Bio::EnsEMBL:Variation::Slice $slice
Arg [2] : $variation_feature_source [optional]
Arg [3] : $phenotype_source [optional]
Arg [4] : $phenotype_name [optional]
Example : my @vfs = @{$vfa->fetch_all_with_phenotype_by_Slice($slice)};
Description: Retrieves all germline variation features associated with phenotypes for
a given slice.
The optional $variation_feature_source argument can be used to
retrieve only variation features from a paricular source.
The optional $phenotype source argument can be used to
retrieve only variation features with phenotypes provided by
a particular source.
The optional $phenotype_name argument can
be used to retrieve only variation features associated with
that phenotype - this can also be a phenotype's dbID.
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_with_phenotype_by_Slice {
my $self = shift;
my ($slice, $v_source, $p_source, $phenotype) = @_;
my $constraint = 'vf.somatic = 0';
return $self->_internal_fetch_all_with_phenotype_by_Slice($slice, $v_source, $p_source, $phenotype, $constraint);
}
=head2 fetch_all_somatic_with_phenotype_by_Slice
Arg [1] : Bio::EnsEMBL:Variation::Slice $slice
Arg [2] : $variation_feature_source [optional]
Arg [3] : $phenotype_source [optional]
Arg [4] : $phenotype_name [optional]
Example : my @vfs = @{$vfa->fetch_all_somatic_with_phenotype_by_Slice($slice)};
Description: Retrieves all somatic variation features associated with phenotypes for
a given slice.
(see fetch_all_with_phenotype_by_Slice documentation for description of
the other parameters)
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_somatic_with_phenotype_by_Slice {
my $self = shift;
my ($slice, $v_source, $p_source, $phenotype) = @_;
my $constraint = 'vf.somatic = 1';
return $self->_internal_fetch_all_with_phenotype_by_Slice($slice, $v_source, $p_source, $phenotype, $constraint);
}
=head2 fetch_all_by_Slice_VariationSet
Arg [1] : Bio::EnsEMBL:Variation::Slice $slice
Arg [2] : Bio::EnsEMBL:Variation::VariationSet $set
Example : my @vfs =
@{$vfa->fetch_all_by_Slice_VariationSet($slice, $set)};
Description: Retrieves all variation features in a slice that belong to a
given variation set.
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on bad argument
Caller : general
Status : Stable
=cut
sub fetch_all_by_Slice_VariationSet{
my $self = shift;
my $slice = shift;
my $set = shift;
#$self->{_get_variations} = 1;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
if(!ref($set) || !$set->isa('Bio::EnsEMBL::Variation::VariationSet')) {
throw('Bio::EnsEMBL::Variation::VariationSet arg expected');
}
# fix for failed sets
my $failed = $self->db->include_failed_variations;
$self->db->include_failed_variations(1) if $failed == 0 && $set->name =~ /fail/;
#Get the bitvalue for this set and its subsets
my $bitvalue = $set->_get_bitvalue();
# Add a constraint to only return VariationFeatures having the primary keys of the supplied VariationSet or its subsets in the variation_set_id column
my $constraint = " vf.variation_set_id & $bitvalue ";
#Get the VariationFeatures by calling fetch_all_by_Slice_constraint
my $vfs = $self->fetch_all_by_Slice_constraint($slice,$constraint);
# restore failed fetch flag
$self->db->include_failed_variations($failed);
$self->{_get_variations} = 0;
return $vfs;
}
=head2 fetch_all_by_Slice_Population
Arg [1] : Bio::EnsEMBL::Slice
Arg [2] : Bio::EnsEMBL::Variation::Population
Arg [3] : $minimum_frequency (optional)
Example : $pop = $pop_adaptor->fetch_by_dbID(659);
$slice = $slice_adaptor->fetch_by_region("chromosome", 1, 1, 1e6);
@vfs = @{$vf_adaptor->fetch_all_by_Slice_Population($pop,$slice)};
Description: Retrieves all variation features in a slice which are stored for
a specified population. If $minimum_frequency is supplied, only
variations with a minor allele frequency (MAF) greater than
$minimum_frequency will be returned.
Returntype : listref of Bio::EnsEMBL::Variation::VariationFeature
Exceptions : throw on incorrect argument
Caller : general
Status : At Risk
=cut
sub fetch_all_by_Slice_Population {
my $self = shift;
my $slice = shift;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
my $pop = shift;
if(!ref($pop) || !$pop->isa('Bio::EnsEMBL::Variation::Population')) {
throw('Bio::EnsEMBL::Variation::Population arg expected');
}
# default to 5% frequency
my $freq = shift;
my $extra_sql = '';
if(defined $freq) {
# adjust frequency if given a percentage
$freq /= 100 if $freq > 1;
$extra_sql = qq{ AND (IF(a.frequency > 0.5, 1-a.frequency, a.frequency) > $freq) }
}
# Add the constraint for failed variations
$extra_sql .= " AND vf.display = 1 " unless $self->db->include_failed_variations();
my $cols = join ",", $self->_columns();
my $sth = $self->prepare(qq{
SELECT $cols
FROM (variation_feature vf, source s, allele a)
WHERE vf.source_id = s.source_id
AND vf.variation_id = a.variation_id
AND a.population_id = ?
$extra_sql
AND vf.seq_region_id = ?
AND vf.seq_region_end >= ?
AND vf.seq_region_start <= ?
GROUP BY a.variation_id
});
$sth->execute($pop->dbID, $slice->get_seq_region_id, $slice->start, $slice->end);
##### ALTERNATIVE USING SUB-QUERY - WORKS FOR MULTIALLELIC BUT TAKES FOREVER!!!
# my $cols = join ",", $self->_columns();
#
# my $sth = $self->prepare(qq{
# SELECT $cols
# FROM variation_feature vf, source s, allele a_outer
# WHERE
# vf.source_id = s.source_id AND
# vf.variation_id = a_outer.variation_id AND
# a_outer.population_id = ? AND
# a_outer.frequency > ? AND
# a_outer.frequency < 0.5 AND
# vf.seq_region_id = ? AND
# vf.seq_region_end >= ? AND
# vf.seq_region_start <= ? AND
# NOT EXISTS (
# SELECT
# *
# FROM
# allele a_inner
# WHERE
# a_inner.variation_id = a_outer.variation_id AND
# a_inner.population_id = a_outer.population_id AND
# a_inner.frequency < a_outer.frequency
# );
# });
#$sth->execute($pop->dbID, $freq, $slice->get_seq_region_id, $slice->start, $slice->end);
return $self->_objs_from_sth($sth, undef, $slice);
}
sub _internal_fetch_all_with_phenotype {
my ($self, $v_source, $p_source, $phenotype, $constraint) = @_;
my $extra_sql = '';
my $extra_table = '';
if(defined $v_source) {
$extra_sql .= qq{ AND s.name = '$v_source' };
}
if(defined $p_source) {
$extra_sql .= qq{ AND pf.source_id = ps.source_id AND ps.name = '$p_source' };
$extra_table .= qq{, source ps};
}
if(defined $phenotype) {
if($phenotype =~ /^[0-9]+$/) {
$extra_sql .= qq{ AND pf.phenotype_id = $phenotype };
}
else {
$extra_sql .= qq{ AND pf.phenotype_id = p.phenotype_id
AND (p.name = '$phenotype' OR p.description LIKE '%$phenotype%')
};
$extra_table .= qq{, phenotype p};
}
}
if ($constraint) {
$extra_sql .= qq{ AND $constraint };
}
# Add the constraint for failed variations
$extra_sql .= " AND vf.display = 1 " unless $self->db->include_failed_variations();
my $cols = join ",", $self->_columns();
my $sth = $self->prepare(qq{
SELECT $cols
FROM (variation_feature vf, phenotype_feature pf,
source s $extra_table) # need to link twice to source
WHERE vf.source_id = s.source_id
AND vf.seq_region_id = pf.seq_region_id
AND vf.seq_region_start = pf.seq_region_start
AND vf.seq_region_end = pf.seq_region_end
AND vf.variation_name = pf.object_id
$extra_sql
GROUP BY vf.variation_feature_id
});
$sth->execute;
return $self->_objs_from_sth($sth);
}
=head2 fetch_all_with_phenotype
Arg [1] : $variation_feature_source [optional]
Arg [2] : $phenotype_source [optional]
Arg [3] : $phenotype_name [optional]
Example : my @vfs = @{$vfa->fetch_all_with_phenotype('EGA', undef, 123)};
Description: Retrieves all germline variation features associated with the given phenotype
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Caller : webcode
Status : Experimental
=cut
sub fetch_all_with_phenotype {
my ($self, $v_source, $p_source, $phenotype, $constraint) = @_;
my $somatic_constraint = 'vf.somatic = 0';
if ($constraint) {
$constraint .= " AND $somatic_constraint";
}
else {
$constraint = $somatic_constraint;
}
return $self->_internal_fetch_all_with_phenotype($v_source, $p_source, $phenotype, $constraint);
}
=head2 fetch_all_somatic_with_phenotype
Arg [1] : $variation_feature_source [optional]
Arg [2] : $phenotype_source [optional]
Arg [3] : $phenotype_name [optional]
Example : my @vfs = @{$vfa->fetch_all_somatic_with_phenotype('COSMIC', undef, 807)};
Description: Retrieves all somatic variation features associated with the given phenotype
Returntype : reference to list Bio::EnsEMBL::Variation::VariationFeature
Caller : webcode
Status : Experimental
=cut
sub fetch_all_somatic_with_phenotype {
my ($self, $v_source, $p_source, $phenotype, $constraint) = @_;
my $somatic_constraint = 'vf.somatic = 1';
if ($constraint) {
$constraint .= " AND $somatic_constraint";
}
else {
$constraint = $somatic_constraint;
}
return $self->_internal_fetch_all_with_phenotype($v_source, $p_source, $phenotype, $constraint);
}
=head2 fetch_all_by_Slice_SO_terms
Arg [1] : Bio::EnsEMBL::Slice
Arg [2] : listref of SO terms
Description: Fetch all germline VariationFeatures on the given slice with
consequences with given SO terms
Returntype : listref of Bio::EnsEMBL::Variation::VariationFeatures
Status : At risk
=cut
sub fetch_all_by_Slice_SO_terms {
my ($self, $slice, $terms, $without_children, $included_so) = @_;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
if(!defined($terms) || scalar @$terms == 0) {
return $self->fetch_all_by_Slice($slice);
}
my $constraint = $self->_get_consequence_constraint($terms, $without_children, $included_so);
if (!$constraint) {
return [];
}
my $vfs = $self->fetch_all_by_Slice_constraint($slice,$constraint);
return $vfs;
}
=head2 fetch_all_somatic_by_Slice_SO_terms
Arg [1] : Bio::EnsEMBL::Slice
Arg [2] : listref of SO terms
Description: Fetch all somatic VariationFeatures on the given slice with
consequences with given SO terms
Returntype : listref of Bio::EnsEMBL::Variation::VariationFeatures
Status : At risk
=cut
sub fetch_all_somatic_by_Slice_SO_terms {
my ($self, $slice, $terms, $without_children, $included_so) = @_;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
if(!defined($terms) || scalar @$terms == 0) {
return $self->fetch_all_somatic_by_Slice($slice);
}
my $constraint = $self->_get_consequence_constraint($terms, $without_children, $included_so);
if (!$constraint) {
return [];
}
my $vfs = $self->fetch_all_somatic_by_Slice_constraint($slice,$constraint);
return $vfs;
}
=head2 fetch_all_by_Slice_VariationSet_SO_terms
Arg [1] : Bio::EnsEMBL::Slice
Arg [2] : Bio::EnsEMBL::Variation::VariationSet
Arg [3] : Optional listref of SO terms
Description: Fetch all VariationFeatures in the given set, on the given
slice, optionally with consequences with given SO terms
Returntype : listref of Bio::EnsEMBL::Variation::VariationFeatures
Status : At risk
=cut
sub fetch_all_by_Slice_VariationSet_SO_terms{
my ($self, $slice, $set, $terms, $without_children, $included_so) = @_;
if(!ref($slice) || !$slice->isa('Bio::EnsEMBL::Slice')) {
throw('Bio::EnsEMBL::Slice arg expected');
}
if( !ref($set) || !$set->isa('Bio::EnsEMBL::Variation::VariationSet')) {
throw('Bio::EnsEMBL::Variation::VariationSet arg expected');
}
if(!defined($terms) || scalar @$terms == 0 ) {
return $self->fetch_all_by_Slice_VariationSet($slice, $set);
}
my $constraint = $self->_get_consequence_constraint($terms, $without_children, $included_so);
# Get the bitvalue for this set and its subsets
my $bitvalue = $set->_get_bitvalue();
$constraint .= " and vf.variation_set_id & $bitvalue ";
my $vfs = $self->fetch_all_by_Slice_constraint($slice,$constraint);
return $vfs;
}
# call to method in BaseAdaptor
sub _get_consequence_constraint {
my $self = shift;
return $self->SUPER::_get_consequence_constraint('variation_feature', @_);
}
=head2 fetch_Iterator
Arg [1] : int $cache_size (optional)
Example : $var_iterator = $varf_adaptor->fetch_Iterator;
Description: returns an iterator over all variation features in the database
Returntype : Bio::EnsEMBL::Utils::Iterator
Exceptions : none
Caller : general
Status : Experimental
=cut
sub fetch_Iterator {
my ($self, $cache_size) = @_;
return $self->_generic_fetch_Iterator($cache_size);
}
sub _generic_fetch_Iterator {
my ($self, $cache_size, $constraint) = @_;
# prepare and execute a query to fetch all dbIDs
my $sth = $self->prepare(qq{
SELECT variation_feature_id
FROM variation_feature
});
$sth->execute;
my $varf_id;
$sth->bind_columns(\$varf_id);
# we probably can't fit all of these into memory at once though,
# so create an iterator that fetches $cache_size dbIDs from the
# statement handle at a time and then fetches these objects,
# storing them in a cache. We then return variation feature
# objects from this cache one by one, before filling it again if
# necessary
$cache_size ||= $DEFAULT_ITERATOR_CACHE_SIZE;
my @cache;
my $items_to_fetch = 1;
return Bio::EnsEMBL::Utils::Iterator->new(sub{
if (@cache == 0 && $items_to_fetch) {
# Our cache is empty, and there are still items to fetch, so
# fetch the next chunk of dbIDs and create objects from them
my @dbIDs;
my $item_count = 0;
while( $sth->fetch ) {
push @dbIDs, $varf_id;
if (++$item_count == $cache_size) {
# we have fetched a cache's worth of dbIDs, so
# flag that there are still items to fetch and
# last out of the loop
$items_to_fetch = 1;
last;
}
# If this is the last row, this flag will be 0 outside
# the loop
$items_to_fetch = 0;
}
$sth->finish unless $items_to_fetch;
# This looks tricky...
@cache = @{ $self->fetch_all_by_dbID_list(\@dbIDs) } if @dbIDs;
}
return shift @cache;
});
}
# method used by import VCF script
sub _fetch_all_by_coords {
my ($self, $seq_region_id, $start, $end, $somatic) = @_;
$somatic ||= 0;
return $self->generic_fetch(qq{
vf.seq_region_id = $seq_region_id AND
vf.seq_region_start = $start AND
vf.seq_region_end = $end AND
vf.somatic = $somatic
});
}
# method used by superclass to construct SQL
sub _tables {
my $self = shift;
my $dbc = $self->dbc;
my @tables;
if ($dbc->driver eq 'SQLite') {
@tables = (
[ 'variation_feature', 'vf'],
[ 'source', 's']
);
} else {
@tables = (
[ 'variation_feature', 'vf', 'IGNORE INDEX(consequence_type_idx)'],
[ 'source', 's']
);
}
return @tables;
}
sub _default_where_clause {
my $self = shift;
my $clause = 'vf.source_id = s.source_id';
$clause .= ' AND vf.display = 1 ' unless $self->db->include_failed_variations();
return $clause;
}
sub _columns {
return qw( vf.variation_feature_id vf.seq_region_id vf.seq_region_start
vf.seq_region_end vf.seq_region_strand vf.variation_id
vf.allele_string vf.variation_name vf.map_weight vf.source_id vf.somatic
vf.consequence_types vf.class_attrib_id
vf.minor_allele vf.minor_allele_freq vf.minor_allele_count vf.alignment_quality
vf.evidence_attribs vf.clinical_significance vf.display s.name);
}
sub _objs_from_sth {
my ($self, $sth, $mapper, $dest_slice) = @_;
#warn $sth->sql;
#
# This code is ugly because an attempt has been made to remove as many
# function calls as possible for speed purposes. Thus many caches and
# a fair bit of gymnastics is used.
#
my $sa = $self->db()->dnadb()->get_SliceAdaptor();
my $aa = $self->db->get_AttributeAdaptor;
my @features;
my %slice_hash;
my %sr_name_hash;
my %sr_cs_hash;
my ($variation_feature_id, $seq_region_id, $seq_region_start,
$seq_region_end, $seq_region_strand, $variation_id,
$allele_string, $variation_name, $map_weight, $source_id,
$is_somatic, $consequence_types, $class_attrib_id,
$minor_allele, $minor_allele_freq, $minor_allele_count, $last_vf_id,
$alignment_quality,$evidence_attribs,$clin_sig,$display, $source_name );
$sth->bind_columns(\$variation_feature_id, \$seq_region_id,
\$seq_region_start, \$seq_region_end, \$seq_region_strand,
\$variation_id, \$allele_string, \$variation_name,
\$map_weight, \$source_id, \$is_somatic,
\$consequence_types, \$class_attrib_id,
\$minor_allele, \$minor_allele_freq, \$minor_allele_count,
\$alignment_quality, \$evidence_attribs, \$clin_sig, \$display, \$source_name);
my $asm_cs;
my $cmp_cs;
my $asm_cs_vers;
my $asm_cs_name;
my $cmp_cs_vers;
my $cmp_cs_name;
if($mapper) {
$asm_cs = $mapper->assembled_CoordSystem();
$cmp_cs = $mapper->component_CoordSystem();
$asm_cs_name = $asm_cs->name();
$asm_cs_vers = $asm_cs->version();
$cmp_cs_name = $cmp_cs->name();
$cmp_cs_vers = $cmp_cs->version();
}
my $dest_slice_start;
my $dest_slice_end;
my $dest_slice_strand;
my $dest_slice_length;
if($dest_slice) {
$dest_slice_start = $dest_slice->start();
$dest_slice_end = $dest_slice->end();
$dest_slice_strand = $dest_slice->strand();
$dest_slice_length = $dest_slice->length();
}
my $finished = 0;
my $iterator = Bio::EnsEMBL::Utils::Iterator->new(sub{
return undef if $finished;
FEATURE: while( $sth->fetch ) {
# Skip if we are getting multiple rows because of the left join to failed variation
next if (defined($last_vf_id) && $last_vf_id == $variation_feature_id);
$last_vf_id = $variation_feature_id;
#get the slice object
my $slice = $slice_hash{"ID:".$seq_region_id};
if(!$slice) {
$slice = $sa->fetch_by_seq_region_id($seq_region_id);
$slice_hash{"ID:".$seq_region_id} = $slice;
$sr_name_hash{$seq_region_id} = $slice->seq_region_name();
$sr_cs_hash{$seq_region_id} = $slice->coord_system();
}
# remap the feature coordinates to another coord system
# if a mapper was provided
if($mapper) {
my $sr_name = $sr_name_hash{$seq_region_id};
my $sr_cs = $sr_cs_hash{$seq_region_id};
($sr_name,$seq_region_start,$seq_region_end,$seq_region_strand) =
$mapper->fastmap($sr_name, $seq_region_start, $seq_region_end,
$seq_region_strand, $sr_cs);
#skip features that map to gaps or coord system boundaries
next FEATURE if(!defined($sr_name));
#get a slice in the coord system we just mapped to
if($asm_cs == $sr_cs || ($cmp_cs != $sr_cs && $asm_cs->equals($sr_cs))) {
$slice = $slice_hash{"NAME:$sr_name:$cmp_cs_name:$cmp_cs_vers"} ||=
$sa->fetch_by_region($cmp_cs_name, $sr_name,undef, undef, undef,
$cmp_cs_vers);
} else {
$slice = $slice_hash{"NAME:$sr_name:$asm_cs_name:$asm_cs_vers"} ||=
$sa->fetch_by_region($asm_cs_name, $sr_name, undef, undef, undef,
$asm_cs_vers);
}
}
#
# If a destination slice was provided convert the coords
# If the dest_slice starts at 1 and is foward strand, nothing needs doing
#
if($dest_slice) {
if($dest_slice_start != 1 || $dest_slice_strand != 1) {
if($dest_slice_strand == 1) {
$seq_region_start = $seq_region_start - $dest_slice_start + 1;
$seq_region_end = $seq_region_end - $dest_slice_start + 1;
} else {
my $tmp_seq_region_start = $seq_region_start;
$seq_region_start = $dest_slice_end - $seq_region_end + 1;
$seq_region_end = $dest_slice_end - $tmp_seq_region_start + 1;
#$seq_region_strand *= -1;
}
#throw away features off the end of the requested slice
if($seq_region_end < 1 || $seq_region_start > $dest_slice_length) {
next FEATURE;
}
}
$slice = $dest_slice;
}
my @evidence;
if (defined($evidence_attribs)) {
my $aa = $self->db->get_AttributeAdaptor;
my @attrib_ids = split(/,/,$evidence_attribs);
foreach my $attrib_id (@attrib_ids){
my $evidence_value = $aa->attrib_value_for_id($attrib_id);
push @evidence, $evidence_value ;
}
}
my @clin_sig;
if (defined($clin_sig)) {
@clin_sig = split(/,/,$clin_sig );
}
#my $overlap_consequences = $self->_variation_feature_consequences_for_set_number($consequence_types);
my $overlap_consequences = [ map { $OVERLAP_CONSEQUENCES{$_} } split /,/, ($consequence_types || 'sequence_variant') ];
$seq_region_start = $seq_region_end if $seq_region_start == $seq_region_end + 2; ## patch problem fix
# consequence_types
return $self->_create_feature_fast('Bio::EnsEMBL::Variation::VariationFeature',
#push @features, Bio::EnsEMBL::Variation::VariationFeature->new_fast(
#if use new_fast, then do not need "-" infront of key, i.e 'start' => $seq_region_start,
{'start' => $seq_region_start,
'end' => $seq_region_end,
'strand' => $seq_region_strand,
'slice' => $slice,
'allele_string' => $allele_string,
'variation_name' => $variation_name,
'adaptor' => $self,
'dbID' => $variation_feature_id,
'map_weight' => $map_weight,
'_source_id' => $source_id,
'_source_name' => $source_name,
'is_somatic' => $is_somatic,
'overlap_consequences' => $overlap_consequences,
'_variation_id' => $variation_id,
'class_SO_term' => $aa->attrib_value_for_id($class_attrib_id),
'minor_allele' => $minor_allele,
'minor_allele_frequency' => $minor_allele_freq,
'minor_allele_count' => $minor_allele_count,
'flank_match' => $alignment_quality,
'evidence' => \@evidence,
'clinical_significance' => \@clin_sig,
'display' => $display
}
);
}
unless ($finished) {
$sth->finish;
$finished = 1;
}
return undef;
});
if ($self->{_iterator}) {
return $iterator;
}
else {
if ($self->{_get_variations}) {
my $vfs = $iterator->to_arrayref;
my @v_ids = map { $_->{_variation_id} } @$vfs;
my $vs = $self->db->get_VariationAdaptor->fetch_all_by_dbID_list(\@v_ids);
my %vs_by_id = map { $_->dbID => $_ } @$vs;
#warn "Got variations";
map { $_->variation( $vs_by_id{ $_->{_variation_id} }) } @$vfs;
return $vfs;
}
if ($self->{_get_transcript_variations}) {
my $vfs = $iterator->to_arrayref;
return $vfs unless @$vfs;
#warn "getting transcript variations";
my $tvs = $self->db->get_TranscriptVariationAdaptor->fetch_all_by_VariationFeatures($vfs);
for my $tv (@$tvs) {
$tv->variation_feature->add_TranscriptVariation($tv);
#$tv->variation_feature->{transcript_variations}->{$tv->transcript_stable_id} = $tv;
}
return $vfs;
}
else {
my $vfs = $iterator->to_arrayref;
#warn "Got ".scalar(@$vfs). "VFs";
return $vfs;
}
}
}
=head2 list_dbIDs
Arg [1] : none
Example : @feature_ids = @{$simple_feature_adaptor->list_dbIDs()};
Description: Gets an array of internal ids for all simple features in
the current db
Returntype : list of ints
Exceptions : none
Caller : general
Status : At Risk
=cut
sub list_dbIDs {
my $self = shift;
return $self->_list_dbIDs('variation_feature');
}
=head2 get_all_synonym_sources
Args[1] : Bio::EnsEMBL::Variation::VariationFeature vf
Example : my @sources = @{$vf_adaptor->get_all_synonym_sources($vf)};
Description : returns a list of all the sources for synonyms of this
VariationFeature
ReturnType : reference to list of strings
Exceptions : none
Caller : general
Status : At Risk
: Variation database is under development.
=cut
sub get_all_synonym_sources{
my $self = shift;
my $vf = shift;
my %sources;
my @sources;
if(!ref($vf) || !$vf->isa('Bio::EnsEMBL::Variation::VariationFeature')) {
throw("Bio::EnsEMBL::Variation::VariationFeature argument expected");
}
if (!defined($vf->{'_variation_id'}) && !defined($vf->{'variation'})){
warning("Not possible to get synonym sources for the VariationFeature: you need to attach a Variation first");
return \@sources;
}
#get the variation_id
my $variation_id;
if (defined ($vf->{'_variation_id'})){
$variation_id = $vf->{'_variation_id'};
}
else{
$variation_id = $vf->variation->dbID();
}
#and go to the varyation_synonym table to get the extra sources
my $source_name;
my $sth = $self->prepare(qq{SELECT s.name
FROM variation_synonym vs, source s
WHERE s.source_id = vs.source_id
AND vs.variation_id = ?
});
$sth->bind_param(1,$variation_id,SQL_INTEGER);
$sth->execute();
$sth->bind_columns(\$source_name);
while ($sth->fetch){
$sources{$source_name}++;
}
@sources = keys(%sources);
return \@sources;
}
=head2 new_fake
Arg [1] : string $species
Example :
$vfa = Bio::EnsEMBL::Variation::VariationFeatureAdaptor->new_fake('human');
Description: Creates a VariationFeatureAdaptor with no underlying database
attached. Should be used only when getting consequence types for
species with no variation database available.
Returntype : Bio::EnsEMBL::Variation::VariationFeatureAdaptor
Exceptions : throw if no species given
Caller : called from webcode for species where no variation database present
Status : Stable
=cut
sub new_fake {
my $class = shift;
my $species = shift;
throw("No species defined") unless defined $species;
my $self = bless {}, $class;
$self->{'species'} = $species;
return $self;
}
sub _parse_hgvs_genomic_position {
my $description = shift;
my ($start, $start_offset, $end, $end_offset) = $description=~ m/^([\-\*]?\d+)((?:[\+\-]\d+)?)(?:_([\-\*]?\d+)((?:[\+\-]\d+)?))?/;
## end information needed even if same as start
unless ($end){$end = $start;}
unless ($end_offset){$end_offset = $start_offset;}
return ($start, $end);
}
sub _parse_hgvs_transcript_position {
### Work out genomic coordinates from hgvs coding or non coding annotation
### Non-exonic notation -
### P+n => n bases after listed exonic base
### P-n => n bases before listed exonic base
### -P+n => n bases after listed 5'UTR base
### *P-n => n bases before listed 3'UTR base
my $description = shift;
my $transcript = shift;
my ($start,$start_offset, $end, $end_offset) = $description =~ m/^([\-\*]?\d+)((?:[\+\-]\d+)?)(?:_([\-\*]?\d+)((?:[\+\-]\d+)?))?/;
my $is_exonic = 1;
$is_exonic = 0 if ($start_offset || $end_offset || substr($start,0,1) eq '*' || (defined $end && substr($end,0,1) eq '*') || $start < 0);
## go back or forward into intron
my $start_direction = 0;
my $end_direction = 0;
if($start_offset ){
### extract + or - for intronic positions in coding nomenclature
if (substr($start_offset,0,1) eq '+' || substr($start_offset,0,1) eq '-'){
$start_direction = substr($start_offset,0,1);
$start_offset = substr($start_offset,1) ;
$start = $start;
}
}
else{ ### exonic
$start_offset = 0 ;
}
if($end_offset ){
### this is needed for long intronic events eg. ENST00000299272.5:c.98-354_98-351dupGAAA
if (substr($end_offset,0,1) eq '+' || substr($end_offset,0,1) eq '-'){
$end_direction = substr($end_offset,0,1);
$end_offset = substr($end_offset,1) ;
$end = $end
}
}
else{
$end_offset = $start_offset;
}
### add missing values if single-location variant - needed for refseq check later
unless (defined $end) {
$end = $start;
$end_direction= $start_direction ;
}
### Variant in the 3' UTR => convert the coordinates by setting them to be the stop codon position + the UTR offset
if (substr($start,0,1) eq '*'){
$start = ($transcript->cdna_coding_end() - $transcript->cdna_coding_start() + 1) + int(substr($start,1)) ;
}
if (substr($end,0,1) eq '*'){
$end = ($transcript->cdna_coding_end() - $transcript->cdna_coding_start() + 1) + int(substr($end,1));
}
### Variant in the 5' UTR => convert the coordinates by setting them to be the start codon position(0) - the UTR offset
if (substr($start,0,1) eq '-'){
$start = 0 - int(substr($start,1)) ;
}
if (substr($end,0,1) eq '-'){
$end = 0 - int(substr($end,1));
}
# Get the TranscriptMapper to convert to genomic coords
my $tr_mapper = $transcript->get_TranscriptMapper();
if($DEBUG ==1){print "About to convert to genomic $start $end, ccs:". $transcript->cdna_coding_start() ."\n";}
#The mapper can only convert cDNA coordinates, but we have CDS (relative to the start codon), so we need to convert them
my ($cds_start, $cds_end) ;
if( defined $transcript->cdna_coding_start()){
($cds_start, $cds_end) = (($start + $transcript->cdna_coding_start() - ($start > 0)),($end + $transcript->cdna_coding_start() - ($end > 0)));
}
else{
#### non coding transcript
($cds_start, $cds_end) = ($start, $end);
}
# Convert the cDNA coordinates to genomic coordinates.
my @coords = $tr_mapper->cdna2genomic($cds_start,$cds_end);
if($DEBUG ==1){
print "In parser: cdna2genomic coords: ". $coords[0]->start() . "-". $coords[0]->end() . " and strand ". $coords[0]->strand()." from $cds_start,$cds_end\n";}
#Throw an error if we didn't get an unambiguous coordinate back
throw ("Unable to map the cDNA coordinates $start\-$end to genomic coordinates for Transcript " .$transcript->stable_id()) if (scalar(@coords) != 1 || !$coords[0]->isa('Bio::EnsEMBL::Mapper::Coordinate'));
my $strand = $coords[0]->strand();
### overwrite exonic location with genomic coordinates
$start = $coords[0]->start();
$end = $coords[0]->end();
#### intronic variants are described as after or before the nearest exon
#### - add this offset to genomic start & end positions
if( $start_direction ne 0 || $end_direction ne 0 ){
if($strand == 1){
if($start_direction eq "+"){ $start = $start + $start_offset; }
if($end_direction eq "+"){ $end = $end + $end_offset; }
if($start_direction eq "-"){ $start = $start - $start_offset; }
if($end_direction eq "-"){ $end = $end - $end_offset; }
}
elsif($strand == -1 ){
## start & end swapped for rev strand features => apply offsets
if($end_direction eq "+"){ $start = $start - $end_offset;}
if($start_direction eq "+"){ $end = $end - $start_offset; }
if($end_direction eq "-"){ $start = $start + $end_offset;}
if($start_direction eq "-"){ $end = $end + $start_offset; }
}
}
return ($start, $end, $strand, $is_exonic);
}
=head2 fetch_by_hgvs_notation
Arg[1] : String $hgvs
Example : my $hgvs = 'LRG_8t1:c.3891A>T';
$vf = $vf_adaptor->fetch_by_hgvs_notation($hgvs);
Description : Parses an HGVS notation and tries to create a VariationFeature object
based on the notation. The object will have a Variation and Alleles attached.
ReturnType : Bio::EnsEMBL::Variation::VariationFeature, undef on failure
Exceptions : thrown on error
Caller : general
Status : Stable
=cut
sub fetch_by_hgvs_notation {
my $self = shift;
my ($hgvs, $user_slice_adaptor, $user_transcript_adaptor, $multiple_ok, $replace_ref) = rearrange([qw(
HGVS
SLICE_ADAPTOR
TRANSCRIPT_ADAPTOR
MULTIPLE_OK
REPLACE_REF
)], @_);
if($DEBUG ==1){print "\nStarting fetch_by_hgvs_notation for $hgvs\n";}
########################### Check & split input ###########################
#Split the HGVS notation into the reference, notation type and variation description
my ($reference,$type,$description) = $hgvs =~ m/^([^\:]+)\:.*?([cgmnrp]?)\.?(.*?[\*\-0-9]+.*)$/i;
#If any of the fields are unknown, return undef
throw ("Could not parse the HGVS notation $hgvs")
unless (defined($reference) && defined($type) && defined($description));
my $extra;
if($description =~ m/\(.+\)/) {
($description, $extra) = $description=~ /(.+?)(\(.+\))/;
throw ("Could not parse the HGVS notation $hgvs - can't interpret \'$extra\'") unless $extra eq '(p.=)';
}
# strip version number from reference
if ($reference=~ /^ENS|^LRG_\d+/){
$reference =~ s/\.\d+//g;
}
$description =~ s/\s+//;
####################### extract genomic coordinates and reference seq allele #######################
my ($start, $end, $strand, $ref_allele, $alt_allele);
#Get a slice adaptor to enable check of supplied reference allele
my $slice_adaptor = $user_slice_adaptor || $self->db()->dnadb()->get_SliceAdaptor();
my $slice ;
if($type =~ m/c|n/i) {
#Get the Transcript object to convert coordinates
my $transcript_adaptor = $user_transcript_adaptor || $self->db()->dnadb()->get_TranscriptAdaptor();
my $transcript = $transcript_adaptor->fetch_by_stable_id($reference);
my @transcripts;
#try and fetch via gene
if(!defined($transcript)) {
push @transcripts, @{$self->_get_gene_transcripts($transcript_adaptor, $reference, $multiple_ok)};
}
else {
push @transcripts, $transcript;
}
throw ("Could not get a Transcript object for '$reference'") unless @transcripts;
my @results;
my %errors;
foreach my $transcript(@transcripts) {
my ($is_exonic, $result);
eval {
($start, $end, $strand, $is_exonic) = _parse_hgvs_transcript_position($description, $transcript) ;
$slice = $slice_adaptor->fetch_by_region($transcript->coord_system_name(),$transcript->seq_region_name());
($ref_allele, $alt_allele) = get_hgvs_alleles($hgvs);
$result = $self->_hgvs_from_components(
$hgvs, $reference, $type, $description,
$slice, $ref_allele, $alt_allele, $start, $end, $strand, $replace_ref
)
};
if($@) {
$errors{$@} = 1;
}
else {
push @results, $result;
}
}
throw(join("\n", keys %errors)) unless @results;
return $multiple_ok ? \@results : $results[0];
}
elsif($type =~ m/g|m/i) {
($start, $end) = _parse_hgvs_genomic_position($description) ;
## grab reference allele; second call after "||" allows for LRG regions to be fetched
$slice = $slice_adaptor->fetch_by_region('chromosome', $reference ) || $slice_adaptor->fetch_by_region(undef, $reference);
$strand =1; ## strand should be genome strand for HGVS genomic notation
($ref_allele, $alt_allele) = get_hgvs_alleles($hgvs);
my $result = $self->_hgvs_from_components(
$hgvs, $reference, $type, $description,
$slice, $ref_allele, $alt_allele, $start, $end, $strand, $replace_ref
);
return $multiple_ok ? [$result] : $result;
}
elsif($type =~ m/p/i) {
#Get the Transcript object to convert coordinates
my $transcript_adaptor = $user_transcript_adaptor || $self->db()->dnadb()->get_TranscriptAdaptor();
my $transcript = $transcript_adaptor->fetch_by_translation_stable_id($reference);
my @transcripts;
#try and fetch via gene
if(!defined($transcript)) {
push @transcripts, @{$self->_get_gene_transcripts($transcript_adaptor, $reference, $multiple_ok)};
}
else {
push @transcripts, $transcript;
}
throw ("Could not get a Transcript object for '$reference'") unless @transcripts;
my @results;
my %errors;
foreach my $transcript(@transcripts) {
my $possible_prot;
eval {
$possible_prot = _parse_hgvs_protein_position($description, $reference, $transcript);
throw("Could not uniquely determine nucleotide change from $hgvs") if scalar @$possible_prot > 1 && !$multiple_ok;
$slice = $slice_adaptor->fetch_by_region($transcript->coord_system_name(), $transcript->seq_region_name());
};
if($@) {
$errors{$@} = 1;
next;
}
foreach my $poss(@$possible_prot) {
my $result;
eval {
$result = $self->_hgvs_from_components(
$hgvs, $reference, $type, $description, $slice,
@$poss, $replace_ref
)
};
if($@) {
$errors{$@} = 1;
}
else {
push @results, $result;
}
}
}
throw(join("\n", keys %errors)) unless @results;
return $multiple_ok ? \@results : $results[0];
}
else {
throw ("HGVS type $type not recognised for $hgvs");
}
}
sub _get_gene_transcripts {
my ($self, $transcript_adaptor, $reference, $multiple_ok) = @_;
my $gene_adaptor = $transcript_adaptor->db->get_GeneAdaptor();
my ($gene) = grep {($_->external_name || '') eq $reference} @{$gene_adaptor->fetch_all_by_external_name($reference)};
my @transcripts;
if($gene) {
if($multiple_ok) {
push @transcripts, @{$gene->get_all_Transcripts};
}
else {
push @transcripts, $self->_pick_likely_transcript($gene->get_all_Transcripts);
print STDERR "Picked transcript ".$transcripts[0]->stable_id."\n" if $DEBUG==1;
}
}
return \@transcripts;
}
=head2 fetch_all_possible_by_hgvs_notation
Arg[1] : String $hgvs
Example : my $hgvs = 'ENSP00000284967.6:p.Glu2Asp';
$vfs = $vf_adaptor->fetch_all_possible_by_hgvs_notation($hgvs);
Description : Parses an HGVS notation and tries to create VariationFeature objects.
Some protein (p.) notations may reverse translate to multiple
possible genomic changes; this method returns all possible
variants representing the shortest path from reference to alternate
allele.
ReturnType : arrayref of Bio::EnsEMBL::Variation::VariationFeature
Exceptions : thrown on error
Caller : general
Status : Stable
=cut
sub fetch_all_possible_by_hgvs_notation {
my $self = shift;
my ($hgvs, $user_slice_adaptor, $user_transcript_adaptor, $replace_ref) = rearrange([qw(
HGVS
SLICE_ADAPTOR
TRANSCRIPT_ADAPTOR
REPLACE_REF
)], @_);
return $self->fetch_by_hgvs_notation(
-hgvs => $hgvs,
-slice_adaptor => $user_slice_adaptor,
-transcript_adaptor => $user_transcript_adaptor,
-replace_ref => $replace_ref,
-multiple_ok => 1
);
}
sub _hgvs_from_components {
my ($self, $hgvs, $reference, $type, $description, $slice, $ref_allele, $alt_allele, $start, $end, $strand, $replace_ref) = @_;
####################### check alleles #######################
#Get the reference allele based on the coordinates - need to supply lowest coordinate first to slice->subseq()
my $refseq_allele;
if($start > $end){ $refseq_allele = $slice->subseq($end, $start, $strand);}
else{ $refseq_allele = $slice->subseq($start, $end, $strand);}
# take reference allele from genomic reference & coordinates if not supplied in HGVS string for a deletion
$ref_allele = $refseq_allele if( $type =~ m/g|c|n|m/ && $description =~ m/del/ );
# If the reference allele was omitted, set it to undef
$ref_allele = undef unless (defined($ref_allele) && length($ref_allele));
# take alternate allele from genomic reference & coordinates if not supplied in HGVS string for a duplication
if($description =~ /dup/){
## special case: handle as insertion for ensembl object purposes
$start = $end ;
if($strand == 1){ $start++; }
else{ $end--; }
$ref_allele = "-" ;
$alt_allele = $refseq_allele;
}
elsif ($description =~ m/ins/i && $description =~ m/del/i) {
## check for malformed indels
($ref_allele, $alt_allele, $start, $end) = @{trim_sequences($ref_allele, $alt_allele, $start, $end, 1)};
}
elsif ($description =~ m/ins/i && $description !~ m/del/i) {
# insertion: the start & end positions are inverted by convention
if($end > $start){ ($start, $end ) = ( $end , $start); }
}
else {
if($DEBUG==1){print "Reference allele: $refseq_allele expected allele: $ref_allele\n";}
if($replace_ref && defined($ref_allele)) {
$ref_allele = $refseq_allele;
}
# If the reference from the sequence does not correspond to the reference given in the HGVS notation, throw an exception
elsif (defined($ref_allele) && $ref_allele ne $refseq_allele){
throw ("Reference allele extracted from $reference:$start-$end ($refseq_allele) does not match reference allele given by HGVS notation $hgvs ($ref_allele)");
}
}
if (defined($ref_allele) && $ref_allele eq $alt_allele){
throw ("Reference allele extracted from $reference:$start-$end ($refseq_allele) matches alt allele given by HGVS notation $hgvs ($alt_allele)");
}
####################### Create objects #######################
#Create Allele objects
my @allele_objs;
if($self->db) {
foreach my $allele ($ref_allele,$alt_allele) {
push(@allele_objs,Bio::EnsEMBL::Variation::Allele->new('-adaptor' => $self, '-allele' => $allele));
}
}
#Create a variation object. Use the HGVS string as its name
my $variation = Bio::EnsEMBL::Variation::Variation->new(
'-adaptor' => $self->db ? $self->db()->get_VariationAdaptor() : undef,
'-name' => $hgvs,
'-source' => 'Parsed from HGVS notation',
'-alleles' => \@allele_objs
);
#Create a variation feature object
my $variation_feature = Bio::EnsEMBL::Variation::VariationFeature->new(
'-adaptor' => $self,
'-start' => $start,
'-end' => $end,
'-strand' => $strand,
'-slice' => $slice,
'-map_weight' => 1,
'-variation' => $variation,
'-allele_string' => "$ref_allele/$alt_allele"
);
if($DEBUG==1){print "Created object $hgvs allele_string: $ref_allele/$alt_allele, start:$start, end:$end\n";}
return $variation_feature;
}
## when a user gives a HGVS notation on a gene
## we want to pick the "most likely" transcript
sub _pick_likely_transcript {
my $self = shift;
my $transcripts = shift;
return $transcripts->[0] if scalar @$transcripts == 1;
my @tr_info;
foreach my $tr(@$transcripts) {
# create a hash of info for this transcript that will be used to rank it
my $info = {
canonical => 1,
ccds => 1,
length => 0,
biotype => 1,
tsl => 100,
appris => 100,
tr => $tr
};
# 0 is "best"
$info->{canonical} = $tr->is_canonical ? 0 : 1;
$info->{biotype} = $tr->biotype eq 'protein_coding' ? 0 : 1;
$info->{ccds} = (grep {$_->database eq 'CCDS'} @{$tr->get_all_DBEntries}) ? 0 : 1;
# "invert" length so longer is best
$info->{length} = 0 - $tr->length();
# lower TSL is best
if(my ($tsl) = @{$tr->get_all_Attributes('TSL')}) {
if($tsl->value =~ m/tsl(\d+)/) {
$info->{tsl} = $1 if $1;
}
}
# same for APPRIS
if(my ($appris) = @{$tr->get_all_Attributes('APPRIS')}) {
if($appris->value =~ m/(.+?)(\d+)/) {
if(my $num = $2) {
$num += 10 unless $1 eq 'principal';
$info->{appris} = $num if $num;
}
}
}
push @tr_info, $info;
}
my @order = qw(appris tsl canonical biotype ccds rank length);
my $picked;
# go through each category in order
foreach my $cat(@order) {
# sort on that category
@tr_info = sort {$a->{$cat} <=> $b->{$cat}} @tr_info;
# take the first (will have the lowest value of $cat)
$picked = shift @tr_info;
my @tmp = ($picked);
# now add to @tmp those vfoas that have the same value of $cat as $picked
push @tmp, shift @tr_info while @tr_info && $tr_info[0]->{$cat} eq $picked->{$cat};
# if there was only one, return
return $picked->{tr} if scalar @tmp == 1;
# otherwise shrink the array to just those that had the lowest
# this gives fewer to sort on the next round
@tr_info = @tmp;
}
# probably shouldn't get here, but if we do, return the first
return $tr_info[0]->{tr};
}
## Extract enough information to make a variation_feature from HGVS protein nomenclature
## Only attempts substitutions
## - assumes protein change results from minimum number of nucleotide changes
## - returns VF information only if one minimal solution found
sub _parse_hgvs_protein_position{
my ($description, $reference, $transcript ) = @_;
## only supporting the parsing of hgvs substitutions [eg. Met213Ile]
my ($from, $pos, $to) = $description =~ /^(\w+?)(\d+)(\w+?|\*)$/;
throw("Could not parse HGVS protein notation " . $reference . ":p.". $description ) unless $from and $pos and $to;
# convert three letter AA to single
$from = $Bio::SeqUtils::ONECODE{$from} || $from;
$to = $Bio::SeqUtils::ONECODE{$to} || $to;
# get genomic position
my $tr_mapper = $transcript->get_TranscriptMapper();
my @coords = $tr_mapper->pep2genomic($pos, $pos);
throw ("Unable to map the peptide coordinate $pos to genomic coordinates for protein $reference") if (scalar(@coords) != 1 || !$coords[0]->isa('Bio::EnsEMBL::Mapper::Coordinate'));
my $strand = $coords[0]->strand();
my $start = $strand > 0 ? $coords[0]->start() : $coords[0]->end();
my $end = $strand > 0 ? $coords[0]->start() : $coords[0]->end();
## find reference sequence
my $slice = $transcript->slice();
## make a small slice for sequence look-up
my $from_slice = Bio::EnsEMBL::Slice->new(-coord_system => $slice->coord_system(),
-start => $coords[0]->start(),
-end => $coords[0]->start()+2,
-strand => $slice->strand(),
-seq_region_name => $slice->seq_region_name,
-seq_region_length => 3,
-adaptor => $slice->adaptor);
my $from_codon_ref = $from_slice->seq();
throw ("Unable to find the genomic reference sequence for protein $reference") unless defined $from_codon_ref;
## correct for strand
reverse_comp(\$from_codon_ref) if $strand <0;
# get correct codon table
my $attrib = $transcript->slice->get_all_Attributes('codon_table')->[0];
# default to the vertebrate codon table which is denoted as 1
my $codon_table = Bio::Tools::CodonTable->new( -id => ($attrib ? $attrib->value : 1));
# check genomic codon is compatible with input HGVS
my $check_prot = $codon_table->translate($from_codon_ref);
my @from_codons;
if ($check_prot eq $from){
push @from_codons, $from_codon_ref ;
}
else{
# rev-translate input ref sequence if the genome sequence does not match
@from_codons = $codon_table->revtranslate($from);
}
# rev-translate alt sequence
my @to_codons = $codon_table->revtranslate($to);
# now iterate over all possible mutation paths
my %paths;
foreach my $from_codon (@from_codons) {
foreach my $to_codon (@to_codons) {
my $key = $from_codon .'_'. $to_codon;
for my $i(0..2) {
my ($a, $b) = (substr($from_codon, $i, 1), substr($to_codon, $i, 1));
next if uc($a) eq uc($b);
push @{$paths{$key}}, $i.'_'.uc($a).'/'.uc($b);
}
# non consecutive paths
if(scalar @{$paths{$key}} == 2 and $paths{$key}->[0] =~ /^0/ and $paths{$key}->[1] =~ /^2/) {
splice(@{$paths{$key}}, 1, 0, '1_'.substr($from_codon, 1, 1).'/'.substr($from_codon, 1, 1));
}
$paths{$key} = join ",", @{$paths{$key}};
}
}
# get shortest dist and best paths with that dist
my $shortest_dist = length((sort {length($a) <=> length($b)} values %paths)[0]);
my %best_paths = map {$_ => 1} grep {length($_) eq $shortest_dist} values %paths;
throw("Could not determine nucleotide change from peptide change $from \-\> $to") unless scalar keys %best_paths;
my @results;
foreach my $best_path(keys %best_paths) {
my ($ref_allele, $alt_allele) = ('', '');
my ($this_start, $this_end) = ($start, $end);
my @path = split(/\,/, $best_path);
# coords
if($strand > 0) {
$this_start += (split /\_/, $path[0])[0];
$this_end += (split /\_/, $path[-1])[0];
}
else {
$this_start -= (split /\_/, $path[0])[0];
$this_end -= (split /\_/, $path[-1])[0];
}
# alleles
$ref_allele .= (split /\_|\//, $path[$_])[1] for 0..$#path;
$alt_allele .= (split /\_|\//, $path[$_])[2] for 0..$#path;
push @results, [$ref_allele, $alt_allele, $this_start, $this_end, $strand];
}
return \@results;
#
#use Data::Dumper;
#$Data::Dumper::Maxdepth = 3;
#warn Dumper \@from_codons;
#warn Dumper \@to_codons;
#warn Dumper \%paths;
#warn Dumper \%best_paths;
#exit(0);
}
1;
| willmclaren/ensembl-variation | modules/Bio/EnsEMBL/Variation/DBSQL/VariationFeatureAdaptor.pm | Perl | apache-2.0 | 73,279 |
#!/usr/bin/perl
require "/perfstat/build/serialize/create/ServiceConfig.pl";
#add create new service
$service = Service->new( RRA => "RRA:AVERAGE:0.5:1:1728 RRA:AVERAGE:0.5:6:1296 RRA:AVERAGE:0.5:24:996 RRA:AVERAGE:0.5:144:730",
rrdStep => "300",
serviceName => "cpu",
);
#add metric 0
$obj = Metric->new( rrdIndex => 0,
metricName => "usrPct",
friendlyName => "User % Utilization",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 75,
critThreshold => 90,
thresholdUnit => "Percent",
);
$service->addMetric($obj);
#add metric 1
$obj = Metric->new( rrdIndex => 1,
metricName => "sysPct",
friendlyName => "System % Utilization",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 75,
critThreshold => 90,
thresholdUnit => "Percent",
);
$service->addMetric($obj);
#add metric 2
$obj = Metric->new( rrdIndex => 2,
metricName => "idlePct",
friendlyName => "Idle % Utilization",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 75,
critThreshold => 90,
thresholdUnit => "Percent",
);
$service->addMetric($obj);
#add metric 3
$obj = Metric->new( rrdIndex => 3,
metricName => "load1",
friendlyName => "Load Average (1 Minute)",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 3,
critThreshold => 5,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add metric 4
$obj = Metric->new( rrdIndex => 4,
metricName => "load5",
friendlyName => "Load Average (5 Minute)",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 3,
critThreshold => 5,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add metric 5
$obj = Metric->new( rrdIndex => 5,
metricName => "load15",
friendlyName => "Load Average (15 Minute)",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 3,
critThreshold => 5,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add graph 0
$obj = Graph->new( name => "load",
title => "load average on",
y_axis => "Number",
legend => "",
optionsArray => [qq{-u 1.0}],
defArray => [q{DEF:load1=$RRD:load1:AVERAGE},q{DEF:load5=$RRD:load5:AVERAGE},q{DEF:load15=$RRD:load15:AVERAGE}],
cdefArray => [],
lineArray => [qq{LINE2:load1#FF0000:1 Min Load},qq{LINE2:load5#FFFF00:5 Min Load},qq{LINE2:load15#00CC00:15 Min Load}],
text => "",
);
$service->addGraph($obj);
#add graph 1
$obj = Graph->new( name => "usage",
title => "CPU usage on",
y_axis => "Number",
legend => "",
optionsArray => [qq{-u 100},qq{-r}],,
defArray => [q{DEF:idlePct=$RRD:idlePct:AVERAGE},q{DEF:usrPct=$RRD:usrPct:AVERAGE},q{DEF:sysPct=$RRD:sysPct:AVERAGE}],
cdefArray => [],
lineArray => [qq{AREA:sysPct#FF0000:System},qq{STACK:usrPct#FFFF00:User},qq{STACK:idlePct#00FF00:Idle}],
text => "",
);
$service->addGraph($obj);
#print out this service
print ("Ref: ref($service)\n");
$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
$rrdStep = $service->getRRDStep();
$lastUpdate = $service->getLastUpdate();
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
print ("rrdStep: $rrdStep\n");
print ("Last Update: $lastUpdate\n");
#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$metricObject = $service->{metricArray}->[$counter];
$rrdIndex = $metricObject->getRRDIndex();
$rrdDST = $metricObject->getRRDDST();
$rrdHeartbeat = $metricObject->getRRDHeartbeat();
$rrdMin = $metricObject->getRRDMin();
$rrdMax = $metricObject->getRRDMax();
$metricName = $metricObject->getMetricName();
$friendlyName = $metricObject->getFriendlyName();
$status = $metricObject->getStatus();
$hasEvents = $metricObject->getHasEvents();
$warnThreshold = $metricObject->getWarnThreshold();
$critThreshold = $metricObject->getCritThreshold();
$thresholdUnit = $metricObject->getThresholdUnit();
print ("rrdIndex: $rrdIndex\n");
print ("rrdDST: $rrdDST\n");
print ("rrdHeartbeat: $rrdHeartbeat\n");
print ("rrdMin: $rrdMin\n");
print ("rrdMax: $rrdMax\n");
print ("metricName: $metricName\n");
print ("friendlyName: $friendlyName\n");
print ("status: $status\n");
print ("hasEvents: $hasEvents\n");
print ("warnThreshold: $warnThreshold\n");
print ("critThreshold: $critThreshold\n");
print ("threshUnit: $thresholdUnit\n\n");
}
#print out this services graphs
$arrayLength = $service->getGraphArrayLength();
print ("graph Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$graphObject = $service->{graphArray}->[$counter];
$name = $graphObject->getName();
$title = $graphObject->getTitle();
$y_axis = $graphObject->getYaxis();
$legend = $graphObject->getLegend();
$text = $graphObject->getText();
print ("name: $name\n");
print ("title: $title\n");
print ("y_axis: $y_axis\n");
print ("legend: $legend\n");
print ("text: $text\n");
$arrayLength2 = $graphObject->getOptionsArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("option: $graphObject->{optionsArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getDefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("def: $graphObject->{defArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getCdefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("cdef: $graphObject->{cdefArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getLineArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("line: $graphObject->{lineArray}->[$counter2]\n");
}
}
#Store the service
$service->store("$perfhome/etc/configs/Linux/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
| ktenzer/perfstat | misc/serialize/create/Linux/20904/cpu.pl | Perl | apache-2.0 | 6,548 |
package VMOMI::InvalidProfileReferenceHost;
use parent 'VMOMI::RuntimeFault';
use strict;
use warnings;
our @class_ancestors = (
'RuntimeFault',
'MethodFault',
);
our @class_members = (
['reason', undef, 0, 1],
['host', 'ManagedObjectReference', 0, 1],
['profile', 'ManagedObjectReference', 0, 1],
['profileName', undef, 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/InvalidProfileReferenceHost.pm | Perl | apache-2.0 | 577 |
package t::RedisParser;
use Test::Base -Base;
use IPC::Run3;
use Cwd;
use Test::LongString;
our @EXPORT = qw( run_tests );
$ENV{LUA_CPATH} = "?.so;" . ($ENV{LUA_CPATH} || "") . ';' . "/usr/local/openresty-debug/lualib/?.so;/usr/local/openresty/lualib/?.so;;";
#$ENV{LUA_PATH} = ($ENV{LUA_PATH} || "" ) . ';' . getcwd . "/runtime/?.lua" . ';;';
sub run_test ($) {
my $block = shift;
#print $json_xs->pretty->encode(\@new_rows);
#my $res = #print $json_xs->pretty->encode($res);
my $name = $block->name;
my $lua = $block->lua or
die "No --- lua specified for test $name\n";
open my $fh, ">test_case.lua";
print $fh $lua;
close $fh;
my ($res, $err);
my @cmd;
if ($ENV{TEST_LUA_USE_VALGRIND}) {
@cmd = ('valgrind', '-q', '--leak-check=full', 'lua', 'test_case.lua');
} else {
@cmd = ('lua', 'test_case.lua');
}
run3 \@cmd, undef, \$res, \$err;
#warn "res:$res\nerr:$err\n";
if (defined $block->err) {
$err =~ /.*:.*:.*: (.*\s)?/;
$err = $1;
is $err, $block->err, "$name - err expected";
} elsif ($?) {
die "Failed to execute --- lua for test $name: $err\n";
} else {
#is $res, $block->out, "$name - output ok";
is_string $res, $block->out, "$name - output ok";
}
unlink 'test_case.lua' or warn "could not delete \'test_case.lua\':$!";
}
sub run_tests () {
for my $block (blocks()) {
run_test($block);
}
}
1;
| caidongyun/nginx-openresty-windows | lua-redis-parser-0.10/t/RedisParser.pm | Perl | bsd-2-clause | 1,553 |
use strict;
use warnings;
use diagnostics;
use 5.20.1;
use Win32::Clipboard;
use autodie;
use Imager;
use Getopt::Long;
use Path::Tiny;
my $fileName;
(GetOptions('file|f=s' => \$fileName) && $fileName) or die "Usage: $0 --file|-f Name";
path($fileName)->touchpath;
my $clip = Win32::Clipboard();
if($clip->IsBitmap()){
my $bitmap = $clip->GetBitmap();
if($bitmap){
my $img = Imager->new;
$img->read(data=> $bitmap) or die $img->errstr;
$img->write(file=>"$fileName") or die $img->errstr;
say "done!";
}else{
say "no map in clipboard";
}
}
| lust4life/quick.dirty.perl | Perl STH/tools/pasteIntoFile.pl | Perl | bsd-3-clause | 600 |
# better color the HP display
# prayer-safe HP is colored as dark gray
# it also doesn't "miss" like the real hpmon
# by Eidolos
include "stats";
our $notified = 0;
each_iteration
{
$botl{hp} =~ s{(HP:)(\d+\(\d+\))}{
my $color = '';
if ($curhp * 7 <= $maxhp || $curhp <= 5) { $color = "\e[1;30m" }
elsif ($curhp >= $maxhp) { }
elsif ($curhp * 2 >= $maxhp) { $color = "\e[1;32m" }
elsif ($curhp * 3 >= $maxhp) { $color = "\e[1;33m" }
elsif ($curhp * 4 >= $maxhp) { $color = "\e[0;31m" }
else { $color = "\e[1;31m" }
if ($curhp > 0 && ($curhp * 7 <= $maxhp || $curhp <= 5))
{
if (!$notified)
{
push @postonce, sub { force_tab("Your HP is monstrously low!") };
$notified = 1;
}
}
else
{
$notified = 0;
}
"$1$color$2\e[0m"
}eg;
}
| Sec42/interhack | plugins/hpmon.pl | Perl | mit | 955 |
package Teng::Schema::Table;
use strict;
use warnings;
use Class::Accessor::Lite
rw => [ qw(
name
primary_keys
columns
escaped_columns
sql_types
row_class
base_row_class
) ]
;
use Carp ();
use Class::Load ();
sub new {
my ($class, %args) = @_;
my $self = bless {
deflators => [],
inflators => [],
escaped_columns => {},
base_row_class => 'Teng::Row',
%args
}, $class;
# load row class
my $row_class = $self->row_class;
Class::Load::load_optional_class($row_class) or do {
# make row class automatically
Class::Load::load_class($self->base_row_class);
no strict 'refs'; @{"$row_class\::ISA"} = ($self->base_row_class);
};
for my $col (@{$self->columns}) {
no strict 'refs';
unless ($row_class->can($col)) {
*{"$row_class\::$col"} = $row_class->generate_column_accessor($col);
}
}
$self->row_class($row_class);
return $self;
}
sub get_sql_type {
my ($self, $column_name) = @_;
$self->sql_types->{ $column_name };
}
sub add_deflator {
my ($self, $rule, $code) = @_;
if ( ref $rule ne 'Regexp' ) {
$rule = qr/^\Q$rule\E$/;
}
unless (ref($code) eq 'CODE') {
Carp::croak('deflate code must be coderef.');
}
push @{ $self->{deflators} }, ( $rule, $code );
}
sub add_inflator {
my ($self, $rule, $code) = @_;
if ( ref $rule ne 'Regexp' ) {
$rule = qr/^\Q$rule\E$/;
}
unless (ref($code) eq 'CODE') {
Carp::croak('inflate code must be coderef.');
}
push @{ $self->{inflators} }, ( $rule, $code );
}
sub call_deflate {
my ($self, $col_name, $col_value) = @_;
my $rules = $self->{deflators};
my $i = 0;
my $max = @$rules;
while ( $i < $max ) {
my ($rule, $code) = @$rules[ $i, $i + 1 ];
if ($col_name =~ /$rule/) {
return $code->($col_value);
}
$i += 2;
}
return $col_value;
}
sub call_inflate {
my ($self, $col_name, $col_value) = @_;
my $rules = $self->{inflators};
my $i = 0;
my $max = @$rules;
while ( $i < $max ) {
my ($rule, $code) = @$rules[ $i, $i + 1 ];
if ($col_name =~ /$rule/) {
return $code->($col_value);
}
$i += 2;
}
return $col_value;
}
sub has_deflators {
my $self = shift;
return scalar @{ $self->{deflators} };
}
sub has_inflators {
my $self = shift;
return scalar @{ $self->{inflators} };
}
sub prepare_from_dbh {
my ($self, $dbh) = @_;
$self->escaped_columns->{$dbh->{Driver}->{Name}} ||= [
map { \$dbh->quote_identifier($_) }
@{$self->columns}
];
}
1;
__END__
=head1 NAME
Teng::Schema::Table - Teng table class.
=head1 METHODS
=over 4
=item $table = Teng::Schema::Table->new
create new Teng::Schema::Table's object.
=item $table->get_sql_type
get column SQL type.
=item $table->add_deflator($column_rule, $code)
add deflate code reference.
=item $table->add_inflator($column_rule, $code)
add inflate code reference.
=item $table->call_deflate
execute deflate.
=item $table->call_inflate
execute inflate.
=item $table->has_deflators()
Returns true if there are any deflators
=item $table->has_inflators();
Returns true if there are any inflators
=back
| rosiro/wasarabi | local/lib/perl5/Teng/Schema/Table.pm | Perl | mit | 3,393 |
# Pod::Man -- Convert POD data to formatted *roff input.
#
# This module translates POD documentation into *roff markup using the man
# macro set, and is intended for converting POD documents written as Unix
# manual pages to manual pages that can be read by the man(1) command. It is
# a replacement for the pod2man command distributed with versions of Perl
# prior to 5.6.
#
# Perl core hackers, please note that this module is also separately
# maintained outside of the Perl core as part of the podlators. Please send
# me any patches at the address above in addition to sending them to the
# standard Perl mailing lists.
#
# Written by Russ Allbery <rra@cpan.org>
# Substantial contributions by Sean Burke <sburke@cpan.org>
# Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
# 2010, 2012, 2013, 2014, 2015, 2016 Russ Allbery <rra@cpan.org>
#
# This program is free software; you may redistribute it and/or modify it
# under the same terms as Perl itself.
##############################################################################
# Modules and declarations
##############################################################################
package Pod::Man;
use 5.006;
use strict;
use warnings;
use subs qw(makespace);
use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION);
use Carp qw(carp croak);
use Pod::Simple ();
# Conditionally import Encode and set $HAS_ENCODE if it is available.
our $HAS_ENCODE;
BEGIN {
$HAS_ENCODE = eval { require Encode };
}
@ISA = qw(Pod::Simple);
$VERSION = '4.07';
# Set the debugging level. If someone has inserted a debug function into this
# class already, use that. Otherwise, use any Pod::Simple debug function
# that's defined, and failing that, define a debug level of 10.
BEGIN {
my $parent = defined (&Pod::Simple::DEBUG) ? \&Pod::Simple::DEBUG : undef;
unless (defined &DEBUG) {
*DEBUG = $parent || sub () { 10 };
}
}
# Import the ASCII constant from Pod::Simple. This is true iff we're in an
# ASCII-based universe (including such things as ISO 8859-1 and UTF-8), and is
# generally only false for EBCDIC.
BEGIN { *ASCII = \&Pod::Simple::ASCII }
# Pretty-print a data structure. Only used for debugging.
BEGIN { *pretty = \&Pod::Simple::pretty }
# Formatting instructions for various types of blocks. cleanup makes hyphens
# hard, adds spaces between consecutive underscores, and escapes backslashes.
# convert translates characters into escapes. guesswork means to apply the
# transformations done by the guesswork sub. literal says to protect literal
# quotes from being turned into UTF-8 quotes. By default, all transformations
# are on except literal, but some elements override.
#
# DEFAULT specifies the default settings. All other elements should list only
# those settings that they are overriding. Data indicates =for roff blocks,
# which should be passed along completely verbatim.
#
# Formatting inherits negatively, in the sense that if the parent has turned
# off guesswork, all child elements should leave it off.
my %FORMATTING = (
DEFAULT => { cleanup => 1, convert => 1, guesswork => 1, literal => 0 },
Data => { cleanup => 0, convert => 0, guesswork => 0, literal => 0 },
Verbatim => { guesswork => 0, literal => 1 },
C => { guesswork => 0, literal => 1 },
X => { cleanup => 0, guesswork => 0 },
);
##############################################################################
# Object initialization
##############################################################################
# Initialize the object and set various Pod::Simple options that we need.
# Here, we also process any additional options passed to the constructor or
# set up defaults if none were given. Note that all internal object keys are
# in all-caps, reserving all lower-case object keys for Pod::Simple and user
# arguments.
sub new {
my $class = shift;
my $self = $class->SUPER::new;
# Tell Pod::Simple not to handle S<> by automatically inserting .
$self->nbsp_for_S (1);
# Tell Pod::Simple to keep whitespace whenever possible.
if (my $preserve_whitespace = $self->can ('preserve_whitespace')) {
$self->$preserve_whitespace (1);
} else {
$self->fullstop_space_harden (1);
}
# The =for and =begin targets that we accept.
$self->accept_targets (qw/man MAN roff ROFF/);
# Ensure that contiguous blocks of code are merged together. Otherwise,
# some of the guesswork heuristics don't work right.
$self->merge_text (1);
# Pod::Simple doesn't do anything useful with our arguments, but we want
# to put them in our object as hash keys and values. This could cause
# problems if we ever clash with Pod::Simple's own internal class
# variables.
%$self = (%$self, @_);
# Send errors to stderr if requested.
if ($$self{stderr} and not $$self{errors}) {
$$self{errors} = 'stderr';
}
delete $$self{stderr};
# Validate the errors parameter and act on it.
if (not defined $$self{errors}) {
$$self{errors} = 'pod';
}
if ($$self{errors} eq 'stderr' || $$self{errors} eq 'die') {
$self->no_errata_section (1);
$self->complain_stderr (1);
if ($$self{errors} eq 'die') {
$$self{complain_die} = 1;
}
} elsif ($$self{errors} eq 'pod') {
$self->no_errata_section (0);
$self->complain_stderr (0);
} elsif ($$self{errors} eq 'none') {
$self->no_whining (1);
} else {
croak (qq(Invalid errors setting: "$$self{errors}"));
}
delete $$self{errors};
# Degrade back to non-utf8 if Encode is not available.
#
# Suppress the warning message when PERL_CORE is set, indicating this is
# running as part of the core Perl build. Perl builds podlators (and all
# pure Perl modules) before Encode and other XS modules, so Encode won't
# yet be available. Rely on the Perl core build to generate man pages
# later, after all the modules are available, so that UTF-8 handling will
# be correct.
if ($$self{utf8} and !$HAS_ENCODE) {
if (!$ENV{PERL_CORE}) {
carp ('utf8 mode requested but Encode module not available,'
. ' falling back to non-utf8');
}
delete $$self{utf8};
}
# Initialize various other internal constants based on our arguments.
$self->init_fonts;
$self->init_quotes;
$self->init_page;
# For right now, default to turning on all of the magic.
$$self{MAGIC_CPP} = 1;
$$self{MAGIC_EMDASH} = 1;
$$self{MAGIC_FUNC} = 1;
$$self{MAGIC_MANREF} = 1;
$$self{MAGIC_SMALLCAPS} = 1;
$$self{MAGIC_VARS} = 1;
return $self;
}
# Translate a font string into an escape.
sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }
# Determine which fonts the user wishes to use and store them in the object.
# Regular, italic, bold, and bold-italic are constants, but the fixed width
# fonts may be set by the user. Sets the internal hash key FONTS which is
# used to map our internal font escapes to actual *roff sequences later.
sub init_fonts {
my ($self) = @_;
# Figure out the fixed-width font. If user-supplied, make sure that they
# are the right length.
for (qw/fixed fixedbold fixeditalic fixedbolditalic/) {
my $font = $$self{$_};
if (defined ($font) && (length ($font) < 1 || length ($font) > 2)) {
croak qq(roff font should be 1 or 2 chars, not "$font");
}
}
# Set the default fonts. We can't be sure portably across different
# implementations what fixed bold-italic may be called (if it's even
# available), so default to just bold.
$$self{fixed} ||= 'CW';
$$self{fixedbold} ||= 'CB';
$$self{fixeditalic} ||= 'CI';
$$self{fixedbolditalic} ||= 'CB';
# Set up a table of font escapes. First number is fixed-width, second is
# bold, third is italic.
$$self{FONTS} = { '000' => '\fR', '001' => '\fI',
'010' => '\fB', '011' => '\f(BI',
'100' => toescape ($$self{fixed}),
'101' => toescape ($$self{fixeditalic}),
'110' => toescape ($$self{fixedbold}),
'111' => toescape ($$self{fixedbolditalic}) };
}
# Initialize the quotes that we'll be using for C<> text. This requires some
# special handling, both to parse the user parameter if given and to make sure
# that the quotes will be safe against *roff. Sets the internal hash keys
# LQUOTE and RQUOTE.
sub init_quotes {
my ($self) = (@_);
$$self{quotes} ||= '"';
if ($$self{quotes} eq 'none') {
$$self{LQUOTE} = $$self{RQUOTE} = '';
} elsif (length ($$self{quotes}) == 1) {
$$self{LQUOTE} = $$self{RQUOTE} = $$self{quotes};
} elsif (length ($$self{quotes}) % 2 == 0) {
my $length = length ($$self{quotes}) / 2;
$$self{LQUOTE} = substr ($$self{quotes}, 0, $length);
$$self{RQUOTE} = substr ($$self{quotes}, $length);
} else {
croak(qq(Invalid quote specification "$$self{quotes}"))
}
# Double the first quote; note that this should not be s///g as two double
# quotes is represented in *roff as three double quotes, not four. Weird,
# I know.
$$self{LQUOTE} =~ s/\"/\"\"/;
$$self{RQUOTE} =~ s/\"/\"\"/;
}
# Initialize the page title information and indentation from our arguments.
sub init_page {
my ($self) = @_;
# We used to try first to get the version number from a local binary, but
# we shouldn't need that any more. Get the version from the running Perl.
# Work a little magic to handle subversions correctly under both the
# pre-5.6 and the post-5.6 version numbering schemes.
my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/);
$version[2] ||= 0;
$version[2] *= 10 ** (3 - length $version[2]);
for (@version) { $_ += 0 }
my $version = join ('.', @version);
# Set the defaults for page titles and indentation if the user didn't
# override anything.
$$self{center} = 'User Contributed Perl Documentation'
unless defined $$self{center};
$$self{release} = 'perl v' . $version
unless defined $$self{release};
$$self{indent} = 4
unless defined $$self{indent};
# Double quotes in things that will be quoted.
for (qw/center release/) {
$$self{$_} =~ s/\"/\"\"/g if $$self{$_};
}
}
##############################################################################
# Core parsing
##############################################################################
# This is the glue that connects the code below with Pod::Simple itself. The
# goal is to convert the event stream coming from the POD parser into method
# calls to handlers once the complete content of a tag has been seen. Each
# paragraph or POD command will have textual content associated with it, and
# as soon as all of a paragraph or POD command has been seen, that content
# will be passed in to the corresponding method for handling that type of
# object. The exceptions are handlers for lists, which have opening tag
# handlers and closing tag handlers that will be called right away.
#
# The internal hash key PENDING is used to store the contents of a tag until
# all of it has been seen. It holds a stack of open tags, each one
# represented by a tuple of the attributes hash for the tag, formatting
# options for the tag (which are inherited), and the contents of the tag.
# Add a block of text to the contents of the current node, formatting it
# according to the current formatting instructions as we do.
sub _handle_text {
my ($self, $text) = @_;
DEBUG > 3 and print "== $text\n";
my $tag = $$self{PENDING}[-1];
$$tag[2] .= $self->format_text ($$tag[1], $text);
}
# Given an element name, get the corresponding method name.
sub method_for_element {
my ($self, $element) = @_;
$element =~ tr/A-Z-/a-z_/;
$element =~ tr/_a-z0-9//cd;
return $element;
}
# Handle the start of a new element. If cmd_element is defined, assume that
# we need to collect the entire tree for this element before passing it to the
# element method, and create a new tree into which we'll collect blocks of
# text and nested elements. Otherwise, if start_element is defined, call it.
sub _handle_element_start {
my ($self, $element, $attrs) = @_;
DEBUG > 3 and print "++ $element (<", join ('> <', %$attrs), ">)\n";
my $method = $self->method_for_element ($element);
# If we have a command handler, we need to accumulate the contents of the
# tag before calling it. Turn off IN_NAME for any command other than
# <Para> and the formatting codes so that IN_NAME isn't still set for the
# first heading after the NAME heading.
if ($self->can ("cmd_$method")) {
DEBUG > 2 and print "<$element> starts saving a tag\n";
$$self{IN_NAME} = 0 if ($element ne 'Para' && length ($element) > 1);
# How we're going to format embedded text blocks depends on the tag
# and also depends on our parent tags. Thankfully, inside tags that
# turn off guesswork and reformatting, nothing else can turn it back
# on, so this can be strictly inherited.
my $formatting = {
%{ $$self{PENDING}[-1][1] || $FORMATTING{DEFAULT} },
%{ $FORMATTING{$element} || {} },
};
push (@{ $$self{PENDING} }, [ $attrs, $formatting, '' ]);
DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
} elsif (my $start_method = $self->can ("start_$method")) {
$self->$start_method ($attrs, '');
} else {
DEBUG > 2 and print "No $method start method, skipping\n";
}
}
# Handle the end of an element. If we had a cmd_ method for this element,
# this is where we pass along the tree that we built. Otherwise, if we have
# an end_ method for the element, call that.
sub _handle_element_end {
my ($self, $element) = @_;
DEBUG > 3 and print "-- $element\n";
my $method = $self->method_for_element ($element);
# If we have a command handler, pull off the pending text and pass it to
# the handler along with the saved attribute hash.
if (my $cmd_method = $self->can ("cmd_$method")) {
DEBUG > 2 and print "</$element> stops saving a tag\n";
my $tag = pop @{ $$self{PENDING} };
DEBUG > 4 and print "Popped: [", pretty ($tag), "]\n";
DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
my $text = $self->$cmd_method ($$tag[0], $$tag[2]);
if (defined $text) {
if (@{ $$self{PENDING} } > 1) {
$$self{PENDING}[-1][2] .= $text;
} else {
$self->output ($text);
}
}
} elsif (my $end_method = $self->can ("end_$method")) {
$self->$end_method ();
} else {
DEBUG > 2 and print "No $method end method, skipping\n";
}
}
##############################################################################
# General formatting
##############################################################################
# Format a text block. Takes a hash of formatting options and the text to
# format. Currently, the only formatting options are guesswork, cleanup, and
# convert, all of which are boolean.
sub format_text {
my ($self, $options, $text) = @_;
my $guesswork = $$options{guesswork} && !$$self{IN_NAME};
my $cleanup = $$options{cleanup};
my $convert = $$options{convert};
my $literal = $$options{literal};
# Cleanup just tidies up a few things, telling *roff that the hyphens are
# hard, putting a bit of space between consecutive underscores, and
# escaping backslashes. Be careful not to mangle our character
# translations by doing this before processing character translation.
if ($cleanup) {
$text =~ s/\\/\\e/g;
$text =~ s/-/\\-/g;
$text =~ s/_(?=_)/_\\|/g;
}
# Normally we do character translation, but we won't even do that in
# <Data> blocks or if UTF-8 output is desired.
if ($convert && !$$self{utf8} && ASCII) {
$text =~ s/([^\x00-\x7F])/$ESCAPES{ord ($1)} || "X"/eg;
}
# Ensure that *roff doesn't convert literal quotes to UTF-8 single quotes,
# but don't mess up our accept escapes.
if ($literal) {
$text =~ s/(?<!\\\*)\'/\\*\(Aq/g;
$text =~ s/(?<!\\\*)\`/\\\`/g;
}
# If guesswork is asked for, do that. This involves more substantial
# formatting based on various heuristics that may only be appropriate for
# particular documents.
if ($guesswork) {
$text = $self->guesswork ($text);
}
return $text;
}
# Handles C<> text, deciding whether to put \*C` around it or not. This is a
# whole bunch of messy heuristics to try to avoid overquoting, originally from
# Barrie Slaymaker. This largely duplicates similar code in Pod::Text.
sub quote_literal {
my $self = shift;
local $_ = shift;
# A regex that matches the portion of a variable reference that's the
# array or hash index, separated out just because we want to use it in
# several places in the following regex.
my $index = '(?: \[.*\] | \{.*\} )?';
# If in NAME section, just return an ASCII quoted string to avoid
# confusing tools like whatis.
return qq{"$_"} if $$self{IN_NAME};
# Check for things that we don't want to quote, and if we find any of
# them, return the string with just a font change and no quoting.
m{
^\s*
(?:
( [\'\`\"] ) .* \1 # already quoted
| \\\*\(Aq .* \\\*\(Aq # quoted and escaped
| \\?\` .* ( \' | \\\*\(Aq ) # `quoted'
| \$+ [\#^]? \S $index # special ($^Foo, $")
| [\$\@%&*]+ \#? [:\'\w]+ $index # plain var or func
| [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call
| [-+]? ( \d[\d.]* | \.\d+ ) (?: [eE][-+]?\d+ )? # a number
| 0x [a-fA-F\d]+ # a hex constant
)
\s*\z
}xso and return '\f(FS' . $_ . '\f(FE';
# If we didn't return, go ahead and quote the text.
return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE";
}
# Takes a text block to perform guesswork on. Returns the text block with
# formatting codes added. This is the code that marks up various Perl
# constructs and things commonly used in man pages without requiring the user
# to add any explicit markup, and is applied to all non-literal text. We're
# guaranteed that the text we're applying guesswork to does not contain any
# *roff formatting codes. Note that the inserted font sequences must be
# treated later with mapfonts or textmapfonts.
#
# This method is very fragile, both in the regular expressions it uses and in
# the ordering of those modifications. Care and testing is required when
# modifying it.
sub guesswork {
my $self = shift;
local $_ = shift;
DEBUG > 5 and print " Guesswork called on [$_]\n";
# By the time we reach this point, all hyphens will be escaped by adding a
# backslash. We want to undo that escaping if they're part of regular
# words and there's only a single dash, since that's a real hyphen that
# *roff gets to consider a possible break point. Make sure that a dash
# after the first character of a word stays non-breaking, however.
#
# Note that this is not user-controllable; we pretty much have to do this
# transformation or *roff will mangle the output in unacceptable ways.
s{
( (?:\G|^|\s) [\(\"]* [a-zA-Z] ) ( \\- )?
( (?: [a-zA-Z\']+ \\-)+ )
( [a-zA-Z\']+ ) (?= [\)\".?!,;:]* (?:\s|\Z|\\\ ) )
\b
} {
my ($prefix, $hyphen, $main, $suffix) = ($1, $2, $3, $4);
$hyphen ||= '';
$main =~ s/\\-/-/g;
$prefix . $hyphen . $main . $suffix;
}egx;
# Translate "--" into a real em-dash if it's used like one. This means
# that it's either surrounded by whitespace, it follows a regular word, or
# it occurs between two regular words.
if ($$self{MAGIC_EMDASH}) {
s{ (\s) \\-\\- (\s) } { $1 . '\*(--' . $2 }egx;
s{ (\b[a-zA-Z]+) \\-\\- (\s|\Z|[a-zA-Z]+\b) } { $1 . '\*(--' . $2 }egx;
}
# Make words in all-caps a little bit smaller; they look better that way.
# However, we don't want to change Perl code (like @ARGV), nor do we want
# to fix the MIME in MIME-Version since it looks weird with the
# full-height V.
#
# We change only a string of all caps (2) either at the beginning of the
# line or following regular punctuation (like quotes) or whitespace (1),
# and followed by either similar punctuation, an em-dash, or the end of
# the line (3).
#
# Allow the text we're changing to small caps to include double quotes,
# commas, newlines, and periods as long as it doesn't otherwise interrupt
# the string of small caps and still fits the criteria. This lets us turn
# entire warranty disclaimers in man page output into small caps.
if ($$self{MAGIC_SMALLCAPS}) {
s{
( ^ | [\s\(\"\'\`\[\{<>] | \\[ ] ) # (1)
( [A-Z] [A-Z] (?: [/A-Z+:\d_\$&] | \\- | [.,\"\s] )* ) # (2)
(?= [\s>\}\]\(\)\'\".?!,;] | \\*\(-- | \\[ ] | $ ) # (3)
} {
$1 . '\s-1' . $2 . '\s0'
}egx;
}
# Note that from this point forward, we have to adjust for \s-1 and \s-0
# strings inserted around things that we've made small-caps if later
# transforms should work on those strings.
# Italicize functions in the form func(), including functions that are in
# all capitals, but don't italize if there's anything between the parens.
# The function must start with an alphabetic character or underscore and
# then consist of word characters or colons.
if ($$self{MAGIC_FUNC}) {
s{
( \b | \\s-1 )
( [A-Za-z_] ([:\w] | \\s-?[01])+ \(\) )
} {
$1 . '\f(IS' . $2 . '\f(IE'
}egx;
}
# Change references to manual pages to put the page name in italics but
# the number in the regular font, with a thin space between the name and
# the number. Only recognize func(n) where func starts with an alphabetic
# character or underscore and contains only word characters, periods (for
# configuration file man pages), or colons, and n is a single digit,
# optionally followed by some number of lowercase letters. Note that this
# does not recognize man page references like perl(l) or socket(3SOCKET).
if ($$self{MAGIC_MANREF}) {
s{
( \b | \\s-1 )
( [A-Za-z_] (?:[.:\w] | \\- | \\s-?[01])+ )
( \( \d [a-z]* \) )
} {
$1 . '\f(IS' . $2 . '\f(IE\|' . $3
}egx;
}
# Convert simple Perl variable references to a fixed-width font. Be
# careful not to convert functions, though; there are too many subtleties
# with them to want to perform this transformation.
if ($$self{MAGIC_VARS}) {
s{
( ^ | \s+ )
( [\$\@%] [\w:]+ )
(?! \( )
} {
$1 . '\f(FS' . $2 . '\f(FE'
}egx;
}
# Fix up double quotes. Unfortunately, we miss this transformation if the
# quoted text contains any code with formatting codes and there's not much
# we can effectively do about that, which makes it somewhat unclear if
# this is really a good idea.
s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;
# Make C++ into \*(C+, which is a squinched version.
if ($$self{MAGIC_CPP}) {
s{ \b C\+\+ } {\\*\(C+}gx;
}
# Done.
DEBUG > 5 and print " Guesswork returning [$_]\n";
return $_;
}
##############################################################################
# Output
##############################################################################
# When building up the *roff code, we don't use real *roff fonts. Instead, we
# embed font codes of the form \f(<font>[SE] where <font> is one of B, I, or
# F, S stands for start, and E stands for end. This method turns these into
# the right start and end codes.
#
# We add this level of complexity because the old pod2man didn't get code like
# B<someI<thing> else> right; after I<> it switched back to normal text rather
# than bold. We take care of this by using variables that state whether bold,
# italic, or fixed are turned on as a combined pointer to our current font
# sequence, and set each to the number of current nestings of start tags for
# that font.
#
# \fP changes to the previous font, but only one previous font is kept. We
# don't know what the outside level font is; normally it's R, but if we're
# inside a heading it could be something else. So arrange things so that the
# outside font is always the "previous" font and end with \fP instead of \fR.
# Idea from Zack Weinberg.
sub mapfonts {
my ($self, $text) = @_;
my ($fixed, $bold, $italic) = (0, 0, 0);
my %magic = (F => \$fixed, B => \$bold, I => \$italic);
my $last = '\fR';
$text =~ s<
\\f\((.)(.)
> <
my $sequence = '';
my $f;
if ($last ne '\fR') { $sequence = '\fP' }
${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
$f = $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
if ($f eq $last) {
'';
} else {
if ($f ne '\fR') { $sequence .= $f }
$last = $f;
$sequence;
}
>gxe;
return $text;
}
# Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU
# groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather
# than R, presumably because \f(CW doesn't actually do a font change. To work
# around this, use a separate textmapfonts for text blocks where the default
# font is always R and only use the smart mapfonts for headings.
sub textmapfonts {
my ($self, $text) = @_;
my ($fixed, $bold, $italic) = (0, 0, 0);
my %magic = (F => \$fixed, B => \$bold, I => \$italic);
$text =~ s<
\\f\((.)(.)
> <
${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
$$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
>gxe;
return $text;
}
# Given a command and a single argument that may or may not contain double
# quotes, handle double-quote formatting for it. If there are no double
# quotes, just return the command followed by the argument in double quotes.
# If there are double quotes, use an if statement to test for nroff, and for
# nroff output the command followed by the argument in double quotes with
# embedded double quotes doubled. For other formatters, remap paired double
# quotes to LQUOTE and RQUOTE.
sub switchquotes {
my ($self, $command, $text, $extra) = @_;
$text =~ s/\\\*\([LR]\"/\"/g;
# We also have to deal with \*C` and \*C', which are used to add the
# quotes around C<> text, since they may expand to " and if they do this
# confuses the .SH macros and the like no end. Expand them ourselves.
# Also separate troff from nroff if there are any fixed-width fonts in use
# to work around problems with Solaris nroff.
my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/);
my $fixedpat = join '|', @{ $$self{FONTS} }{'100', '101', '110', '111'};
$fixedpat =~ s/\\/\\\\/g;
$fixedpat =~ s/\(/\\\(/g;
if ($text =~ m/\"/ || $text =~ m/$fixedpat/) {
$text =~ s/\"/\"\"/g;
my $nroff = $text;
my $troff = $text;
$troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g;
if ($c_is_quote and $text =~ m/\\\*\(C[\'\`]/) {
$nroff =~ s/\\\*\(C\`/$$self{LQUOTE}/g;
$nroff =~ s/\\\*\(C\'/$$self{RQUOTE}/g;
$troff =~ s/\\\*\(C[\'\`]//g;
}
$nroff = qq("$nroff") . ($extra ? " $extra" : '');
$troff = qq("$troff") . ($extra ? " $extra" : '');
# Work around the Solaris nroff bug where \f(CW\fP leaves the font set
# to Roman rather than the actual previous font when used in headings.
# troff output may still be broken, but at least we can fix nroff by
# just switching the font changes to the non-fixed versions.
my $font_end = "(?:\\f[PR]|\Q$$self{FONTS}{100}\E)";
$nroff =~ s/\Q$$self{FONTS}{100}\E(.*?)\\f([PR])/$1/g;
$nroff =~ s/\Q$$self{FONTS}{101}\E(.*?)$font_end/\\fI$1\\fP/g;
$nroff =~ s/\Q$$self{FONTS}{110}\E(.*?)$font_end/\\fB$1\\fP/g;
$nroff =~ s/\Q$$self{FONTS}{111}\E(.*?)$font_end/\\f\(BI$1\\fP/g;
# Now finally output the command. Bother with .ie only if the nroff
# and troff output aren't the same.
if ($nroff ne $troff) {
return ".ie n $command $nroff\n.el $command $troff\n";
} else {
return "$command $nroff\n";
}
} else {
$text = qq("$text") . ($extra ? " $extra" : '');
return "$command $text\n";
}
}
# Protect leading quotes and periods against interpretation as commands. Also
# protect anything starting with a backslash, since it could expand or hide
# something that *roff would interpret as a command. This is overkill, but
# it's much simpler than trying to parse *roff here.
sub protect {
my ($self, $text) = @_;
$text =~ s/^([.\'\\])/\\&$1/mg;
return $text;
}
# Make vertical whitespace if NEEDSPACE is set, appropriate to the indentation
# level the situation. This function is needed since in *roff one has to
# create vertical whitespace after paragraphs and between some things, but
# other macros create their own whitespace. Also close out a sequence of
# repeated =items, since calling makespace means we're about to begin the item
# body.
sub makespace {
my ($self) = @_;
$self->output (".PD\n") if $$self{ITEMS} > 1;
$$self{ITEMS} = 0;
$self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n")
if $$self{NEEDSPACE};
}
# Output any pending index entries, and optionally an index entry given as an
# argument. Support multiple index entries in X<> separated by slashes, and
# strip special escapes from index entries.
sub outindex {
my ($self, $section, $index) = @_;
my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
return unless ($section || @entries);
# We're about to output all pending entries, so clear our pending queue.
$$self{INDEX} = [];
# Build the output. Regular index entries are marked Xref, and headings
# pass in their own section. Undo some *roff formatting on headings.
my @output;
if (@entries) {
push @output, [ 'Xref', join (' ', @entries) ];
}
if ($section) {
$index =~ s/\\-/-/g;
$index =~ s/\\(?:s-?\d|.\(..|.)//g;
push @output, [ $section, $index ];
}
# Print out the .IX commands.
for (@output) {
my ($type, $entry) = @$_;
$entry =~ s/\s+/ /g;
$entry =~ s/\"/\"\"/g;
$entry =~ s/\\/\\\\/g;
$self->output (".IX $type " . '"' . $entry . '"' . "\n");
}
}
# Output some text, without any additional changes.
sub output {
my ($self, @text) = @_;
if ($$self{ENCODE}) {
print { $$self{output_fh} } Encode::encode ('UTF-8', join ('', @text));
} else {
print { $$self{output_fh} } @text;
}
}
##############################################################################
# Document initialization
##############################################################################
# Handle the start of the document. Here we handle empty documents, as well
# as setting up our basic macros in a preamble and building the page title.
sub start_document {
my ($self, $attrs) = @_;
if ($$attrs{contentless} && !$$self{ALWAYS_EMIT_SOMETHING}) {
DEBUG and print "Document is contentless\n";
$$self{CONTENTLESS} = 1;
} else {
delete $$self{CONTENTLESS};
}
# When UTF-8 output is set, check whether our output file handle already
# has a PerlIO encoding layer set. If it does not, we'll need to encode
# our output before printing it (handled in the output() sub). Wrap the
# check in an eval to handle versions of Perl without PerlIO.
$$self{ENCODE} = 0;
if ($$self{utf8}) {
$$self{ENCODE} = 1;
eval {
my @options = (output => 1, details => 1);
my $flag = (PerlIO::get_layers ($$self{output_fh}, @options))[-1];
if ($flag & PerlIO::F_UTF8 ()) {
$$self{ENCODE} = 0;
}
}
}
# Determine information for the preamble and then output it unless the
# document was content-free.
if (!$$self{CONTENTLESS}) {
my ($name, $section);
if (defined $$self{name}) {
$name = $$self{name};
$section = $$self{section} || 1;
} else {
($name, $section) = $self->devise_title;
}
my $date = defined($$self{date}) ? $$self{date} : $self->devise_date;
$self->preamble ($name, $section, $date)
unless $self->bare_output or DEBUG > 9;
}
# Initialize a few per-document variables.
$$self{INDENT} = 0; # Current indentation level.
$$self{INDENTS} = []; # Stack of indentations.
$$self{INDEX} = []; # Index keys waiting to be printed.
$$self{IN_NAME} = 0; # Whether processing the NAME section.
$$self{ITEMS} = 0; # The number of consecutive =items.
$$self{ITEMTYPES} = []; # Stack of =item types, one per list.
$$self{SHIFTWAIT} = 0; # Whether there is a shift waiting.
$$self{SHIFTS} = []; # Stack of .RS shifts.
$$self{PENDING} = [[]]; # Pending output.
}
# Handle the end of the document. This handles dying on POD errors, since
# Pod::Parser currently doesn't. Otherwise, does nothing but print out a
# final comment at the end of the document under debugging.
sub end_document {
my ($self) = @_;
if ($$self{complain_die} && $self->errors_seen) {
croak ("POD document had syntax errors");
}
return if $self->bare_output;
return if ($$self{CONTENTLESS} && !$$self{ALWAYS_EMIT_SOMETHING});
$self->output (q(.\" [End document]) . "\n") if DEBUG;
}
# Try to figure out the name and section from the file name and return them as
# a list, returning an empty name and section 1 if we can't find any better
# information. Uses File::Basename and File::Spec as necessary.
sub devise_title {
my ($self) = @_;
my $name = $self->source_filename || '';
my $section = $$self{section} || 1;
$section = 3 if (!$$self{section} && $name =~ /\.pm\z/i);
$name =~ s/\.p(od|[lm])\z//i;
# If Pod::Parser gave us an IO::File reference as the source file name,
# convert that to the empty string as well. Then, if we don't have a
# valid name, emit a warning and convert it to STDIN.
if ($name =~ /^IO::File(?:=\w+)\(0x[\da-f]+\)$/i) {
$name = '';
}
if ($name eq '') {
$self->whine (1, 'No name given for document');
$name = 'STDIN';
}
# If the section isn't 3, then the name defaults to just the basename of
# the file.
if ($section !~ /^3/) {
require File::Basename;
$name = uc File::Basename::basename ($name);
} else {
require File::Spec;
my ($volume, $dirs, $file) = File::Spec->splitpath ($name);
# Otherwise, assume we're dealing with a module. We want to figure
# out the full module name from the path to the file, but we don't
# want to include too much of the path into the module name. Lose
# anything up to the first of:
#
# */lib/*perl*/ standard or site_perl module
# */*perl*/lib/ from -Dprefix=/opt/perl
# */*perl*/ random module hierarchy
#
# Also strip off a leading site, site_perl, or vendor_perl component,
# any OS-specific component, and any version number component, and
# strip off an initial component of "lib" or "blib/lib" since that's
# what ExtUtils::MakeMaker creates.
#
# splitdir requires at least File::Spec 0.8.
my @dirs = File::Spec->splitdir ($dirs);
if (@dirs) {
my $cut = 0;
my $i;
for ($i = 0; $i < @dirs; $i++) {
if ($dirs[$i] =~ /perl/) {
$cut = $i + 1;
$cut++ if ($dirs[$i + 1] && $dirs[$i + 1] eq 'lib');
last;
}
}
if ($cut > 0) {
splice (@dirs, 0, $cut);
shift @dirs if ($dirs[0] =~ /^(site|vendor)(_perl)?$/);
shift @dirs if ($dirs[0] =~ /^[\d.]+$/);
shift @dirs if ($dirs[0] =~ /^(.*-$^O|$^O-.*|$^O)$/);
}
shift @dirs if $dirs[0] eq 'lib';
splice (@dirs, 0, 2) if ($dirs[0] eq 'blib' && $dirs[1] eq 'lib');
}
# Remove empty directories when building the module name; they
# occur too easily on Unix by doubling slashes.
$name = join ('::', (grep { $_ ? $_ : () } @dirs), $file);
}
return ($name, $section);
}
# Determine the modification date and return that, properly formatted in ISO
# format.
#
# If POD_MAN_DATE is set, that overrides anything else. This can be used for
# reproducible generation of the same file even if the input file timestamps
# are unpredictable or the POD coms from standard input.
#
# Otherwise, if SOURCE_DATE_EPOCH is set and can be parsed as seconds since
# the UNIX epoch, base the timestamp on that. See
# <https://reproducible-builds.org/specs/source-date-epoch/>
#
# Otherwise, use the modification date of the input if we can stat it. Be
# aware that Pod::Simple returns the stringification of the file handle as
# source_filename for input from a file handle, so we'll stat some random ref
# string in that case. If that fails, instead use the current time.
#
# $self - Pod::Man object, used to get the source file
#
# Returns: YYYY-MM-DD date suitable for the left-hand footer
sub devise_date {
my ($self) = @_;
# If POD_MAN_DATE is set, always use it.
if (defined($ENV{POD_MAN_DATE})) {
return $ENV{POD_MAN_DATE};
}
# If SOURCE_DATE_EPOCH is set and can be parsed, use that.
my $time;
if (defined($ENV{SOURCE_DATE_EPOCH}) && $ENV{SOURCE_DATE_EPOCH} !~ /\D/) {
$time = $ENV{SOURCE_DATE_EPOCH};
}
# Otherwise, get the input filename and try to stat it. If that fails,
# use the current time.
if (!defined $time) {
my $input = $self->source_filename;
if ($input) {
$time = (stat($input))[9] || time();
} else {
$time = time();
}
}
# Can't use POSIX::strftime(), which uses Fcntl, because MakeMaker uses
# this and it has to work in the core which can't load dynamic libraries.
# Use gmtime instead of localtime so that the generated man page does not
# depend on the local time zone setting and is more reproducible
my ($year, $month, $day) = (gmtime($time))[5,4,3];
return sprintf("%04d-%02d-%02d", $year + 1900, $month + 1, $day);
}
# Print out the preamble and the title. The meaning of the arguments to .TH
# unfortunately vary by system; some systems consider the fourth argument to
# be a "source" and others use it as a version number. Generally it's just
# presented as the left-side footer, though, so it doesn't matter too much if
# a particular system gives it another interpretation.
#
# The order of date and release used to be reversed in older versions of this
# module, but this order is correct for both Solaris and Linux.
sub preamble {
my ($self, $name, $section, $date) = @_;
my $preamble = $self->preamble_template (!$$self{utf8});
# Build the index line and make sure that it will be syntactically valid.
my $index = "$name $section";
$index =~ s/\"/\"\"/g;
# If name or section contain spaces, quote them (section really never
# should, but we may as well be cautious).
for ($name, $section) {
if (/\s/) {
s/\"/\"\"/g;
$_ = '"' . $_ . '"';
}
}
# Double quotes in date, since it will be quoted.
$date =~ s/\"/\"\"/g;
# Substitute into the preamble the configuration options.
$preamble =~ s/\@CFONT\@/$$self{fixed}/;
$preamble =~ s/\@LQUOTE\@/$$self{LQUOTE}/;
$preamble =~ s/\@RQUOTE\@/$$self{RQUOTE}/;
chomp $preamble;
# Get the version information.
my $version = $self->version_report;
# Finally output everything.
$self->output (<<"----END OF HEADER----");
.\\" Automatically generated by $version
.\\"
.\\" Standard preamble:
.\\" ========================================================================
$preamble
.\\" ========================================================================
.\\"
.IX Title "$index"
.TH $name $section "$date" "$$self{release}" "$$self{center}"
.\\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\\" way too many mistakes in technical documents.
.if n .ad l
.nh
----END OF HEADER----
$self->output (".\\\" [End of preamble]\n") if DEBUG;
}
##############################################################################
# Text blocks
##############################################################################
# Handle a basic block of text. The only tricky part of this is if this is
# the first paragraph of text after an =over, in which case we have to change
# indentations for *roff.
sub cmd_para {
my ($self, $attrs, $text) = @_;
my $line = $$attrs{start_line};
# Output the paragraph. We also have to handle =over without =item. If
# there's an =over without =item, SHIFTWAIT will be set, and we need to
# handle creation of the indent here. Add the shift to SHIFTS so that it
# will be cleaned up on =back.
$self->makespace;
if ($$self{SHIFTWAIT}) {
$self->output (".RS $$self{INDENT}\n");
push (@{ $$self{SHIFTS} }, $$self{INDENT});
$$self{SHIFTWAIT} = 0;
}
# Add the line number for debugging, but not in the NAME section just in
# case the comment would confuse apropos.
$self->output (".\\\" [At source line $line]\n")
if defined ($line) && DEBUG && !$$self{IN_NAME};
# Force exactly one newline at the end and strip unwanted trailing
# whitespace at the end, but leave "\ " backslashed space from an S< > at
# the end of a line. Reverse the text first, to avoid having to scan the
# entire paragraph.
$text = reverse $text;
$text =~ s/\A\s*?(?= \\|\S|\z)/\n/;
$text = reverse $text;
# Output the paragraph.
$self->output ($self->protect ($self->textmapfonts ($text)));
$self->outindex;
$$self{NEEDSPACE} = 1;
return '';
}
# Handle a verbatim paragraph. Put a null token at the beginning of each line
# to protect against commands and wrap in .Vb/.Ve (which we define in our
# prelude).
sub cmd_verbatim {
my ($self, $attrs, $text) = @_;
# Ignore an empty verbatim paragraph.
return unless $text =~ /\S/;
# Force exactly one newline at the end and strip unwanted trailing
# whitespace at the end. Reverse the text first, to avoid having to scan
# the entire paragraph.
$text = reverse $text;
$text =~ s/\A\s*/\n/;
$text = reverse $text;
# Get a count of the number of lines before the first blank line, which
# we'll pass to .Vb as its parameter. This tells *roff to keep that many
# lines together. We don't want to tell *roff to keep huge blocks
# together.
my @lines = split (/\n/, $text);
my $unbroken = 0;
for (@lines) {
last if /^\s*$/;
$unbroken++;
}
$unbroken = 10 if ($unbroken > 12 && !$$self{MAGIC_VNOPAGEBREAK_LIMIT});
# Prepend a null token to each line.
$text =~ s/^/\\&/gm;
# Output the results.
$self->makespace;
$self->output (".Vb $unbroken\n$text.Ve\n");
$$self{NEEDSPACE} = 1;
return '';
}
# Handle literal text (produced by =for and similar constructs). Just output
# it with the minimum of changes.
sub cmd_data {
my ($self, $attrs, $text) = @_;
$text =~ s/^\n+//;
$text =~ s/\n{0,2}$/\n/;
$self->output ($text);
return '';
}
##############################################################################
# Headings
##############################################################################
# Common code for all headings. This is called before the actual heading is
# output. It returns the cleaned up heading text (putting the heading all on
# one line) and may do other things, like closing bad =item blocks.
sub heading_common {
my ($self, $text, $line) = @_;
$text =~ s/\s+$//;
$text =~ s/\s*\n\s*/ /g;
# This should never happen; it means that we have a heading after =item
# without an intervening =back. But just in case, handle it anyway.
if ($$self{ITEMS} > 1) {
$$self{ITEMS} = 0;
$self->output (".PD\n");
}
# Output the current source line.
$self->output ( ".\\\" [At source line $line]\n" )
if defined ($line) && DEBUG;
return $text;
}
# First level heading. We can't output .IX in the NAME section due to a bug
# in some versions of catman, so don't output a .IX for that section. .SH
# already uses small caps, so remove \s0 and \s-1. Maintain IN_NAME as
# appropriate.
sub cmd_head1 {
my ($self, $attrs, $text) = @_;
$text =~ s/\\s-?\d//g;
$text = $self->heading_common ($text, $$attrs{start_line});
my $isname = ($text eq 'NAME' || $text =~ /\(NAME\)/);
$self->output ($self->switchquotes ('.SH', $self->mapfonts ($text)));
$self->outindex ('Header', $text) unless $isname;
$$self{NEEDSPACE} = 0;
$$self{IN_NAME} = $isname;
return '';
}
# Second level heading.
sub cmd_head2 {
my ($self, $attrs, $text) = @_;
$text = $self->heading_common ($text, $$attrs{start_line});
$self->output ($self->switchquotes ('.SS', $self->mapfonts ($text)));
$self->outindex ('Subsection', $text);
$$self{NEEDSPACE} = 0;
return '';
}
# Third level heading. *roff doesn't have this concept, so just put the
# heading in italics as a normal paragraph.
sub cmd_head3 {
my ($self, $attrs, $text) = @_;
$text = $self->heading_common ($text, $$attrs{start_line});
$self->makespace;
$self->output ($self->textmapfonts ('\f(IS' . $text . '\f(IE') . "\n");
$self->outindex ('Subsection', $text);
$$self{NEEDSPACE} = 1;
return '';
}
# Fourth level heading. *roff doesn't have this concept, so just put the
# heading as a normal paragraph.
sub cmd_head4 {
my ($self, $attrs, $text) = @_;
$text = $self->heading_common ($text, $$attrs{start_line});
$self->makespace;
$self->output ($self->textmapfonts ($text) . "\n");
$self->outindex ('Subsection', $text);
$$self{NEEDSPACE} = 1;
return '';
}
##############################################################################
# Formatting codes
##############################################################################
# All of the formatting codes that aren't handled internally by the parser,
# other than L<> and X<>.
sub cmd_b { return $_[0]->{IN_NAME} ? $_[2] : '\f(BS' . $_[2] . '\f(BE' }
sub cmd_i { return $_[0]->{IN_NAME} ? $_[2] : '\f(IS' . $_[2] . '\f(IE' }
sub cmd_f { return $_[0]->{IN_NAME} ? $_[2] : '\f(IS' . $_[2] . '\f(IE' }
sub cmd_c { return $_[0]->quote_literal ($_[2]) }
# Index entries are just added to the pending entries.
sub cmd_x {
my ($self, $attrs, $text) = @_;
push (@{ $$self{INDEX} }, $text);
return '';
}
# Links reduce to the text that we're given, wrapped in angle brackets if it's
# a URL, followed by the URL. We take an option to suppress the URL if anchor
# text is given. We need to format the "to" value of the link before
# comparing it to the text since we may escape hyphens.
sub cmd_l {
my ($self, $attrs, $text) = @_;
if ($$attrs{type} eq 'url') {
my $to = $$attrs{to};
if (defined $to) {
my $tag = $$self{PENDING}[-1];
$to = $self->format_text ($$tag[1], $to);
}
if (not defined ($to) or $to eq $text) {
return "<$text>";
} elsif ($$self{nourls}) {
return $text;
} else {
return "$text <$$attrs{to}>";
}
} else {
return $text;
}
}
##############################################################################
# List handling
##############################################################################
# Handle the beginning of an =over block. Takes the type of the block as the
# first argument, and then the attr hash. This is called by the handlers for
# the four different types of lists (bullet, number, text, and block).
sub over_common_start {
my ($self, $type, $attrs) = @_;
my $line = $$attrs{start_line};
my $indent = $$attrs{indent};
DEBUG > 3 and print " Starting =over $type (line $line, indent ",
($indent || '?'), "\n";
# Find the indentation level.
unless (defined ($indent) && $indent =~ /^[-+]?\d{1,4}\s*$/) {
$indent = $$self{indent};
}
# If we've gotten multiple indentations in a row, we need to emit the
# pending indentation for the last level that we saw and haven't acted on
# yet. SHIFTS is the stack of indentations that we've actually emitted
# code for.
if (@{ $$self{SHIFTS} } < @{ $$self{INDENTS} }) {
$self->output (".RS $$self{INDENT}\n");
push (@{ $$self{SHIFTS} }, $$self{INDENT});
}
# Now, do record-keeping. INDENTS is a stack of indentations that we've
# seen so far, and INDENT is the current level of indentation. ITEMTYPES
# is a stack of list types that we've seen.
push (@{ $$self{INDENTS} }, $$self{INDENT});
push (@{ $$self{ITEMTYPES} }, $type);
$$self{INDENT} = $indent + 0;
$$self{SHIFTWAIT} = 1;
}
# End an =over block. Takes no options other than the class pointer.
# Normally, once we close a block and therefore remove something from INDENTS,
# INDENTS will now be longer than SHIFTS, indicating that we also need to emit
# *roff code to close the indent. This isn't *always* true, depending on the
# circumstance. If we're still inside an indentation, we need to emit another
# .RE and then a new .RS to unconfuse *roff.
sub over_common_end {
my ($self) = @_;
DEBUG > 3 and print " Ending =over\n";
$$self{INDENT} = pop @{ $$self{INDENTS} };
pop @{ $$self{ITEMTYPES} };
# If we emitted code for that indentation, end it.
if (@{ $$self{SHIFTS} } > @{ $$self{INDENTS} }) {
$self->output (".RE\n");
pop @{ $$self{SHIFTS} };
}
# If we're still in an indentation, *roff will have now lost track of the
# right depth of that indentation, so fix that.
if (@{ $$self{INDENTS} } > 0) {
$self->output (".RE\n");
$self->output (".RS $$self{INDENT}\n");
}
$$self{NEEDSPACE} = 1;
$$self{SHIFTWAIT} = 0;
}
# Dispatch the start and end calls as appropriate.
sub start_over_bullet { my $s = shift; $s->over_common_start ('bullet', @_) }
sub start_over_number { my $s = shift; $s->over_common_start ('number', @_) }
sub start_over_text { my $s = shift; $s->over_common_start ('text', @_) }
sub start_over_block { my $s = shift; $s->over_common_start ('block', @_) }
sub end_over_bullet { $_[0]->over_common_end }
sub end_over_number { $_[0]->over_common_end }
sub end_over_text { $_[0]->over_common_end }
sub end_over_block { $_[0]->over_common_end }
# The common handler for all item commands. Takes the type of the item, the
# attributes, and then the text of the item.
#
# Emit an index entry for anything that's interesting, but don't emit index
# entries for things like bullets and numbers. Newlines in an item title are
# turned into spaces since *roff can't handle them embedded.
sub item_common {
my ($self, $type, $attrs, $text) = @_;
my $line = $$attrs{start_line};
DEBUG > 3 and print " $type item (line $line): $text\n";
# Clean up the text. We want to end up with two variables, one ($text)
# which contains any body text after taking out the item portion, and
# another ($item) which contains the actual item text.
$text =~ s/\s+$//;
my ($item, $index);
if ($type eq 'bullet') {
$item = "\\\(bu";
$text =~ s/\n*$/\n/;
} elsif ($type eq 'number') {
$item = $$attrs{number} . '.';
} else {
$item = $text;
$item =~ s/\s*\n\s*/ /g;
$text = '';
$index = $item if ($item =~ /\w/);
}
# Take care of the indentation. If shifts and indents are equal, close
# the top shift, since we're about to create an indentation with .IP.
# Also output .PD 0 to turn off spacing between items if this item is
# directly following another one. We only have to do that once for a
# whole chain of items so do it for the second item in the change. Note
# that makespace is what undoes this.
if (@{ $$self{SHIFTS} } == @{ $$self{INDENTS} }) {
$self->output (".RE\n");
pop @{ $$self{SHIFTS} };
}
$self->output (".PD 0\n") if ($$self{ITEMS} == 1);
# Now, output the item tag itself.
$item = $self->textmapfonts ($item);
$self->output ($self->switchquotes ('.IP', $item, $$self{INDENT}));
$$self{NEEDSPACE} = 0;
$$self{ITEMS}++;
$$self{SHIFTWAIT} = 0;
# If body text for this item was included, go ahead and output that now.
if ($text) {
$text =~ s/\s*$/\n/;
$self->makespace;
$self->output ($self->protect ($self->textmapfonts ($text)));
$$self{NEEDSPACE} = 1;
}
$self->outindex ($index ? ('Item', $index) : ());
}
# Dispatch the item commands to the appropriate place.
sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) }
sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) }
sub cmd_item_text { my $self = shift; $self->item_common ('text', @_) }
sub cmd_item_block { my $self = shift; $self->item_common ('block', @_) }
##############################################################################
# Backward compatibility
##############################################################################
# Reset the underlying Pod::Simple object between calls to parse_from_file so
# that the same object can be reused to convert multiple pages.
sub parse_from_file {
my $self = shift;
$self->reinit;
# Fake the old cutting option to Pod::Parser. This fiddings with internal
# Pod::Simple state and is quite ugly; we need a better approach.
if (ref ($_[0]) eq 'HASH') {
my $opts = shift @_;
if (defined ($$opts{-cutting}) && !$$opts{-cutting}) {
$$self{in_pod} = 1;
$$self{last_was_blank} = 1;
}
}
# Do the work.
my $retval = $self->SUPER::parse_from_file (@_);
# Flush output, since Pod::Simple doesn't do this. Ideally we should also
# close the file descriptor if we had to open one, but we can't easily
# figure this out.
my $fh = $self->output_fh ();
my $oldfh = select $fh;
my $oldflush = $|;
$| = 1;
print $fh '';
$| = $oldflush;
select $oldfh;
return $retval;
}
# Pod::Simple failed to provide this backward compatibility function, so
# implement it ourselves. File handles are one of the inputs that
# parse_from_file supports.
sub parse_from_filehandle {
my $self = shift;
return $self->parse_from_file (@_);
}
# Pod::Simple's parse_file doesn't set output_fh. Wrap the call and do so
# ourself unless it was already set by the caller, since our documentation has
# always said that this should work.
sub parse_file {
my ($self, $in) = @_;
unless (defined $$self{output_fh}) {
$self->output_fh (\*STDOUT);
}
return $self->SUPER::parse_file ($in);
}
# Do the same for parse_lines, just to be polite. Pod::Simple's man page
# implies that the caller is responsible for setting this, but I don't see any
# reason not to set a default.
sub parse_lines {
my ($self, @lines) = @_;
unless (defined $$self{output_fh}) {
$self->output_fh (\*STDOUT);
}
return $self->SUPER::parse_lines (@lines);
}
# Likewise for parse_string_document.
sub parse_string_document {
my ($self, $doc) = @_;
unless (defined $$self{output_fh}) {
$self->output_fh (\*STDOUT);
}
return $self->SUPER::parse_string_document ($doc);
}
##############################################################################
# Translation tables
##############################################################################
# The following table is adapted from Tom Christiansen's pod2man. It assumes
# that the standard preamble has already been printed, since that's what
# defines all of the accent marks. We really want to do something better than
# this when *roff actually supports other character sets itself, since these
# results are pretty poor.
#
# This only works in an ASCII world. What to do in a non-ASCII world is very
# unclear -- hopefully we can assume UTF-8 and just leave well enough alone.
@ESCAPES{0xA0 .. 0xFF} = (
"\\ ", undef, undef, undef, undef, undef, undef, undef,
undef, undef, undef, undef, undef, "\\%", undef, undef,
undef, undef, undef, undef, undef, undef, undef, undef,
undef, undef, undef, undef, undef, undef, undef, undef,
"A\\*`", "A\\*'", "A\\*^", "A\\*~", "A\\*:", "A\\*o", "\\*(Ae", "C\\*,",
"E\\*`", "E\\*'", "E\\*^", "E\\*:", "I\\*`", "I\\*'", "I\\*^", "I\\*:",
"\\*(D-", "N\\*~", "O\\*`", "O\\*'", "O\\*^", "O\\*~", "O\\*:", undef,
"O\\*/", "U\\*`", "U\\*'", "U\\*^", "U\\*:", "Y\\*'", "\\*(Th", "\\*8",
"a\\*`", "a\\*'", "a\\*^", "a\\*~", "a\\*:", "a\\*o", "\\*(ae", "c\\*,",
"e\\*`", "e\\*'", "e\\*^", "e\\*:", "i\\*`", "i\\*'", "i\\*^", "i\\*:",
"\\*(d-", "n\\*~", "o\\*`", "o\\*'", "o\\*^", "o\\*~", "o\\*:", undef,
"o\\*/" , "u\\*`", "u\\*'", "u\\*^", "u\\*:", "y\\*'", "\\*(th", "y\\*:",
) if ASCII;
##############################################################################
# Premable
##############################################################################
# The following is the static preamble which starts all *roff output we
# generate. Most is static except for the font to use as a fixed-width font,
# which is designed by @CFONT@, and the left and right quotes to use for C<>
# text, designated by @LQOUTE@ and @RQUOTE@. However, the second part, which
# defines the accent marks, is only used if $escapes is set to true.
sub preamble_template {
my ($self, $accents) = @_;
my $preamble = <<'----END OF PREAMBLE----';
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft @CFONT@
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
.\" nothing in troff, for use with C<>.
.tr \(*W-
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` @LQUOTE@
. ds C' @RQUOTE@
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
. ds C`
. ds C'
'br\}
.\"
.\" Escape single quotes in literal strings from groff's Unicode transform.
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\"
.\" If the F register is >0, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.\"
.\" Avoid warning from groff about undefined register 'F'.
.de IX
..
.if !\nF .nr F 0
.if \nF>0 \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. if !\nF==2 \{\
. nr % 0
. nr F 2
. \}
.\}
----END OF PREAMBLE----
#'# for cperl-mode
if ($accents) {
$preamble .= <<'----END OF PREAMBLE----'
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
----END OF PREAMBLE----
#`# for cperl-mode
}
return $preamble;
}
##############################################################################
# Module return value and documentation
##############################################################################
1;
__END__
=for stopwords
en em ALLCAPS teeny fixedbold fixeditalic fixedbolditalic stderr utf8
UTF-8 Allbery Sean Burke Ossanna Solaris formatters troff uppercased
Christiansen nourls parsers Kernighan
=head1 NAME
Pod::Man - Convert POD data to formatted *roff input
=head1 SYNOPSIS
use Pod::Man;
my $parser = Pod::Man->new (release => $VERSION, section => 8);
# Read POD from STDIN and write to STDOUT.
$parser->parse_file (\*STDIN);
# Read POD from file.pod and write to file.1.
$parser->parse_from_file ('file.pod', 'file.1');
=head1 DESCRIPTION
Pod::Man is a module to convert documentation in the POD format (the
preferred language for documenting Perl) into *roff input using the man
macro set. The resulting *roff code is suitable for display on a terminal
using L<nroff(1)>, normally via L<man(1)>, or printing using L<troff(1)>.
It is conventionally invoked using the driver script B<pod2man>, but it can
also be used directly.
As a derived class from Pod::Simple, Pod::Man supports the same methods and
interfaces. See L<Pod::Simple> for all the details.
new() can take options, in the form of key/value pairs that control the
behavior of the parser. See below for details.
If no options are given, Pod::Man uses the name of the input file with any
trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
section 1 unless the file ended in C<.pm> in which case it defaults to
section 3, to a centered title of "User Contributed Perl Documentation", to
a centered footer of the Perl version it is run with, and to a left-hand
footer of the modification date of its input (or the current date if given
C<STDIN> for input).
Pod::Man assumes that your *roff formatters have a fixed-width font named
C<CW>. If yours is called something else (like C<CR>), use the C<fixed>
option to specify it. This generally only matters for troff output for
printing. Similarly, you can set the fonts used for bold, italic, and
bold italic fixed-width output.
Besides the obvious pod conversions, Pod::Man also takes care of
formatting func(), func(3), and simple variable references like $foo or
@bar so you don't have to use code escapes for them; complex expressions
like C<$fred{'stuff'}> will still need to be escaped, though. It also
translates dashes that aren't used as hyphens into en dashes, makes long
dashes--like this--into proper em dashes, fixes "paired quotes," makes C++
look right, puts a little space between double underscores, makes ALLCAPS
a teeny bit smaller in B<troff>, and escapes stuff that *roff treats as
special so that you don't have to.
The recognized options to new() are as follows. All options take a single
argument.
=over 4
=item center
Sets the centered page header for the C<.TH> macro. The default, if this
option is not specified, is "User Contributed Perl Documentation".
=item date
Sets the left-hand footer for the C<.TH> macro. If this option is not set,
the contents of the environment variable POD_MAN_DATE, if set, will be used.
Failing that, the value of SOURCE_DATE_EPOCH, the modification date of the
input file, or the current time if stat() can't find that file (which will be
the case if the input is from C<STDIN>) will be used. If obtained from the
file modification date or the current time, the date will be formatted as
C<YYYY-MM-DD> and will be based on UTC (so that the output will be
reproducible regardless of local time zone).
=item errors
How to report errors. C<die> says to throw an exception on any POD
formatting error. C<stderr> says to report errors on standard error, but
not to throw an exception. C<pod> says to include a POD ERRORS section
in the resulting documentation summarizing the errors. C<none> ignores
POD errors entirely, as much as possible.
The default is C<pod>.
=item fixed
The fixed-width font to use for verbatim text and code. Defaults to
C<CW>. Some systems may want C<CR> instead. Only matters for B<troff>
output.
=item fixedbold
Bold version of the fixed-width font. Defaults to C<CB>. Only matters
for B<troff> output.
=item fixeditalic
Italic version of the fixed-width font (actually, something of a misnomer,
since most fixed-width fonts only have an oblique version, not an italic
version). Defaults to C<CI>. Only matters for B<troff> output.
=item fixedbolditalic
Bold italic (probably actually oblique) version of the fixed-width font.
Pod::Man doesn't assume you have this, and defaults to C<CB>. Some
systems (such as Solaris) have this font available as C<CX>. Only matters
for B<troff> output.
=item name
Set the name of the manual page for the C<.TH> macro. Without this
option, the manual name is set to the uppercased base name of the file
being converted unless the manual section is 3, in which case the path is
parsed to see if it is a Perl module path. If it is, a path like
C<.../lib/Pod/Man.pm> is converted into a name like C<Pod::Man>. This
option, if given, overrides any automatic determination of the name.
If generating a manual page from standard input, this option is required,
since there's otherwise no way for Pod::Man to know what to use for the
manual page name.
=item nourls
Normally, LZ<><> formatting codes with a URL but anchor text are formatted
to show both the anchor text and the URL. In other words:
L<foo|http://example.com/>
is formatted as:
foo <http://example.com/>
This option, if set to a true value, suppresses the URL when anchor text
is given, so this example would be formatted as just C<foo>. This can
produce less cluttered output in cases where the URLs are not particularly
important.
=item quotes
Sets the quote marks used to surround CE<lt>> text. If the value is a
single character, it is used as both the left and right quote. Otherwise,
it is split in half, and the first half of the string is used as the left
quote and the second is used as the right quote.
This may also be set to the special value C<none>, in which case no quote
marks are added around CE<lt>> text (but the font is still changed for troff
output).
=item release
Set the centered footer for the C<.TH> macro. By default, this is set to
the version of Perl you run Pod::Man under. Setting this to the empty
string will cause some *roff implementations to use the system default
value.
Note that some system C<an> macro sets assume that the centered footer
will be a modification date and will prepend something like "Last
modified: ". If this is the case for your target system, you may want to
set C<release> to the last modified date and C<date> to the version
number.
=item section
Set the section for the C<.TH> macro. The standard section numbering
convention is to use 1 for user commands, 2 for system calls, 3 for
functions, 4 for devices, 5 for file formats, 6 for games, 7 for
miscellaneous information, and 8 for administrator commands. There is a lot
of variation here, however; some systems (like Solaris) use 4 for file
formats, 5 for miscellaneous information, and 7 for devices. Still others
use 1m instead of 8, or some mix of both. About the only section numbers
that are reliably consistent are 1, 2, and 3.
By default, section 1 will be used unless the file ends in C<.pm> in which
case section 3 will be selected.
=item stderr
Send error messages about invalid POD to standard error instead of
appending a POD ERRORS section to the generated *roff output. This is
equivalent to setting C<errors> to C<stderr> if C<errors> is not already
set. It is supported for backward compatibility.
=item utf8
By default, Pod::Man produces the most conservative possible *roff output
to try to ensure that it will work with as many different *roff
implementations as possible. Many *roff implementations cannot handle
non-ASCII characters, so this means all non-ASCII characters are converted
either to a *roff escape sequence that tries to create a properly accented
character (at least for troff output) or to C<X>.
If this option is set, Pod::Man will instead output UTF-8. If your *roff
implementation can handle it, this is the best output format to use and
avoids corruption of documents containing non-ASCII characters. However,
be warned that *roff source with literal UTF-8 characters is not supported
by many implementations and may even result in segfaults and other bad
behavior.
Be aware that, when using this option, the input encoding of your POD
source should be properly declared unless it's US-ASCII. Pod::Simple will
attempt to guess the encoding and may be successful if it's Latin-1 or
UTF-8, but it will produce warnings. Use the C<=encoding> command to
declare the encoding. See L<perlpod(1)> for more information.
=back
The standard Pod::Simple method parse_file() takes one argument naming the
POD file to read from. By default, the output is sent to C<STDOUT>, but
this can be changed with the output_fh() method.
The standard Pod::Simple method parse_from_file() takes up to two
arguments, the first being the input file to read POD from and the second
being the file to write the formatted output to.
You can also call parse_lines() to parse an array of lines or
parse_string_document() to parse a document already in memory. As with
parse_file(), parse_lines() and parse_string_document() default to sending
their output to C<STDOUT> unless changed with the output_fh() method.
To put the output from any parse method into a string instead of a file
handle, call the output_string() method instead of output_fh().
See L<Pod::Simple> for more specific details on the methods available to
all derived parsers.
=head1 DIAGNOSTICS
=over 4
=item roff font should be 1 or 2 chars, not "%s"
(F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
wasn't either one or two characters. Pod::Man doesn't support *roff fonts
longer than two characters, although some *roff extensions do (the
canonical versions of B<nroff> and B<troff> don't either).
=item Invalid errors setting "%s"
(F) The C<errors> parameter to the constructor was set to an unknown value.
=item Invalid quote specification "%s"
(F) The quote specification given (the C<quotes> option to the
constructor) was invalid. A quote specification must be either one
character long or an even number (greater than one) characters long.
=item POD document had syntax errors
(F) The POD document being formatted had syntax errors and the C<errors>
option was set to C<die>.
=back
=head1 ENVIRONMENT
=over 4
=item PERL_CORE
If set and Encode is not available, silently fall back to non-UTF-8 mode
without complaining to standard error. This environment variable is set
during Perl core builds, which build Encode after podlators. Encode is
expected to not (yet) be available in that case.
=item POD_MAN_DATE
If set, this will be used as the value of the left-hand footer unless the
C<date> option is explicitly set, overriding the timestamp of the input
file or the current time. This is primarily useful to ensure reproducible
builds of the same output file given the same source and Pod::Man version,
even when file timestamps may not be consistent.
=item SOURCE_DATE_EPOCH
If set, and POD_MAN_DATE and the C<date> options are not set, this will be
used as the modification time of the source file, overriding the timestamp of
the input file or the current time. It should be set to the desired time in
seconds since UNIX epoch. This is primarily useful to ensure reproducible
builds of the same output file given the same source and Pod::Man version,
even when file timestamps may not be consistent. See
L<https://reproducible-builds.org/specs/source-date-epoch/> for the full
specification.
(Arguably, according to the specification, this variable should be used only
if the timestamp of the input file is not available and Pod::Man uses the
current time. However, for reproducible builds in Debian, results were more
reliable if this variable overrode the timestamp of the input file.)
=back
=head1 BUGS
Encoding handling assumes that PerlIO is available and does not work
properly if it isn't. The C<utf8> option is therefore not supported
unless Perl is built with PerlIO support.
There is currently no way to turn off the guesswork that tries to format
unmarked text appropriately, and sometimes it isn't wanted (particularly
when using POD to document something other than Perl). Most of the work
toward fixing this has now been done, however, and all that's still needed
is a user interface.
The NAME section should be recognized specially and index entries emitted
for everything in that section. This would have to be deferred until the
next section, since extraneous things in NAME tends to confuse various man
page processors. Currently, no index entries are emitted for anything in
NAME.
Pod::Man doesn't handle font names longer than two characters. Neither do
most B<troff> implementations, but GNU troff does as an extension. It would
be nice to support as an option for those who want to use it.
The preamble added to each output file is rather verbose, and most of it
is only necessary in the presence of non-ASCII characters. It would
ideally be nice if all of those definitions were only output if needed,
perhaps on the fly as the characters are used.
Pod::Man is excessively slow.
=head1 CAVEATS
If Pod::Man is given the C<utf8> option, the encoding of its output file
handle will be forced to UTF-8 if possible, overriding any existing
encoding. This will be done even if the file handle is not created by
Pod::Man and was passed in from outside. This maintains consistency
regardless of PERL_UNICODE and other settings.
The handling of hyphens and em dashes is somewhat fragile, and one may get
the wrong one under some circumstances. This should only matter for
B<troff> output.
When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
necessarily get it right.
Converting neutral double quotes to properly matched double quotes doesn't
work unless there are no formatting codes between the quote marks. This
only matters for troff output.
=head1 AUTHOR
Russ Allbery <rra@cpan.org>, based I<very> heavily on the original
B<pod2man> by Tom Christiansen <tchrist@mox.perl.com>. The modifications to
work with Pod::Simple instead of Pod::Parser were originally contributed by
Sean Burke (but I've since hacked them beyond recognition and all bugs are
mine).
=head1 COPYRIGHT AND LICENSE
Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
2009, 2010, 2012, 2013, 2014, 2015, 2016 Russ Allbery <rra@cpan.org>
This program is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.
=head1 SEE ALSO
L<Pod::Simple>, L<perlpod(1)>, L<pod2man(1)>, L<nroff(1)>, L<troff(1)>,
L<man(1)>, L<man(7)>
Ossanna, Joseph F., and Brian W. Kernighan. "Troff User's Manual,"
Computing Science Technical Report No. 54, AT&T Bell Laboratories. This is
the best documentation of standard B<nroff> and B<troff>. At the time of
this writing, it's available at
L<http://www.cs.bell-labs.com/cm/cs/cstr.html>.
The man page documenting the man macro set may be L<man(5)> instead of
L<man(7)> on your system. Also, please see L<pod2man(1)> for extensive
documentation on writing manual pages if you've not done it before and
aren't familiar with the conventions.
The current version of this module is always available from its web site at
L<http://www.eyrie.org/~eagle/software/podlators/>. It is also part of the
Perl core distribution as of 5.6.0.
=cut
| operepo/ope | bin/usr/share/perl5/core_perl/Pod/Man.pm | Perl | mit | 78,692 |
# This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/ympzZnp0Uq/europe. Olson data version 2012c
#
# Do not edit this file directly.
#
package DateTime::TimeZone::Asia::Krasnoyarsk;
{
$DateTime::TimeZone::Asia::Krasnoyarsk::VERSION = '1.46';
}
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::Asia::Krasnoyarsk::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY,
60558169720,
DateTime::TimeZone::NEG_INFINITY,
60558192000,
22280,
0,
'LMT'
],
[
60558169720,
60888132000,
60558191320,
60888153600,
21600,
0,
'KRAT'
],
[
60888132000,
62490589200,
60888157200,
62490614400,
25200,
0,
'KRAT'
],
[
62490589200,
62506396800,
62490618000,
62506425600,
28800,
1,
'KRAST'
],
[
62506396800,
62522125200,
62506422000,
62522150400,
25200,
0,
'KRAT'
],
[
62522125200,
62537932800,
62522154000,
62537961600,
28800,
1,
'KRAST'
],
[
62537932800,
62553661200,
62537958000,
62553686400,
25200,
0,
'KRAT'
],
[
62553661200,
62569468800,
62553690000,
62569497600,
28800,
1,
'KRAST'
],
[
62569468800,
62585283600,
62569494000,
62585308800,
25200,
0,
'KRAT'
],
[
62585283600,
62601015600,
62585312400,
62601044400,
28800,
1,
'KRAST'
],
[
62601015600,
62616740400,
62601040800,
62616765600,
25200,
0,
'KRAT'
],
[
62616740400,
62632465200,
62616769200,
62632494000,
28800,
1,
'KRAST'
],
[
62632465200,
62648190000,
62632490400,
62648215200,
25200,
0,
'KRAT'
],
[
62648190000,
62663914800,
62648218800,
62663943600,
28800,
1,
'KRAST'
],
[
62663914800,
62679639600,
62663940000,
62679664800,
25200,
0,
'KRAT'
],
[
62679639600,
62695364400,
62679668400,
62695393200,
28800,
1,
'KRAST'
],
[
62695364400,
62711089200,
62695389600,
62711114400,
25200,
0,
'KRAT'
],
[
62711089200,
62726814000,
62711118000,
62726842800,
28800,
1,
'KRAST'
],
[
62726814000,
62742538800,
62726839200,
62742564000,
25200,
0,
'KRAT'
],
[
62742538800,
62758263600,
62742567600,
62758292400,
28800,
1,
'KRAST'
],
[
62758263600,
62773988400,
62758288800,
62774013600,
25200,
0,
'KRAT'
],
[
62773988400,
62790318000,
62774017200,
62790346800,
28800,
1,
'KRAST'
],
[
62790318000,
62806042800,
62790343200,
62806068000,
25200,
0,
'KRAT'
],
[
62806042800,
62821771200,
62806068000,
62821796400,
25200,
1,
'KRAST'
],
[
62821771200,
62831448000,
62821792800,
62831469600,
21600,
0,
'KRAT'
],
[
62831448000,
62837481600,
62831473200,
62837506800,
25200,
0,
'KRAT'
],
[
62837481600,
62853202800,
62837510400,
62853231600,
28800,
1,
'KRAST'
],
[
62853202800,
62868942000,
62853228000,
62868967200,
25200,
0,
'KRAT'
],
[
62868942000,
62884666800,
62868970800,
62884695600,
28800,
1,
'KRAST'
],
[
62884666800,
62900391600,
62884692000,
62900416800,
25200,
0,
'KRAT'
],
[
62900391600,
62916116400,
62900420400,
62916145200,
28800,
1,
'KRAST'
],
[
62916116400,
62931841200,
62916141600,
62931866400,
25200,
0,
'KRAT'
],
[
62931841200,
62947566000,
62931870000,
62947594800,
28800,
1,
'KRAST'
],
[
62947566000,
62963895600,
62947591200,
62963920800,
25200,
0,
'KRAT'
],
[
62963895600,
62982039600,
62963924400,
62982068400,
28800,
1,
'KRAST'
],
[
62982039600,
62995345200,
62982064800,
62995370400,
25200,
0,
'KRAT'
],
[
62995345200,
63013489200,
62995374000,
63013518000,
28800,
1,
'KRAST'
],
[
63013489200,
63026794800,
63013514400,
63026820000,
25200,
0,
'KRAT'
],
[
63026794800,
63044938800,
63026823600,
63044967600,
28800,
1,
'KRAST'
],
[
63044938800,
63058244400,
63044964000,
63058269600,
25200,
0,
'KRAT'
],
[
63058244400,
63076993200,
63058273200,
63077022000,
28800,
1,
'KRAST'
],
[
63076993200,
63089694000,
63077018400,
63089719200,
25200,
0,
'KRAT'
],
[
63089694000,
63108442800,
63089722800,
63108471600,
28800,
1,
'KRAST'
],
[
63108442800,
63121143600,
63108468000,
63121168800,
25200,
0,
'KRAT'
],
[
63121143600,
63139892400,
63121172400,
63139921200,
28800,
1,
'KRAST'
],
[
63139892400,
63153198000,
63139917600,
63153223200,
25200,
0,
'KRAT'
],
[
63153198000,
63171342000,
63153226800,
63171370800,
28800,
1,
'KRAST'
],
[
63171342000,
63184647600,
63171367200,
63184672800,
25200,
0,
'KRAT'
],
[
63184647600,
63202791600,
63184676400,
63202820400,
28800,
1,
'KRAST'
],
[
63202791600,
63216097200,
63202816800,
63216122400,
25200,
0,
'KRAT'
],
[
63216097200,
63234846000,
63216126000,
63234874800,
28800,
1,
'KRAST'
],
[
63234846000,
63247546800,
63234871200,
63247572000,
25200,
0,
'KRAT'
],
[
63247546800,
63266295600,
63247575600,
63266324400,
28800,
1,
'KRAST'
],
[
63266295600,
63278996400,
63266320800,
63279021600,
25200,
0,
'KRAT'
],
[
63278996400,
63297745200,
63279025200,
63297774000,
28800,
1,
'KRAST'
],
[
63297745200,
63310446000,
63297770400,
63310471200,
25200,
0,
'KRAT'
],
[
63310446000,
63329194800,
63310474800,
63329223600,
28800,
1,
'KRAST'
],
[
63329194800,
63342500400,
63329220000,
63342525600,
25200,
0,
'KRAT'
],
[
63342500400,
63360644400,
63342529200,
63360673200,
28800,
1,
'KRAST'
],
[
63360644400,
63373950000,
63360669600,
63373975200,
25200,
0,
'KRAT'
],
[
63373950000,
63392094000,
63373978800,
63392122800,
28800,
1,
'KRAST'
],
[
63392094000,
63405399600,
63392119200,
63405424800,
25200,
0,
'KRAT'
],
[
63405399600,
63424148400,
63405428400,
63424177200,
28800,
1,
'KRAST'
],
[
63424148400,
63436849200,
63424173600,
63436874400,
25200,
0,
'KRAT'
],
[
63436849200,
DateTime::TimeZone::INFINITY,
63436878000,
DateTime::TimeZone::INFINITY,
28800,
0,
'KRAT'
],
];
sub olson_version { '2012c' }
sub has_dst_changes { 30 }
sub _max_year { 2022 }
sub _new_instance
{
return shift->_init( @_, spans => $spans );
}
1;
| leighpauls/k2cro4 | third_party/perl/perl/vendor/lib/DateTime/TimeZone/Asia/Krasnoyarsk.pm | Perl | bsd-3-clause | 6,215 |
#!/usr/bin/perl
#
## Licensed to the Apache Software Foundation (ASF) under one
## or more contributor license agreements. See the NOTICE file
## distributed with this work for additional information
## regarding copyright ownership. The ASF licenses this file
## to you under the Apache License, Version 2.0 (the
## "License"); you may not use this file except in compliance
## with the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
use strict;
use warnings;
{
print "sni:\n";
while (<>) {
chomp;
#print "y $_\n";
if (m|fqdn\s+=\s+'(\S+)',|) {
my $fqdn = $1;
if ($fqdn =~ m|\*|) {
$fqdn = "'" . $fqdn . "'";
}
print "- fqdn: $fqdn\n";
while (<>) {
chomp;
last if (m|},|);
#print "x $_\n";
if (m|(\w+)\s+=\s+'(\S+)',?|) {
my $key = $1;
my $value = $2;
if ($key eq 'verify_server_policy') {
$value = 'PERMISSIVE' if ($value eq 'moderate');
$value = 'DISABLED' if ($value eq 'disabled');
}
print " $key: $value\n"
}
}
}
}
}
| SolidWallOfCode/trafficserver | tools/sni_lua_to_yaml.pl | Perl | apache-2.0 | 1,490 |
#-----------------------------------------------------------
# autoendtasks.pl
#
# History
# 20081128 - created
#
# Ref:
# http://support.microsoft.com/kb/555619
# This Registry setting tells XP (and Vista) to automatically
# end non-responsive tasks; value may not exist on Vista.
#
# copyright 2008 H. Carvey, keydet89@yahoo.com
#-----------------------------------------------------------
package autoendtasks;
use strict;
my %config = (hive => "NTUSER\.DAT",
osmask => 22,
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
version => 20081128);
sub getConfig{return %config}
sub getShortDescr {
return "Automatically end a non-responsive task";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
sub pluginmain {
my $class = shift;
my $hive = shift;
::logMsg("Launching autoendtasks v.".$VERSION);
::rptMsg("autoendtasks v.".$VERSION); # banner
::rptMsg("(".$config{hive}.") ".getShortDescr()."\n"); # banner
my $reg = Parse::Win32Registry->new($hive);
my $root_key = $reg->get_root_key;
my $key_path = 'Control Panel\\Desktop';
my $key;
if ($key = $root_key->get_subkey($key_path)) {
# ::rptMsg("autoendtasks");
::rptMsg($key_path);
# ::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
::rptMsg("");
my $autoend;
eval {
$autoend = $key->get_value("AutoEndTasks")->get_data();
};
if ($@) {
::rptMsg("AutoEndTasks value not found.");
}
else {
::rptMsg("AutoEndTasks = ".$autoend);
}
}
else {
::rptMsg($key_path." not found.");
::logMsg($key_path." not found.");
}
}
1; | APriestman/autopsy | thirdparty/rr-full/plugins/autoendtasks.pl | Perl | apache-2.0 | 1,744 |
# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
# vim: ts=4 sts=4 sw=4:
package CPAN::Distribution;
use strict;
use Cwd qw(chdir);
use CPAN::Distroprefs;
use CPAN::InfoObj;
use File::Path ();
@CPAN::Distribution::ISA = qw(CPAN::InfoObj);
use vars qw($VERSION);
$VERSION = "1.9602";
# Accessors
sub cpan_comment {
my $self = shift;
my $ro = $self->ro or return;
$ro->{CPAN_COMMENT}
}
#-> CPAN::Distribution::undelay
sub undelay {
my $self = shift;
for my $delayer (
"configure_requires_later",
"configure_requires_later_for",
"later",
"later_for",
) {
delete $self->{$delayer};
}
}
#-> CPAN::Distribution::is_dot_dist
sub is_dot_dist {
my($self) = @_;
return substr($self->id,-1,1) eq ".";
}
# add the A/AN/ stuff
#-> CPAN::Distribution::normalize
sub normalize {
my($self,$s) = @_;
$s = $self->id unless defined $s;
if (substr($s,-1,1) eq ".") {
# using a global because we are sometimes called as static method
if (!$CPAN::META->{LOCK}
&& !$CPAN::Have_warned->{"$s is unlocked"}++
) {
$CPAN::Frontend->mywarn("You are visiting the local directory
'$s'
without lock, take care that concurrent processes do not do likewise.\n");
$CPAN::Frontend->mysleep(1);
}
if ($s eq ".") {
$s = "$CPAN::iCwd/.";
} elsif (File::Spec->file_name_is_absolute($s)) {
} elsif (File::Spec->can("rel2abs")) {
$s = File::Spec->rel2abs($s);
} else {
$CPAN::Frontend->mydie("Your File::Spec is too old, please upgrade File::Spec");
}
CPAN->debug("s[$s]") if $CPAN::DEBUG;
unless ($CPAN::META->exists("CPAN::Distribution", $s)) {
for ($CPAN::META->instance("CPAN::Distribution", $s)) {
$_->{build_dir} = $s;
$_->{archived} = "local_directory";
$_->{unwrapped} = CPAN::Distrostatus->new("YES -- local_directory");
}
}
} elsif (
$s =~ tr|/|| == 1
or
$s !~ m|[A-Z]/[A-Z-]{2}/[A-Z-]{2,}/|
) {
return $s if $s =~ m:^N/A|^Contact Author: ;
$s =~ s|^(.)(.)([^/]*/)(.+)$|$1/$1$2/$1$2$3$4|;
CPAN->debug("s[$s]") if $CPAN::DEBUG;
}
$s;
}
#-> sub CPAN::Distribution::author ;
sub author {
my($self) = @_;
my($authorid);
if (substr($self->id,-1,1) eq ".") {
$authorid = "LOCAL";
} else {
($authorid) = $self->pretty_id =~ /^([\w\-]+)/;
}
CPAN::Shell->expand("Author",$authorid);
}
# tries to get the yaml from CPAN instead of the distro itself:
# EXPERIMENTAL, UNDOCUMENTED AND UNTESTED, for Tels
sub fast_yaml {
my($self) = @_;
my $meta = $self->pretty_id;
$meta =~ s/\.(tar.gz|tgz|zip|tar.bz2)/.meta/;
my(@ls) = CPAN::Shell->globls($meta);
my $norm = $self->normalize($meta);
my($local_file);
my($local_wanted) =
File::Spec->catfile(
$CPAN::Config->{keep_source_where},
"authors",
"id",
split(/\//,$norm)
);
$self->debug("Doing localize") if $CPAN::DEBUG;
unless ($local_file =
CPAN::FTP->localize("authors/id/$norm",
$local_wanted)) {
$CPAN::Frontend->mydie("Giving up on downloading yaml file '$local_wanted'\n");
}
my $yaml = CPAN->_yaml_loadfile($local_file)->[0];
}
#-> sub CPAN::Distribution::cpan_userid
sub cpan_userid {
my $self = shift;
if ($self->{ID} =~ m{[A-Z]/[A-Z\-]{2}/([A-Z\-]+)/}) {
return $1;
}
return $self->SUPER::cpan_userid;
}
#-> sub CPAN::Distribution::pretty_id
sub pretty_id {
my $self = shift;
my $id = $self->id;
return $id unless $id =~ m|^./../|;
substr($id,5);
}
#-> sub CPAN::Distribution::base_id
sub base_id {
my $self = shift;
my $id = $self->pretty_id();
my $base_id = File::Basename::basename($id);
$base_id =~ s{\.(?:tar\.(bz2|gz|Z)|t(?:gz|bz)|zip)$}{}i;
return $base_id;
}
#-> sub CPAN::Distribution::tested_ok_but_not_installed
sub tested_ok_but_not_installed {
my $self = shift;
return (
$self->{make_test}
&& $self->{build_dir}
&& (UNIVERSAL::can($self->{make_test},"failed") ?
! $self->{make_test}->failed :
$self->{make_test} =~ /^YES/
)
&& (
!$self->{install}
||
$self->{install}->failed
)
);
}
# mark as dirty/clean for the sake of recursion detection. $color=1
# means "in use", $color=0 means "not in use anymore". $color=2 means
# we have determined prereqs now and thus insist on passing this
# through (at least) once again.
#-> sub CPAN::Distribution::color_cmd_tmps ;
sub color_cmd_tmps {
my($self) = shift;
my($depth) = shift || 0;
my($color) = shift || 0;
my($ancestors) = shift || [];
# a distribution needs to recurse into its prereq_pms
$self->debug("color_cmd_tmps[$depth,$color,@$ancestors]") if $CPAN::DEBUG;
return if exists $self->{incommandcolor}
&& $color==1
&& $self->{incommandcolor}==$color;
if ($depth>=$CPAN::MAX_RECURSION) {
die(CPAN::Exception::RecursiveDependency->new($ancestors));
}
# warn "color_cmd_tmps $depth $color " . $self->id; # sleep 1;
my $prereq_pm = $self->prereq_pm;
if (defined $prereq_pm) {
PREREQ: for my $pre (keys %{$prereq_pm->{requires}||{}},
keys %{$prereq_pm->{build_requires}||{}}) {
next PREREQ if $pre eq "perl";
my $premo;
unless ($premo = CPAN::Shell->expand("Module",$pre)) {
$CPAN::Frontend->mywarn("prerequisite module[$pre] not known\n");
$CPAN::Frontend->mysleep(0.2);
next PREREQ;
}
$premo->color_cmd_tmps($depth+1,$color,[@$ancestors, $self->id]);
}
}
if ($color==0) {
delete $self->{sponsored_mods};
# as we are at the end of a command, we'll give up this
# reminder of a broken test. Other commands may test this guy
# again. Maybe 'badtestcnt' should be renamed to
# 'make_test_failed_within_command'?
delete $self->{badtestcnt};
}
$self->{incommandcolor} = $color;
}
#-> sub CPAN::Distribution::as_string ;
sub as_string {
my $self = shift;
$self->containsmods;
$self->upload_date;
$self->SUPER::as_string(@_);
}
#-> sub CPAN::Distribution::containsmods ;
sub containsmods {
my $self = shift;
return keys %{$self->{CONTAINSMODS}} if exists $self->{CONTAINSMODS};
my $dist_id = $self->{ID};
for my $mod ($CPAN::META->all_objects("CPAN::Module")) {
my $mod_file = $mod->cpan_file or next;
my $mod_id = $mod->{ID} or next;
# warn "mod_file[$mod_file] dist_id[$dist_id] mod_id[$mod_id]";
# sleep 1;
if ($CPAN::Signal) {
delete $self->{CONTAINSMODS};
return;
}
$self->{CONTAINSMODS}{$mod_id} = undef if $mod_file eq $dist_id;
}
keys %{$self->{CONTAINSMODS}||={}};
}
#-> sub CPAN::Distribution::upload_date ;
sub upload_date {
my $self = shift;
return $self->{UPLOAD_DATE} if exists $self->{UPLOAD_DATE};
my(@local_wanted) = split(/\//,$self->id);
my $filename = pop @local_wanted;
push @local_wanted, "CHECKSUMS";
my $author = CPAN::Shell->expand("Author",$self->cpan_userid);
return unless $author;
my @dl = $author->dir_listing(\@local_wanted,0,$CPAN::Config->{show_upload_date});
return unless @dl;
my($dirent) = grep { $_->[2] eq $filename } @dl;
# warn sprintf "dirent[%s]id[%s]", $dirent, $self->id;
return unless $dirent->[1];
return $self->{UPLOAD_DATE} = $dirent->[1];
}
#-> sub CPAN::Distribution::uptodate ;
sub uptodate {
my($self) = @_;
my $c;
foreach $c ($self->containsmods) {
my $obj = CPAN::Shell->expandany($c);
unless ($obj->uptodate) {
my $id = $self->pretty_id;
$self->debug("$id not uptodate due to $c") if $CPAN::DEBUG;
return 0;
}
}
return 1;
}
#-> sub CPAN::Distribution::called_for ;
sub called_for {
my($self,$id) = @_;
$self->{CALLED_FOR} = $id if defined $id;
return $self->{CALLED_FOR};
}
#-> sub CPAN::Distribution::get ;
sub get {
my($self) = @_;
$self->debug("checking goto id[$self->{ID}]") if $CPAN::DEBUG;
if (my $goto = $self->prefs->{goto}) {
$CPAN::Frontend->mywarn
(sprintf(
"delegating to '%s' as specified in prefs file '%s' doc %d\n",
$goto,
$self->{prefs_file},
$self->{prefs_file_doc},
));
return $self->goto($goto);
}
local $ENV{PERL5LIB} = defined($ENV{PERL5LIB})
? $ENV{PERL5LIB}
: ($ENV{PERLLIB} || "");
local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : "";
$CPAN::META->set_perl5lib;
local $ENV{MAKEFLAGS}; # protect us from outer make calls
EXCUSE: {
my @e;
my $goodbye_message;
$self->debug("checking disabled id[$self->{ID}]") if $CPAN::DEBUG;
if ($self->prefs->{disabled} && ! $self->{force_update}) {
my $why = sprintf(
"Disabled via prefs file '%s' doc %d",
$self->{prefs_file},
$self->{prefs_file_doc},
);
push @e, $why;
$self->{unwrapped} = CPAN::Distrostatus->new("NO $why");
$goodbye_message = "[disabled] -- NA $why";
# note: not intended to be persistent but at least visible
# during this session
} else {
if (exists $self->{build_dir} && -d $self->{build_dir}
&& ($self->{modulebuild}||$self->{writemakefile})
) {
# this deserves print, not warn:
$CPAN::Frontend->myprint(" Has already been unwrapped into directory ".
"$self->{build_dir}\n"
);
return 1;
}
# although we talk about 'force' we shall not test on
# force directly. New model of force tries to refrain from
# direct checking of force.
exists $self->{unwrapped} and (
UNIVERSAL::can($self->{unwrapped},"failed") ?
$self->{unwrapped}->failed :
$self->{unwrapped} =~ /^NO/
)
and push @e, "Unwrapping had some problem, won't try again without force";
}
if (@e) {
$CPAN::Frontend->mywarn(join "", map {"$_\n"} @e);
if ($goodbye_message) {
$self->goodbye($goodbye_message);
}
return;
}
}
my $sub_wd = CPAN::anycwd(); # for cleaning up as good as possible
my($local_file);
unless ($self->{build_dir} && -d $self->{build_dir}) {
$self->get_file_onto_local_disk;
return if $CPAN::Signal;
$self->check_integrity;
return if $CPAN::Signal;
(my $packagedir,$local_file) = $self->run_preps_on_packagedir;
if (exists $self->{writemakefile} && ref $self->{writemakefile}
&& $self->{writemakefile}->can("failed") &&
$self->{writemakefile}->failed) {
return;
}
$packagedir ||= $self->{build_dir};
$self->{build_dir} = $packagedir;
}
if ($CPAN::Signal) {
$self->safe_chdir($sub_wd);
return;
}
return $self->choose_MM_or_MB($local_file);
}
#-> CPAN::Distribution::get_file_onto_local_disk
sub get_file_onto_local_disk {
my($self) = @_;
return if $self->is_dot_dist;
my($local_file);
my($local_wanted) =
File::Spec->catfile(
$CPAN::Config->{keep_source_where},
"authors",
"id",
split(/\//,$self->id)
);
$self->debug("Doing localize") if $CPAN::DEBUG;
unless ($local_file =
CPAN::FTP->localize("authors/id/$self->{ID}",
$local_wanted)) {
my $note = "";
if ($CPAN::Index::DATE_OF_02) {
$note = "Note: Current database in memory was generated ".
"on $CPAN::Index::DATE_OF_02\n";
}
$CPAN::Frontend->mydie("Giving up on '$local_wanted'\n$note");
}
$self->debug("local_wanted[$local_wanted]local_file[$local_file]") if $CPAN::DEBUG;
$self->{localfile} = $local_file;
}
#-> CPAN::Distribution::check_integrity
sub check_integrity {
my($self) = @_;
return if $self->is_dot_dist;
if ($CPAN::META->has_inst("Digest::SHA")) {
$self->debug("Digest::SHA is installed, verifying");
$self->verifyCHECKSUM;
} else {
$self->debug("Digest::SHA is NOT installed");
}
}
#-> CPAN::Distribution::run_preps_on_packagedir
sub run_preps_on_packagedir {
my($self) = @_;
return if $self->is_dot_dist;
$CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new(); # unsafe meta access, ok
my $builddir = $CPAN::META->{cachemgr}->dir; # unsafe meta access, ok
$self->safe_chdir($builddir);
$self->debug("Removing tmp-$$") if $CPAN::DEBUG;
File::Path::rmtree("tmp-$$");
unless (mkdir "tmp-$$", 0755) {
$CPAN::Frontend->unrecoverable_error(<<EOF);
Couldn't mkdir '$builddir/tmp-$$': $!
Cannot continue: Please find the reason why I cannot make the
directory
$builddir/tmp-$$
and fix the problem, then retry.
EOF
}
if ($CPAN::Signal) {
return;
}
$self->safe_chdir("tmp-$$");
#
# Unpack the goods
#
my $local_file = $self->{localfile};
my $ct = eval{CPAN::Tarzip->new($local_file)};
unless ($ct) {
$self->{unwrapped} = CPAN::Distrostatus->new("NO");
delete $self->{build_dir};
return;
}
if ($local_file =~ /(\.tar\.(bz2|gz|Z)|\.tgz)(?!\n)\Z/i) {
$self->{was_uncompressed}++ unless eval{$ct->gtest()};
$self->untar_me($ct);
} elsif ( $local_file =~ /\.zip(?!\n)\Z/i ) {
$self->unzip_me($ct);
} else {
$self->{was_uncompressed}++ unless $ct->gtest();
$local_file = $self->handle_singlefile($local_file);
}
# we are still in the tmp directory!
# Let's check if the package has its own directory.
my $dh = DirHandle->new(File::Spec->curdir)
or Carp::croak("Couldn't opendir .: $!");
my @readdir = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh->read; ### MAC??
if (grep { $_ eq "pax_global_header" } @readdir) {
$CPAN::Frontend->mywarn("Your (un)tar seems to have extracted a file named 'pax_global_header'
from the tarball '$local_file'.
This is almost certainly an error. Please upgrade your tar.
I'll ignore this file for now.
See also http://rt.cpan.org/Ticket/Display.html?id=38932\n");
$CPAN::Frontend->mysleep(5);
@readdir = grep { $_ ne "pax_global_header" } @readdir;
}
$dh->close;
my ($packagedir);
# XXX here we want in each branch File::Temp to protect all build_dir directories
if (CPAN->has_usable("File::Temp")) {
my $tdir_base;
my $from_dir;
my @dirents;
if (@readdir == 1 && -d $readdir[0]) {
$tdir_base = $readdir[0];
$from_dir = File::Spec->catdir(File::Spec->curdir,$readdir[0]);
my $dh2;
unless ($dh2 = DirHandle->new($from_dir)) {
my($mode) = (stat $from_dir)[2];
my $why = sprintf
(
"Couldn't opendir '%s', mode '%o': %s",
$from_dir,
$mode,
$!,
);
$CPAN::Frontend->mywarn("$why\n");
$self->{writemakefile} = CPAN::Distrostatus->new("NO -- $why");
return;
}
@dirents = grep $_ !~ /^\.\.?(?!\n)\Z/s, $dh2->read; ### MAC??
} else {
my $userid = $self->cpan_userid;
CPAN->debug("userid[$userid]");
if (!$userid or $userid eq "N/A") {
$userid = "anon";
}
$tdir_base = $userid;
$from_dir = File::Spec->curdir;
@dirents = @readdir;
}
eval { File::Path::mkpath $builddir; };
if ($@) {
$CPAN::Frontend->mydie("Cannot create directory $builddir: $@");
}
$packagedir = File::Temp::tempdir(
"$tdir_base-XXXXXX",
DIR => $builddir,
CLEANUP => 0,
);
chmod 0777 &~ umask, $packagedir; # may fail
my $f;
for $f (@dirents) { # is already without "." and ".."
my $from = File::Spec->catdir($from_dir,$f);
my $to = File::Spec->catdir($packagedir,$f);
unless (File::Copy::move($from,$to)) {
my $err = $!;
$from = File::Spec->rel2abs($from);
Carp::confess("Couldn't move $from to $to: $err");
}
}
} else { # older code below, still better than nothing when there is no File::Temp
my($distdir);
if (@readdir == 1 && -d $readdir[0]) {
$distdir = $readdir[0];
$packagedir = File::Spec->catdir($builddir,$distdir);
$self->debug("packagedir[$packagedir]builddir[$builddir]distdir[$distdir]")
if $CPAN::DEBUG;
-d $packagedir and $CPAN::Frontend->myprint("Removing previously used ".
"$packagedir\n");
File::Path::rmtree($packagedir);
unless (File::Copy::move($distdir,$packagedir)) {
$CPAN::Frontend->unrecoverable_error(<<EOF);
Couldn't move '$distdir' to '$packagedir': $!
Cannot continue: Please find the reason why I cannot move
$builddir/tmp-$$/$distdir
to
$packagedir
and fix the problem, then retry
EOF
}
$self->debug(sprintf("moved distdir[%s] to packagedir[%s] -e[%s]-d[%s]",
$distdir,
$packagedir,
-e $packagedir,
-d $packagedir,
)) if $CPAN::DEBUG;
} else {
my $userid = $self->cpan_userid;
CPAN->debug("userid[$userid]") if $CPAN::DEBUG;
if (!$userid or $userid eq "N/A") {
$userid = "anon";
}
my $pragmatic_dir = $userid . '000';
$pragmatic_dir =~ s/\W_//g;
$pragmatic_dir++ while -d "../$pragmatic_dir";
$packagedir = File::Spec->catdir($builddir,$pragmatic_dir);
$self->debug("packagedir[$packagedir]") if $CPAN::DEBUG;
File::Path::mkpath($packagedir);
my($f);
for $f (@readdir) { # is already without "." and ".."
my $to = File::Spec->catdir($packagedir,$f);
File::Copy::move($f,$to) or Carp::confess("Couldn't move $f to $to: $!");
}
}
}
$self->{build_dir} = $packagedir;
$self->safe_chdir($builddir);
File::Path::rmtree("tmp-$$");
$self->safe_chdir($packagedir);
$self->_signature_business();
$self->safe_chdir($builddir);
return($packagedir,$local_file);
}
#-> sub CPAN::Distribution::pick_meta_file ;
sub pick_meta_file {
my($self, $filter) = @_;
$filter = '.' unless defined $filter;
my $build_dir;
unless ($build_dir = $self->{build_dir}) {
# maybe permission on build_dir was missing
$CPAN::Frontend->mywarn("Warning: cannot determine META.yml without a build_dir.\n");
return;
}
my $has_cm = $CPAN::META->has_usable("CPAN::Meta");
my $has_pcm = $CPAN::META->has_usable("Parse::CPAN::Meta");
my @choices;
push @choices, 'MYMETA.json' if $has_cm;
push @choices, 'MYMETA.yml' if $has_cm || $has_pcm;
push @choices, 'META.json' if $has_cm;
push @choices, 'META.yml' if $has_cm || $has_pcm;
for my $file ( grep { /$filter/ } @choices ) {
my $path = File::Spec->catdir( $build_dir, $file );
return $path if -f $path
}
return;
}
#-> sub CPAN::Distribution::parse_meta_yml ;
sub parse_meta_yml {
my($self, $yaml) = @_;
$self->debug(sprintf("parse_meta_yml[%s]",$yaml||'undef')) if $CPAN::DEBUG;
my $build_dir = $self->{build_dir} or die "PANIC: cannot parse yaml without a build_dir";
$yaml ||= File::Spec->catfile($build_dir,"META.yml");
$self->debug("meta[$yaml]") if $CPAN::DEBUG;
return unless -f $yaml;
my $early_yaml;
eval {
$CPAN::META->has_inst("Parse::CPAN::Meta") or die;
die "Parse::CPAN::Meta yaml too old" unless $Parse::CPAN::Meta::VERSION >= "1.40";
# P::C::M returns last document in scalar context
$early_yaml = Parse::CPAN::Meta::LoadFile($yaml);
};
unless ($early_yaml) {
eval { $early_yaml = CPAN->_yaml_loadfile($yaml)->[0]; };
}
$self->debug(sprintf("yaml[%s]", $early_yaml || 'UNDEF')) if $CPAN::DEBUG;
$self->debug($early_yaml) if $CPAN::DEBUG && $early_yaml;
return $early_yaml || undef;
}
#-> sub CPAN::Distribution::satisfy_requires ;
sub satisfy_requires {
my ($self) = @_;
$self->debug("Entering satisfy_requires") if $CPAN::DEBUG;
if (my @prereq = $self->unsat_prereq("later")) {
$self->debug("unsatisfied[@prereq]") if $CPAN::DEBUG;
$self->debug(@prereq) if $CPAN::DEBUG && @prereq;
if ($prereq[0][0] eq "perl") {
my $need = "requires perl '$prereq[0][1]'";
my $id = $self->pretty_id;
$CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n");
$self->{make} = CPAN::Distrostatus->new("NO $need");
$self->store_persistent_state;
die "[prereq] -- NOT OK\n";
} else {
my $follow = eval { $self->follow_prereqs("later",@prereq); };
if (0) {
} elsif ($follow) {
# signal success to the queuerunner
return 1;
} elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) {
$CPAN::Frontend->mywarn($@);
die "[depend] -- NOT OK\n";
}
}
}
return;
}
#-> sub CPAN::Distribution::satisfy_configure_requires ;
sub satisfy_configure_requires {
my($self) = @_;
$self->debug("Entering satisfy_configure_requires") if $CPAN::DEBUG;
my $enable_configure_requires = 1;
if (!$enable_configure_requires) {
return 1;
# if we return 1 here, everything is as before we introduced
# configure_requires that means, things with
# configure_requires simply fail, all others succeed
}
my @prereq = $self->unsat_prereq("configure_requires_later");
$self->debug(sprintf "configure_requires[%s]", join(",",map {join "/",@$_} @prereq)) if $CPAN::DEBUG;
return 1 unless @prereq;
$self->debug(\@prereq) if $CPAN::DEBUG;
if ($self->{configure_requires_later}) {
for my $k (keys %{$self->{configure_requires_later_for}||{}}) {
if ($self->{configure_requires_later_for}{$k}>1) {
my $type = "";
for my $p (@prereq) {
if ($p->[0] eq $k) {
$type = $p->[1];
}
}
$type = " $type" if $type;
$CPAN::Frontend->mywarn("Warning: unmanageable(?) prerequisite $k$type");
sleep 1;
}
}
}
if ($prereq[0][0] eq "perl") {
my $need = "requires perl '$prereq[0][1]'";
my $id = $self->pretty_id;
$CPAN::Frontend->mywarn("$id $need; you have only $]; giving up\n");
$self->{make} = CPAN::Distrostatus->new("NO $need");
$self->store_persistent_state;
return $self->goodbye("[prereq] -- NOT OK");
} else {
my $follow = eval {
$self->follow_prereqs("configure_requires_later", @prereq);
};
if (0) {
} elsif ($follow) {
return;
} elsif ($@ && ref $@ && $@->isa("CPAN::Exception::RecursiveDependency")) {
$CPAN::Frontend->mywarn($@);
return $self->goodbye("[depend] -- NOT OK");
}
else {
return $self->goodbye("[configure_requires] -- NOT OK");
}
}
die "never reached";
}
#-> sub CPAN::Distribution::choose_MM_or_MB ;
sub choose_MM_or_MB {
my($self,$local_file) = @_;
$self->satisfy_configure_requires() or return;
my($mpl) = File::Spec->catfile($self->{build_dir},"Makefile.PL");
my($mpl_exists) = -f $mpl;
unless ($mpl_exists) {
# NFS has been reported to have racing problems after the
# renaming of a directory in some environments.
# This trick helps.
$CPAN::Frontend->mysleep(1);
my $mpldh = DirHandle->new($self->{build_dir})
or Carp::croak("Couldn't opendir $self->{build_dir}: $!");
$mpl_exists = grep /^Makefile\.PL$/, $mpldh->read;
$mpldh->close;
}
my $prefer_installer = "eumm"; # eumm|mb
if (-f File::Spec->catfile($self->{build_dir},"Build.PL")) {
if ($mpl_exists) { # they *can* choose
if ($CPAN::META->has_inst("Module::Build")) {
$prefer_installer = CPAN::HandleConfig->prefs_lookup(
$self, q{prefer_installer}
);
# M::B <= 0.35 left a DATA handle open that
# causes problems upgrading M::B on Windows
close *Module::Build::Version::DATA
if fileno *Module::Build::Version::DATA;
}
} else {
$prefer_installer = "mb";
}
}
return unless $self->patch;
if (lc($prefer_installer) eq "rand") {
$prefer_installer = rand()<.5 ? "eumm" : "mb";
}
if (lc($prefer_installer) eq "mb") {
$self->{modulebuild} = 1;
} elsif ($self->{archived} eq "patch") {
# not an edge case, nothing to install for sure
my $why = "A patch file cannot be installed";
$CPAN::Frontend->mywarn("Refusing to handle this file: $why\n");
$self->{writemakefile} = CPAN::Distrostatus->new("NO $why");
} elsif (! $mpl_exists) {
$self->_edge_cases($mpl,$local_file);
}
if ($self->{build_dir}
&&
$CPAN::Config->{build_dir_reuse}
) {
$self->store_persistent_state;
}
return $self;
}
#-> CPAN::Distribution::store_persistent_state
sub store_persistent_state {
my($self) = @_;
my $dir = $self->{build_dir};
unless (defined $dir && length $dir) {
my $id = $self->id;
$CPAN::Frontend->mywarnonce("build_dir of $id is not known, ".
"will not store persistent state\n");
return;
}
unless (File::Spec->canonpath(File::Basename::dirname($dir))
eq File::Spec->canonpath($CPAN::Config->{build_dir})) {
$CPAN::Frontend->mywarnonce("Directory '$dir' not below $CPAN::Config->{build_dir}, ".
"will not store persistent state\n");
return;
}
my $file = sprintf "%s.yml", $dir;
my $yaml_module = CPAN::_yaml_module();
if ($CPAN::META->has_inst($yaml_module)) {
CPAN->_yaml_dumpfile(
$file,
{
time => time,
perl => CPAN::_perl_fingerprint(),
distribution => $self,
}
);
} else {
$CPAN::Frontend->myprintonce("'$yaml_module' not installed, ".
"will not store persistent state\n");
}
}
#-> CPAN::Distribution::try_download
sub try_download {
my($self,$patch) = @_;
my $norm = $self->normalize($patch);
my($local_wanted) =
File::Spec->catfile(
$CPAN::Config->{keep_source_where},
"authors",
"id",
split(/\//,$norm),
);
$self->debug("Doing localize") if $CPAN::DEBUG;
return CPAN::FTP->localize("authors/id/$norm",
$local_wanted);
}
{
my $stdpatchargs = "";
#-> CPAN::Distribution::patch
sub patch {
my($self) = @_;
$self->debug("checking patches id[$self->{ID}]") if $CPAN::DEBUG;
my $patches = $self->prefs->{patches};
$patches ||= "";
$self->debug("patches[$patches]") if $CPAN::DEBUG;
if ($patches) {
return unless @$patches;
$self->safe_chdir($self->{build_dir});
CPAN->debug("patches[$patches]") if $CPAN::DEBUG;
my $patchbin = $CPAN::Config->{patch};
unless ($patchbin && length $patchbin) {
$CPAN::Frontend->mydie("No external patch command configured\n\n".
"Please run 'o conf init /patch/'\n\n");
}
unless (MM->maybe_command($patchbin)) {
$CPAN::Frontend->mydie("No external patch command available\n\n".
"Please run 'o conf init /patch/'\n\n");
}
$patchbin = CPAN::HandleConfig->safe_quote($patchbin);
local $ENV{PATCH_GET} = 0; # formerly known as -g0
unless ($stdpatchargs) {
my $system = "$patchbin --version |";
local *FH;
open FH, $system or die "Could not fork '$system': $!";
local $/ = "\n";
my $pversion;
PARSEVERSION: while (<FH>) {
if (/^patch\s+([\d\.]+)/) {
$pversion = $1;
last PARSEVERSION;
}
}
if ($pversion) {
$stdpatchargs = "-N --fuzz=3";
} else {
$stdpatchargs = "-N";
}
}
my $countedpatches = @$patches == 1 ? "1 patch" : (scalar @$patches . " patches");
$CPAN::Frontend->myprint("Applying $countedpatches:\n");
my $patches_dir = $CPAN::Config->{patches_dir};
for my $patch (@$patches) {
if ($patches_dir && !File::Spec->file_name_is_absolute($patch)) {
my $f = File::Spec->catfile($patches_dir, $patch);
$patch = $f if -f $f;
}
unless (-f $patch) {
CPAN->debug("not on disk: patch[$patch]") if $CPAN::DEBUG;
if (my $trydl = $self->try_download($patch)) {
$patch = $trydl;
} else {
my $fail = "Could not find patch '$patch'";
$CPAN::Frontend->mywarn("$fail; cannot continue\n");
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail");
delete $self->{build_dir};
return;
}
}
$CPAN::Frontend->myprint(" $patch\n");
my $readfh = CPAN::Tarzip->TIEHANDLE($patch);
my $pcommand;
my($ppp,$pfiles) = $self->_patch_p_parameter($readfh);
if ($ppp eq "applypatch") {
$pcommand = "$CPAN::Config->{applypatch} -verbose";
} else {
my $thispatchargs = join " ", $stdpatchargs, $ppp;
$pcommand = "$patchbin $thispatchargs";
require Config; # usually loaded from CPAN.pm
if ($Config::Config{osname} eq "solaris") {
# native solaris patch cannot patch readonly files
for my $file (@{$pfiles||[]}) {
my @stat = stat $file or next;
chmod $stat[2] | 0600, $file; # may fail
}
}
}
$readfh = CPAN::Tarzip->TIEHANDLE($patch); # open again
my $writefh = FileHandle->new;
$CPAN::Frontend->myprint(" $pcommand\n");
unless (open $writefh, "|$pcommand") {
my $fail = "Could not fork '$pcommand'";
$CPAN::Frontend->mywarn("$fail; cannot continue\n");
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail");
delete $self->{build_dir};
return;
}
binmode($writefh);
while (my $x = $readfh->READLINE) {
print $writefh $x;
}
unless (close $writefh) {
my $fail = "Could not apply patch '$patch'";
$CPAN::Frontend->mywarn("$fail; cannot continue\n");
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- $fail");
delete $self->{build_dir};
return;
}
}
$self->{patched}++;
}
return 1;
}
}
# may return
# - "applypatch"
# - ("-p0"|"-p1", $files)
sub _patch_p_parameter {
my($self,$fh) = @_;
my $cnt_files = 0;
my $cnt_p0files = 0;
my @files;
local($_);
while ($_ = $fh->READLINE) {
if (
$CPAN::Config->{applypatch}
&&
/\#\#\#\# ApplyPatch data follows \#\#\#\#/
) {
return "applypatch"
}
next unless /^[\*\+]{3}\s(\S+)/;
my $file = $1;
push @files, $file;
$cnt_files++;
$cnt_p0files++ if -f $file;
CPAN->debug("file[$file]cnt_files[$cnt_files]cnt_p0files[$cnt_p0files]")
if $CPAN::DEBUG;
}
return "-p1" unless $cnt_files;
my $opt_p = $cnt_files==$cnt_p0files ? "-p0" : "-p1";
return ($opt_p, \@files);
}
#-> sub CPAN::Distribution::_edge_cases
# with "configure" or "Makefile" or single file scripts
sub _edge_cases {
my($self,$mpl,$local_file) = @_;
$self->debug(sprintf("makefilepl[%s]anycwd[%s]",
$mpl,
CPAN::anycwd(),
)) if $CPAN::DEBUG;
my $build_dir = $self->{build_dir};
my($configure) = File::Spec->catfile($build_dir,"Configure");
if (-f $configure) {
# do we have anything to do?
$self->{configure} = $configure;
} elsif (-f File::Spec->catfile($build_dir,"Makefile")) {
$CPAN::Frontend->mywarn(qq{
Package comes with a Makefile and without a Makefile.PL.
We\'ll try to build it with that Makefile then.
});
$self->{writemakefile} = CPAN::Distrostatus->new("YES");
$CPAN::Frontend->mysleep(2);
} else {
my $cf = $self->called_for || "unknown";
if ($cf =~ m|/|) {
$cf =~ s|.*/||;
$cf =~ s|\W.*||;
}
$cf =~ s|[/\\:]||g; # risk of filesystem damage
$cf = "unknown" unless length($cf);
if (my $crud = $self->_contains_crud($build_dir)) {
my $why = qq{Package contains $crud; not recognized as a perl package, giving up};
$CPAN::Frontend->mywarn("$why\n");
$self->{writemakefile} = CPAN::Distrostatus->new(qq{NO -- $why});
return;
}
$CPAN::Frontend->mywarn(qq{Package seems to come without Makefile.PL.
(The test -f "$mpl" returned false.)
Writing one on our own (setting NAME to $cf)\a\n});
$self->{had_no_makefile_pl}++;
$CPAN::Frontend->mysleep(3);
# Writing our own Makefile.PL
my $exefile_stanza = "";
if ($self->{archived} eq "maybe_pl") {
$exefile_stanza = $self->_exefile_stanza($build_dir,$local_file);
}
my $fh = FileHandle->new;
$fh->open(">$mpl")
or Carp::croak("Could not open >$mpl: $!");
$fh->print(
qq{# This Makefile.PL has been autogenerated by the module CPAN.pm
# because there was no Makefile.PL supplied.
# Autogenerated on: }.scalar localtime().qq{
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => q[$cf],$exefile_stanza
);
});
$fh->close;
}
}
#-> CPAN;:Distribution::_contains_crud
sub _contains_crud {
my($self,$dir) = @_;
my(@dirs, $dh, @files);
opendir $dh, $dir or return;
my $dirent;
for $dirent (readdir $dh) {
next if $dirent =~ /^\.\.?$/;
my $path = File::Spec->catdir($dir,$dirent);
if (-d $path) {
push @dirs, $dirent;
} elsif (-f $path) {
push @files, $dirent;
}
}
if (@dirs && @files) {
return "both files[@files] and directories[@dirs]";
} elsif (@files > 2) {
return "several files[@files] but no Makefile.PL or Build.PL";
}
return;
}
#-> CPAN;:Distribution::_exefile_stanza
sub _exefile_stanza {
my($self,$build_dir,$local_file) = @_;
my $fh = FileHandle->new;
my $script_file = File::Spec->catfile($build_dir,$local_file);
$fh->open($script_file)
or Carp::croak("Could not open script '$script_file': $!");
local $/ = "\n";
# name parsen und prereq
my($state) = "poddir";
my($name, $prereq) = ("", "");
while (<$fh>) {
if ($state eq "poddir" && /^=head\d\s+(\S+)/) {
if ($1 eq 'NAME') {
$state = "name";
} elsif ($1 eq 'PREREQUISITES') {
$state = "prereq";
}
} elsif ($state =~ m{^(name|prereq)$}) {
if (/^=/) {
$state = "poddir";
} elsif (/^\s*$/) {
# nop
} elsif ($state eq "name") {
if ($name eq "") {
($name) = /^(\S+)/;
$state = "poddir";
}
} elsif ($state eq "prereq") {
$prereq .= $_;
}
} elsif (/^=cut\b/) {
last;
}
}
$fh->close;
for ($name) {
s{.*<}{}; # strip X<...>
s{>.*}{};
}
chomp $prereq;
$prereq = join " ", split /\s+/, $prereq;
my($PREREQ_PM) = join("\n", map {
s{.*<}{}; # strip X<...>
s{>.*}{};
if (/[\s\'\"]/) { # prose?
} else {
s/[^\w:]$//; # period?
" "x28 . "'$_' => 0,";
}
} split /\s*,\s*/, $prereq);
if ($name) {
my $to_file = File::Spec->catfile($build_dir, $name);
rename $script_file, $to_file
or die "Can't rename $script_file to $to_file: $!";
}
return "
EXE_FILES => ['$name'],
PREREQ_PM => {
$PREREQ_PM
},
";
}
#-> CPAN::Distribution::_signature_business
sub _signature_business {
my($self) = @_;
my $check_sigs = CPAN::HandleConfig->prefs_lookup($self,
q{check_sigs});
if ($check_sigs) {
if ($CPAN::META->has_inst("Module::Signature")) {
if (-f "SIGNATURE") {
$self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG;
my $rv = Module::Signature::verify();
if ($rv != Module::Signature::SIGNATURE_OK() and
$rv != Module::Signature::SIGNATURE_MISSING()) {
$CPAN::Frontend->mywarn(
qq{\nSignature invalid for }.
qq{distribution file. }.
qq{Please investigate.\n\n}
);
my $wrap =
sprintf(qq{I'd recommend removing %s. Some error occurred }.
qq{while checking its signature, so it could }.
qq{be invalid. Maybe you have configured }.
qq{your 'urllist' with a bad URL. Please check this }.
qq{array with 'o conf urllist' and retry. Or }.
qq{examine the distribution in a subshell. Try
look %s
and run
cpansign -v
},
$self->{localfile},
$self->pretty_id,
);
$self->{signature_verify} = CPAN::Distrostatus->new("NO");
$CPAN::Frontend->mywarn(Text::Wrap::wrap("","",$wrap));
$CPAN::Frontend->mysleep(5) if $CPAN::Frontend->can("mysleep");
} else {
$self->{signature_verify} = CPAN::Distrostatus->new("YES");
$self->debug("Module::Signature has verified") if $CPAN::DEBUG;
}
} else {
$CPAN::Frontend->mywarn(qq{Package came without SIGNATURE\n\n});
}
} else {
$self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG;
}
}
}
#-> CPAN::Distribution::untar_me ;
sub untar_me {
my($self,$ct) = @_;
$self->{archived} = "tar";
my $result = eval { $ct->untar() };
if ($result) {
$self->{unwrapped} = CPAN::Distrostatus->new("YES");
} else {
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- untar failed");
}
}
# CPAN::Distribution::unzip_me ;
sub unzip_me {
my($self,$ct) = @_;
$self->{archived} = "zip";
if ($ct->unzip()) {
$self->{unwrapped} = CPAN::Distrostatus->new("YES");
} else {
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- unzip failed");
}
return;
}
sub handle_singlefile {
my($self,$local_file) = @_;
if ( $local_file =~ /\.pm(\.(gz|Z))?(?!\n)\Z/ ) {
$self->{archived} = "pm";
} elsif ( $local_file =~ /\.patch(\.(gz|bz2))?(?!\n)\Z/ ) {
$self->{archived} = "patch";
} else {
$self->{archived} = "maybe_pl";
}
my $to = File::Basename::basename($local_file);
if ($to =~ s/\.(gz|Z)(?!\n)\Z//) {
if (eval{CPAN::Tarzip->new($local_file)->gunzip($to)}) {
$self->{unwrapped} = CPAN::Distrostatus->new("YES");
} else {
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- uncompressing failed");
}
} else {
if (File::Copy::cp($local_file,".")) {
$self->{unwrapped} = CPAN::Distrostatus->new("YES");
} else {
$self->{unwrapped} = CPAN::Distrostatus->new("NO -- copying failed");
}
}
return $to;
}
#-> sub CPAN::Distribution::new ;
sub new {
my($class,%att) = @_;
# $CPAN::META->{cachemgr} ||= CPAN::CacheMgr->new();
my $this = { %att };
return bless $this, $class;
}
#-> sub CPAN::Distribution::look ;
sub look {
my($self) = @_;
if ($^O eq 'MacOS') {
$self->Mac::BuildTools::look;
return;
}
if ( $CPAN::Config->{'shell'} ) {
$CPAN::Frontend->myprint(qq{
Trying to open a subshell in the build directory...
});
} else {
$CPAN::Frontend->myprint(qq{
Your configuration does not define a value for subshells.
Please define it with "o conf shell <your shell>"
});
return;
}
my $dist = $self->id;
my $dir;
unless ($dir = $self->dir) {
$self->get;
}
unless ($dir ||= $self->dir) {
$CPAN::Frontend->mywarn(qq{
Could not determine which directory to use for looking at $dist.
});
return;
}
my $pwd = CPAN::anycwd();
$self->safe_chdir($dir);
$CPAN::Frontend->myprint(qq{Working directory is $dir\n});
{
local $ENV{CPAN_SHELL_LEVEL} = $ENV{CPAN_SHELL_LEVEL}||0;
$ENV{CPAN_SHELL_LEVEL} += 1;
my $shell = CPAN::HandleConfig->safe_quote($CPAN::Config->{'shell'});
local $ENV{PERL5LIB} = defined($ENV{PERL5LIB})
? $ENV{PERL5LIB}
: ($ENV{PERLLIB} || "");
local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : "";
$CPAN::META->set_perl5lib;
local $ENV{MAKEFLAGS}; # protect us from outer make calls
unless (system($shell) == 0) {
my $code = $? >> 8;
$CPAN::Frontend->mywarn("Subprocess shell exit code $code\n");
}
}
$self->safe_chdir($pwd);
}
# CPAN::Distribution::cvs_import ;
sub cvs_import {
my($self) = @_;
$self->get;
my $dir = $self->dir;
my $package = $self->called_for;
my $module = $CPAN::META->instance('CPAN::Module', $package);
my $version = $module->cpan_version;
my $userid = $self->cpan_userid;
my $cvs_dir = (split /\//, $dir)[-1];
$cvs_dir =~ s/-\d+[^-]+(?!\n)\Z//;
my $cvs_root =
$CPAN::Config->{cvsroot} || $ENV{CVSROOT};
my $cvs_site_perl =
$CPAN::Config->{cvs_site_perl} || $ENV{CVS_SITE_PERL};
if ($cvs_site_perl) {
$cvs_dir = "$cvs_site_perl/$cvs_dir";
}
my $cvs_log = qq{"imported $package $version sources"};
$version =~ s/\./_/g;
# XXX cvs: undocumented and unclear how it was meant to work
my @cmd = ('cvs', '-d', $cvs_root, 'import', '-m', $cvs_log,
"$cvs_dir", $userid, "v$version");
my $pwd = CPAN::anycwd();
chdir($dir) or $CPAN::Frontend->mydie(qq{Could not chdir to "$dir": $!});
$CPAN::Frontend->myprint(qq{Working directory is $dir\n});
$CPAN::Frontend->myprint(qq{@cmd\n});
system(@cmd) == 0 or
# XXX cvs
$CPAN::Frontend->mydie("cvs import failed");
chdir($pwd) or $CPAN::Frontend->mydie(qq{Could not chdir to "$pwd": $!});
}
#-> sub CPAN::Distribution::readme ;
sub readme {
my($self) = @_;
my($dist) = $self->id;
my($sans,$suffix) = $dist =~ /(.+)\.(tgz|tar[\._-]gz|tar\.Z|zip)$/;
$self->debug("sans[$sans] suffix[$suffix]\n") if $CPAN::DEBUG;
my($local_file);
my($local_wanted) =
File::Spec->catfile(
$CPAN::Config->{keep_source_where},
"authors",
"id",
split(/\//,"$sans.readme"),
);
my $readme = "authors/id/$sans.readme";
$self->debug("Doing localize for '$readme'") if $CPAN::DEBUG;
$local_file = CPAN::FTP->localize($readme,
$local_wanted)
or $CPAN::Frontend->mydie(qq{No $sans.readme found});
if ($^O eq 'MacOS') {
Mac::BuildTools::launch_file($local_file);
return;
}
my $fh_pager = FileHandle->new;
local($SIG{PIPE}) = "IGNORE";
my $pager = $CPAN::Config->{'pager'} || "cat";
$fh_pager->open("|$pager")
or die "Could not open pager $pager\: $!";
my $fh_readme = FileHandle->new;
$fh_readme->open($local_file)
or $CPAN::Frontend->mydie(qq{Could not open "$local_file": $!});
$CPAN::Frontend->myprint(qq{
Displaying file
$local_file
with pager "$pager"
});
$fh_pager->print(<$fh_readme>);
$fh_pager->close;
}
#-> sub CPAN::Distribution::verifyCHECKSUM ;
sub verifyCHECKSUM {
my($self) = @_;
EXCUSE: {
my @e;
$self->{CHECKSUM_STATUS} ||= "";
$self->{CHECKSUM_STATUS} eq "OK" and push @e, "Checksum was ok";
$CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e;
}
my($lc_want,$lc_file,@local,$basename);
@local = split(/\//,$self->id);
pop @local;
push @local, "CHECKSUMS";
$lc_want =
File::Spec->catfile($CPAN::Config->{keep_source_where},
"authors", "id", @local);
local($") = "/";
if (my $size = -s $lc_want) {
$self->debug("lc_want[$lc_want]size[$size]") if $CPAN::DEBUG;
if ($self->CHECKSUM_check_file($lc_want,1)) {
return $self->{CHECKSUM_STATUS} = "OK";
}
}
$lc_file = CPAN::FTP->localize("authors/id/@local",
$lc_want,1);
unless ($lc_file) {
$CPAN::Frontend->myprint("Trying $lc_want.gz\n");
$local[-1] .= ".gz";
$lc_file = CPAN::FTP->localize("authors/id/@local",
"$lc_want.gz",1);
if ($lc_file) {
$lc_file =~ s/\.gz(?!\n)\Z//;
eval{CPAN::Tarzip->new("$lc_file.gz")->gunzip($lc_file)};
} else {
return;
}
}
if ($self->CHECKSUM_check_file($lc_file)) {
return $self->{CHECKSUM_STATUS} = "OK";
}
}
#-> sub CPAN::Distribution::SIG_check_file ;
sub SIG_check_file {
my($self,$chk_file) = @_;
my $rv = eval { Module::Signature::_verify($chk_file) };
if ($rv == Module::Signature::SIGNATURE_OK()) {
$CPAN::Frontend->myprint("Signature for $chk_file ok\n");
return $self->{SIG_STATUS} = "OK";
} else {
$CPAN::Frontend->myprint(qq{\nSignature invalid for }.
qq{distribution file. }.
qq{Please investigate.\n\n}.
$self->as_string,
$CPAN::META->instance(
'CPAN::Author',
$self->cpan_userid
)->as_string);
my $wrap = qq{I\'d recommend removing $chk_file. Its signature
is invalid. Maybe you have configured your 'urllist' with
a bad URL. Please check this array with 'o conf urllist', and
retry.};
$CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap));
}
}
#-> sub CPAN::Distribution::CHECKSUM_check_file ;
# sloppy is 1 when we have an old checksums file that maybe is good
# enough
sub CHECKSUM_check_file {
my($self,$chk_file,$sloppy) = @_;
my($cksum,$file,$basename);
$sloppy ||= 0;
$self->debug("chk_file[$chk_file]sloppy[$sloppy]") if $CPAN::DEBUG;
my $check_sigs = CPAN::HandleConfig->prefs_lookup($self,
q{check_sigs});
if ($check_sigs) {
if ($CPAN::META->has_inst("Module::Signature")) {
$self->debug("Module::Signature is installed, verifying") if $CPAN::DEBUG;
$self->SIG_check_file($chk_file);
} else {
$self->debug("Module::Signature is NOT installed") if $CPAN::DEBUG;
}
}
$file = $self->{localfile};
$basename = File::Basename::basename($file);
my $fh = FileHandle->new;
if (open $fh, $chk_file) {
local($/);
my $eval = <$fh>;
$eval =~ s/\015?\012/\n/g;
close $fh;
my($compmt) = Safe->new();
$cksum = $compmt->reval($eval);
if ($@) {
rename $chk_file, "$chk_file.bad";
Carp::confess($@) if $@;
}
} else {
Carp::carp "Could not open $chk_file for reading";
}
if (! ref $cksum or ref $cksum ne "HASH") {
$CPAN::Frontend->mywarn(qq{
Warning: checksum file '$chk_file' broken.
When trying to read that file I expected to get a hash reference
for further processing, but got garbage instead.
});
my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed nonetheless?", "no");
$answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n");
$self->{CHECKSUM_STATUS} = "NIL -- CHECKSUMS file broken";
return;
} elsif (exists $cksum->{$basename}{sha256}) {
$self->debug("Found checksum for $basename:" .
"$cksum->{$basename}{sha256}\n") if $CPAN::DEBUG;
open($fh, $file);
binmode $fh;
my $eq = $self->eq_CHECKSUM($fh,$cksum->{$basename}{sha256});
$fh->close;
$fh = CPAN::Tarzip->TIEHANDLE($file);
unless ($eq) {
my $dg = Digest::SHA->new(256);
my($data,$ref);
$ref = \$data;
while ($fh->READ($ref, 4096) > 0) {
$dg->add($data);
}
my $hexdigest = $dg->hexdigest;
$eq += $hexdigest eq $cksum->{$basename}{'sha256-ungz'};
}
if ($eq) {
$CPAN::Frontend->myprint("Checksum for $file ok\n");
return $self->{CHECKSUM_STATUS} = "OK";
} else {
$CPAN::Frontend->myprint(qq{\nChecksum mismatch for }.
qq{distribution file. }.
qq{Please investigate.\n\n}.
$self->as_string,
$CPAN::META->instance(
'CPAN::Author',
$self->cpan_userid
)->as_string);
my $wrap = qq{I\'d recommend removing $file. Its
checksum is incorrect. Maybe you have configured your 'urllist' with
a bad URL. Please check this array with 'o conf urllist', and
retry.};
$CPAN::Frontend->mydie(Text::Wrap::wrap("","",$wrap));
# former versions just returned here but this seems a
# serious threat that deserves a die
# $CPAN::Frontend->myprint("\n\n");
# sleep 3;
# return;
}
# close $fh if fileno($fh);
} else {
return if $sloppy;
unless ($self->{CHECKSUM_STATUS}) {
$CPAN::Frontend->mywarn(qq{
Warning: No checksum for $basename in $chk_file.
The cause for this may be that the file is very new and the checksum
has not yet been calculated, but it may also be that something is
going awry right now.
});
my $answer = CPAN::Shell::colorable_makemaker_prompt("Proceed?", "yes");
$answer =~ /^\s*y/i or $CPAN::Frontend->mydie("Aborted.\n");
}
$self->{CHECKSUM_STATUS} = "NIL -- distro not in CHECKSUMS file";
return;
}
}
#-> sub CPAN::Distribution::eq_CHECKSUM ;
sub eq_CHECKSUM {
my($self,$fh,$expect) = @_;
if ($CPAN::META->has_inst("Digest::SHA")) {
my $dg = Digest::SHA->new(256);
my($data);
while (read($fh, $data, 4096)) {
$dg->add($data);
}
my $hexdigest = $dg->hexdigest;
# warn "fh[$fh] hex[$hexdigest] aexp[$expectMD5]";
return $hexdigest eq $expect;
}
return 1;
}
#-> sub CPAN::Distribution::force ;
# Both CPAN::Modules and CPAN::Distributions know if "force" is in
# effect by autoinspection, not by inspecting a global variable. One
# of the reason why this was chosen to work that way was the treatment
# of dependencies. They should not automatically inherit the force
# status. But this has the downside that ^C and die() will return to
# the prompt but will not be able to reset the force_update
# attributes. We try to correct for it currently in the read_metadata
# routine, and immediately before we check for a Signal. I hope this
# works out in one of v1.57_53ff
# "Force get forgets previous error conditions"
#-> sub CPAN::Distribution::fforce ;
sub fforce {
my($self, $method) = @_;
$self->force($method,1);
}
#-> sub CPAN::Distribution::force ;
sub force {
my($self, $method,$fforce) = @_;
my %phase_map = (
get => [
"unwrapped",
"build_dir",
"archived",
"localfile",
"CHECKSUM_STATUS",
"signature_verify",
"prefs",
"prefs_file",
"prefs_file_doc",
],
make => [
"writemakefile",
"make",
"modulebuild",
"prereq_pm",
],
test => [
"badtestcnt",
"make_test",
],
install => [
"install",
],
unknown => [
"reqtype",
"yaml_content",
],
);
my $methodmatch = 0;
my $ldebug = 0;
PHASE: for my $phase (qw(unknown get make test install)) { # order matters
$methodmatch = 1 if $fforce || $phase eq $method;
next unless $methodmatch;
ATTRIBUTE: for my $att (@{$phase_map{$phase}}) {
if ($phase eq "get") {
if (substr($self->id,-1,1) eq "."
&& $att =~ /(unwrapped|build_dir|archived)/ ) {
# cannot be undone for local distros
next ATTRIBUTE;
}
if ($att eq "build_dir"
&& $self->{build_dir}
&& $CPAN::META->{is_tested}
) {
delete $CPAN::META->{is_tested}{$self->{build_dir}};
}
} elsif ($phase eq "test") {
if ($att eq "make_test"
&& $self->{make_test}
&& $self->{make_test}{COMMANDID}
&& $self->{make_test}{COMMANDID} == $CPAN::CurrentCommandId
) {
# endless loop too likely
next ATTRIBUTE;
}
}
delete $self->{$att};
if ($ldebug || $CPAN::DEBUG) {
# local $CPAN::DEBUG = 16; # Distribution
CPAN->debug(sprintf "id[%s]phase[%s]att[%s]", $self->id, $phase, $att);
}
}
}
if ($method && $method =~ /make|test|install/) {
$self->{force_update} = 1; # name should probably have been force_install
}
}
#-> sub CPAN::Distribution::notest ;
sub notest {
my($self, $method) = @_;
# $CPAN::Frontend->mywarn("XDEBUG: set notest for $self $method");
$self->{"notest"}++; # name should probably have been force_install
}
#-> sub CPAN::Distribution::unnotest ;
sub unnotest {
my($self) = @_;
# warn "XDEBUG: deleting notest";
delete $self->{notest};
}
#-> sub CPAN::Distribution::unforce ;
sub unforce {
my($self) = @_;
delete $self->{force_update};
}
#-> sub CPAN::Distribution::isa_perl ;
sub isa_perl {
my($self) = @_;
my $file = File::Basename::basename($self->id);
if ($file =~ m{ ^ perl
-?
(5)
([._-])
(
\d{3}(_[0-4][0-9])?
|
\d+\.\d+
)
\.tar[._-](?:gz|bz2)
(?!\n)\Z
}xs) {
return "$1.$3";
} elsif ($self->cpan_comment
&&
$self->cpan_comment =~ /isa_perl\(.+?\)/) {
return $1;
}
}
#-> sub CPAN::Distribution::perl ;
sub perl {
my ($self) = @_;
if (! $self) {
use Carp qw(carp);
carp __PACKAGE__ . "::perl was called without parameters.";
}
return CPAN::HandleConfig->safe_quote($CPAN::Perl);
}
#-> sub CPAN::Distribution::make ;
sub make {
my($self) = @_;
if (my $goto = $self->prefs->{goto}) {
return $self->goto($goto);
}
my $make = $self->{modulebuild} ? "Build" : "make";
# Emergency brake if they said install Pippi and get newest perl
if ($self->isa_perl) {
if (
$self->called_for ne $self->id &&
! $self->{force_update}
) {
# if we die here, we break bundles
$CPAN::Frontend
->mywarn(sprintf(
qq{The most recent version "%s" of the module "%s"
is part of the perl-%s distribution. To install that, you need to run
force install %s --or--
install %s
},
$CPAN::META->instance(
'CPAN::Module',
$self->called_for
)->cpan_version,
$self->called_for,
$self->isa_perl,
$self->called_for,
$self->id,
));
$self->{make} = CPAN::Distrostatus->new("NO isa perl");
$CPAN::Frontend->mysleep(1);
return;
}
}
$CPAN::Frontend->myprint(sprintf "Running %s for %s\n", $make, $self->id);
$self->get;
return if $self->prefs->{disabled} && ! $self->{force_update};
if ($self->{configure_requires_later}) {
return;
}
local $ENV{PERL5LIB} = defined($ENV{PERL5LIB})
? $ENV{PERL5LIB}
: ($ENV{PERLLIB} || "");
local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : "";
$CPAN::META->set_perl5lib;
local $ENV{MAKEFLAGS}; # protect us from outer make calls
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
my $builddir;
EXCUSE: {
my @e;
if (!$self->{archived} || $self->{archived} eq "NO") {
push @e, "Is neither a tar nor a zip archive.";
}
if (!$self->{unwrapped}
|| (
UNIVERSAL::can($self->{unwrapped},"failed") ?
$self->{unwrapped}->failed :
$self->{unwrapped} =~ /^NO/
)) {
push @e, "Had problems unarchiving. Please build manually";
}
unless ($self->{force_update}) {
exists $self->{signature_verify} and
(
UNIVERSAL::can($self->{signature_verify},"failed") ?
$self->{signature_verify}->failed :
$self->{signature_verify} =~ /^NO/
)
and push @e, "Did not pass the signature test.";
}
if (exists $self->{writemakefile} &&
(
UNIVERSAL::can($self->{writemakefile},"failed") ?
$self->{writemakefile}->failed :
$self->{writemakefile} =~ /^NO/
)) {
# XXX maybe a retry would be in order?
my $err = UNIVERSAL::can($self->{writemakefile},"text") ?
$self->{writemakefile}->text :
$self->{writemakefile};
$err =~ s/^NO\s*(--\s+)?//;
$err ||= "Had some problem writing Makefile";
$err .= ", won't make";
push @e, $err;
}
if (defined $self->{make}) {
if (UNIVERSAL::can($self->{make},"failed") ?
$self->{make}->failed :
$self->{make} =~ /^NO/) {
if ($self->{force_update}) {
# Trying an already failed 'make' (unless somebody else blocks)
} else {
# introduced for turning recursion detection into a distrostatus
my $error = length $self->{make}>3
? substr($self->{make},3) : "Unknown error";
$CPAN::Frontend->mywarn("Could not make: $error\n");
$self->store_persistent_state;
return;
}
} else {
push @e, "Has already been made";
my $wait_for_prereqs = eval { $self->satisfy_requires };
return 1 if $wait_for_prereqs; # tells queuerunner to continue
return $self->goodbye($@) if $@; # tells queuerunner to stop
}
}
my $later = $self->{later} || $self->{configure_requires_later};
if ($later) { # see also undelay
if ($later) {
push @e, $later;
}
}
$CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e;
$builddir = $self->dir or
$CPAN::Frontend->mydie("PANIC: Cannot determine build directory\n");
unless (chdir $builddir) {
push @e, "Couldn't chdir to '$builddir': $!";
}
$CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e;
}
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
$CPAN::Frontend->myprint("\n CPAN.pm: Building ".$self->id."\n\n");
$self->debug("Changed directory to $builddir") if $CPAN::DEBUG;
if ($^O eq 'MacOS') {
Mac::BuildTools::make($self);
return;
}
my %env;
while (my($k,$v) = each %ENV) {
next unless defined $v;
$env{$k} = $v;
}
local %ENV = %env;
if ($CPAN::Config->{prerequisites_policy} eq "follow") {
$ENV{PERL_AUTOINSTALL} ||= "--defaultdeps";
$ENV{PERL_EXTUTILS_AUTOINSTALL} ||= "--defaultdeps";
}
my $system;
my $pl_commandline;
if ($self->prefs->{pl}) {
$pl_commandline = $self->prefs->{pl}{commandline};
}
if ($pl_commandline) {
$system = $pl_commandline;
$ENV{PERL} = $^X;
} elsif ($self->{'configure'}) {
$system = $self->{'configure'};
} elsif ($self->{modulebuild}) {
my($perl) = $self->perl or die "Couldn\'t find executable perl\n";
$system = "$perl Build.PL $CPAN::Config->{mbuildpl_arg}";
} else {
my($perl) = $self->perl or die "Couldn\'t find executable perl\n";
my $switch = "";
# This needs a handler that can be turned on or off:
# $switch = "-MExtUtils::MakeMaker ".
# "-Mops=:default,:filesys_read,:filesys_open,require,chdir"
# if $] > 5.00310;
my $makepl_arg = $self->_make_phase_arg("pl");
$ENV{PERL5_CPAN_IS_EXECUTING} = File::Spec->catfile($self->{build_dir},
"Makefile.PL");
$system = sprintf("%s%s Makefile.PL%s",
$perl,
$switch ? " $switch" : "",
$makepl_arg ? " $makepl_arg" : "",
);
}
my $pl_env;
if ($self->prefs->{pl}) {
$pl_env = $self->prefs->{pl}{env};
}
if ($pl_env) {
for my $e (keys %$pl_env) {
$ENV{$e} = $pl_env->{$e};
}
}
if (exists $self->{writemakefile}) {
} else {
local($SIG{ALRM}) = sub { die "inactivity_timeout reached\n" };
my($ret,$pid,$output);
$@ = "";
my $go_via_alarm;
if ($CPAN::Config->{inactivity_timeout}) {
require Config;
if ($Config::Config{d_alarm}
&&
$Config::Config{d_alarm} eq "define"
) {
$go_via_alarm++
} else {
$CPAN::Frontend->mywarn("Warning: you have configured the config ".
"variable 'inactivity_timeout' to ".
"'$CPAN::Config->{inactivity_timeout}'. But ".
"on this machine the system call 'alarm' ".
"isn't available. This means that we cannot ".
"provide the feature of intercepting long ".
"waiting code and will turn this feature off.\n"
);
$CPAN::Config->{inactivity_timeout} = 0;
}
}
if ($go_via_alarm) {
if ( $self->_should_report('pl') ) {
($output, $ret) = CPAN::Reporter::record_command(
$system,
$CPAN::Config->{inactivity_timeout},
);
CPAN::Reporter::grade_PL( $self, $system, $output, $ret );
}
else {
eval {
alarm $CPAN::Config->{inactivity_timeout};
local $SIG{CHLD}; # = sub { wait };
if (defined($pid = fork)) {
if ($pid) { #parent
# wait;
waitpid $pid, 0;
} else { #child
# note, this exec isn't necessary if
# inactivity_timeout is 0. On the Mac I'd
# suggest, we set it always to 0.
exec $system;
}
} else {
$CPAN::Frontend->myprint("Cannot fork: $!");
return;
}
};
alarm 0;
if ($@) {
kill 9, $pid;
waitpid $pid, 0;
my $err = "$@";
$CPAN::Frontend->myprint($err);
$self->{writemakefile} = CPAN::Distrostatus->new("NO $err");
$@ = "";
$self->store_persistent_state;
return $self->goodbye("$system -- TIMED OUT");
}
}
} else {
if (my $expect_model = $self->_prefs_with_expect("pl")) {
# XXX probably want to check _should_report here and warn
# about not being able to use CPAN::Reporter with expect
$ret = $self->_run_via_expect($system,'writemakefile',$expect_model);
if (! defined $ret
&& $self->{writemakefile}
&& $self->{writemakefile}->failed) {
# timeout
return;
}
}
elsif ( $self->_should_report('pl') ) {
($output, $ret) = CPAN::Reporter::record_command($system);
CPAN::Reporter::grade_PL( $self, $system, $output, $ret );
}
else {
$ret = system($system);
}
if ($ret != 0) {
$self->{writemakefile} = CPAN::Distrostatus
->new("NO '$system' returned status $ret");
$CPAN::Frontend->mywarn("Warning: No success on command[$system]\n");
$self->store_persistent_state;
return $self->goodbye("$system -- NOT OK");
}
}
if (-f "Makefile" || -f "Build") {
$self->{writemakefile} = CPAN::Distrostatus->new("YES");
delete $self->{make_clean}; # if cleaned before, enable next
} else {
my $makefile = $self->{modulebuild} ? "Build" : "Makefile";
my $why = "No '$makefile' created";
$CPAN::Frontend->mywarn($why);
$self->{writemakefile} = CPAN::Distrostatus
->new(qq{NO -- $why\n});
$self->store_persistent_state;
return $self->goodbye("$system -- NOT OK");
}
}
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
my $wait_for_prereqs = eval { $self->satisfy_requires };
return 1 if $wait_for_prereqs; # tells queuerunner to continue
return $self->goodbye($@) if $@; # tells queuerunner to stop
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
my $make_commandline;
if ($self->prefs->{make}) {
$make_commandline = $self->prefs->{make}{commandline};
}
if ($make_commandline) {
$system = $make_commandline;
$ENV{PERL} = CPAN::find_perl();
} else {
if ($self->{modulebuild}) {
unless (-f "Build") {
my $cwd = CPAN::anycwd();
$CPAN::Frontend->mywarn("Alert: no Build file available for 'make $self->{id}'".
" in cwd[$cwd]. Danger, Will Robinson!\n");
$CPAN::Frontend->mysleep(5);
}
$system = join " ", $self->_build_command(), $CPAN::Config->{mbuild_arg};
} else {
$system = join " ", $self->_make_command(), $CPAN::Config->{make_arg};
}
$system =~ s/\s+$//;
my $make_arg = $self->_make_phase_arg("make");
$system = sprintf("%s%s",
$system,
$make_arg ? " $make_arg" : "",
);
}
my $make_env;
if ($self->prefs->{make}) {
$make_env = $self->prefs->{make}{env};
}
if ($make_env) { # overriding the local ENV of PL, not the outer
# ENV, but unlikely to be a risk
for my $e (keys %$make_env) {
$ENV{$e} = $make_env->{$e};
}
}
my $expect_model = $self->_prefs_with_expect("make");
my $want_expect = 0;
if ( $expect_model && @{$expect_model->{talk}} ) {
my $can_expect = $CPAN::META->has_inst("Expect");
if ($can_expect) {
$want_expect = 1;
} else {
$CPAN::Frontend->mywarn("Expect not installed, falling back to ".
"system()\n");
}
}
my $system_ok;
if ($want_expect) {
# XXX probably want to check _should_report here and
# warn about not being able to use CPAN::Reporter with expect
$system_ok = $self->_run_via_expect($system,'make',$expect_model) == 0;
}
elsif ( $self->_should_report('make') ) {
my ($output, $ret) = CPAN::Reporter::record_command($system);
CPAN::Reporter::grade_make( $self, $system, $output, $ret );
$system_ok = ! $ret;
}
else {
$system_ok = system($system) == 0;
}
$self->introduce_myself;
if ( $system_ok ) {
$CPAN::Frontend->myprint(" $system -- OK\n");
$self->{make} = CPAN::Distrostatus->new("YES");
} else {
$self->{writemakefile} ||= CPAN::Distrostatus->new("YES");
$self->{make} = CPAN::Distrostatus->new("NO");
$CPAN::Frontend->mywarn(" $system -- NOT OK\n");
}
$self->store_persistent_state;
}
# CPAN::Distribution::goodbye ;
sub goodbye {
my($self,$goodbye) = @_;
my $id = $self->pretty_id;
$CPAN::Frontend->mywarn(" $id\n $goodbye\n");
return;
}
# CPAN::Distribution::_run_via_expect ;
sub _run_via_expect {
my($self,$system,$phase,$expect_model) = @_;
CPAN->debug("system[$system]expect_model[$expect_model]") if $CPAN::DEBUG;
if ($CPAN::META->has_inst("Expect")) {
my $expo = Expect->new; # expo Expect object;
$expo->spawn($system);
$expect_model->{mode} ||= "deterministic";
if ($expect_model->{mode} eq "deterministic") {
return $self->_run_via_expect_deterministic($expo,$phase,$expect_model);
} elsif ($expect_model->{mode} eq "anyorder") {
return $self->_run_via_expect_anyorder($expo,$phase,$expect_model);
} else {
die "Panic: Illegal expect mode: $expect_model->{mode}";
}
} else {
$CPAN::Frontend->mywarn("Expect not installed, falling back to system()\n");
return system($system);
}
}
sub _run_via_expect_anyorder {
my($self,$expo,$phase,$expect_model) = @_;
my $timeout = $expect_model->{timeout} || 5;
my $reuse = $expect_model->{reuse};
my @expectacopy = @{$expect_model->{talk}}; # we trash it!
my $but = "";
my $timeout_start = time;
EXPECT: while () {
my($eof,$ran_into_timeout);
# XXX not up to the full power of expect. one could certainly
# wrap all of the talk pairs into a single expect call and on
# success tweak it and step ahead to the next question. The
# current implementation unnecessarily limits itself to a
# single match.
my @match = $expo->expect(1,
[ eof => sub {
$eof++;
} ],
[ timeout => sub {
$ran_into_timeout++;
} ],
-re => eval"qr{.}",
);
if ($match[2]) {
$but .= $match[2];
}
$but .= $expo->clear_accum;
if ($eof) {
$expo->soft_close;
return $expo->exitstatus();
} elsif ($ran_into_timeout) {
# warn "DEBUG: they are asking a question, but[$but]";
for (my $i = 0; $i <= $#expectacopy; $i+=2) {
my($next,$send) = @expectacopy[$i,$i+1];
my $regex = eval "qr{$next}";
# warn "DEBUG: will compare with regex[$regex].";
if ($but =~ /$regex/) {
# warn "DEBUG: will send send[$send]";
$expo->send($send);
# never allow reusing an QA pair unless they told us
splice @expectacopy, $i, 2 unless $reuse;
$but =~ s/(?s:^.*?)$regex//;
$timeout_start = time;
next EXPECT;
}
}
my $have_waited = time - $timeout_start;
if ($have_waited < $timeout) {
# warn "DEBUG: have_waited[$have_waited]timeout[$timeout]";
next EXPECT;
}
my $why = "could not answer a question during the dialog";
$CPAN::Frontend->mywarn("Failing: $why\n");
$self->{$phase} =
CPAN::Distrostatus->new("NO $why");
return 0;
}
}
}
sub _run_via_expect_deterministic {
my($self,$expo,$phase,$expect_model) = @_;
my $ran_into_timeout;
my $ran_into_eof;
my $timeout = $expect_model->{timeout} || 15; # currently unsettable
my $expecta = $expect_model->{talk};
EXPECT: for (my $i = 0; $i <= $#$expecta; $i+=2) {
my($re,$send) = @$expecta[$i,$i+1];
CPAN->debug("timeout[$timeout]re[$re]") if $CPAN::DEBUG;
my $regex = eval "qr{$re}";
$expo->expect($timeout,
[ eof => sub {
my $but = $expo->clear_accum;
$CPAN::Frontend->mywarn("EOF (maybe harmless)
expected[$regex]\nbut[$but]\n\n");
$ran_into_eof++;
} ],
[ timeout => sub {
my $but = $expo->clear_accum;
$CPAN::Frontend->mywarn("TIMEOUT
expected[$regex]\nbut[$but]\n\n");
$ran_into_timeout++;
} ],
-re => $regex);
if ($ran_into_timeout) {
# note that the caller expects 0 for success
$self->{$phase} =
CPAN::Distrostatus->new("NO timeout during expect dialog");
return 0;
} elsif ($ran_into_eof) {
last EXPECT;
}
$expo->send($send);
}
$expo->soft_close;
return $expo->exitstatus();
}
#-> CPAN::Distribution::_validate_distropref
sub _validate_distropref {
my($self,@args) = @_;
if (
$CPAN::META->has_inst("CPAN::Kwalify")
&&
$CPAN::META->has_inst("Kwalify")
) {
eval {CPAN::Kwalify::_validate("distroprefs",@args);};
if ($@) {
$CPAN::Frontend->mywarn($@);
}
} else {
CPAN->debug("not validating '@args'") if $CPAN::DEBUG;
}
}
#-> CPAN::Distribution::_find_prefs
sub _find_prefs {
my($self) = @_;
my $distroid = $self->pretty_id;
#CPAN->debug("distroid[$distroid]") if $CPAN::DEBUG;
my $prefs_dir = $CPAN::Config->{prefs_dir};
return if $prefs_dir =~ /^\s*$/;
eval { File::Path::mkpath($prefs_dir); };
if ($@) {
$CPAN::Frontend->mydie("Cannot create directory $prefs_dir");
}
# shortcut if there are no distroprefs files
{
my $dh = DirHandle->new($prefs_dir) or $CPAN::Frontend->mydie("Couldn't open '$prefs_dir': $!");
my @files = map { /\.(yml|dd|st)\z/i } $dh->read;
return unless @files;
}
my $yaml_module = CPAN::_yaml_module();
my $ext_map = {};
my @extensions;
if ($CPAN::META->has_inst($yaml_module)) {
$ext_map->{yml} = 'CPAN';
} else {
my @fallbacks;
if ($CPAN::META->has_inst("Data::Dumper")) {
push @fallbacks, $ext_map->{dd} = 'Data::Dumper';
}
if ($CPAN::META->has_inst("Storable")) {
push @fallbacks, $ext_map->{st} = 'Storable';
}
if (@fallbacks) {
local $" = " and ";
unless ($self->{have_complained_about_missing_yaml}++) {
$CPAN::Frontend->mywarnonce("'$yaml_module' not installed, falling back ".
"to @fallbacks to read prefs '$prefs_dir'\n");
}
} else {
unless ($self->{have_complained_about_missing_yaml}++) {
$CPAN::Frontend->mywarnonce("'$yaml_module' not installed, cannot ".
"read prefs '$prefs_dir'\n");
}
}
}
my $finder = CPAN::Distroprefs->find($prefs_dir, $ext_map);
DIRENT: while (my $result = $finder->next) {
if ($result->is_warning) {
$CPAN::Frontend->mywarn($result->as_string);
$CPAN::Frontend->mysleep(1);
next DIRENT;
} elsif ($result->is_fatal) {
$CPAN::Frontend->mydie($result->as_string);
}
my @prefs = @{ $result->prefs };
ELEMENT: for my $y (0..$#prefs) {
my $pref = $prefs[$y];
$self->_validate_distropref($pref->data, $result->abs, $y);
# I don't know why we silently skip when there's no match, but
# complain if there's an empty match hashref, and there's no
# comment explaining why -- hdp, 2008-03-18
unless ($pref->has_any_match) {
next ELEMENT;
}
unless ($pref->has_valid_subkeys) {
$CPAN::Frontend->mydie(sprintf
"Nonconforming .%s file '%s': " .
"missing match/* subattribute. " .
"Please remove, cannot continue.",
$result->ext, $result->abs,
);
}
my $arg = {
env => \%ENV,
distribution => $distroid,
perl => \&CPAN::find_perl,
perlconfig => \%Config::Config,
module => sub { [ $self->containsmods ] },
};
if ($pref->matches($arg)) {
return {
prefs => $pref->data,
prefs_file => $result->abs,
prefs_file_doc => $y,
};
}
}
}
return;
}
# CPAN::Distribution::prefs
sub prefs {
my($self) = @_;
if (exists $self->{negative_prefs_cache}
&&
$self->{negative_prefs_cache} != $CPAN::CurrentCommandId
) {
delete $self->{negative_prefs_cache};
delete $self->{prefs};
}
if (exists $self->{prefs}) {
return $self->{prefs}; # XXX comment out during debugging
}
if ($CPAN::Config->{prefs_dir}) {
CPAN->debug("prefs_dir[$CPAN::Config->{prefs_dir}]") if $CPAN::DEBUG;
my $prefs = $self->_find_prefs();
$prefs ||= ""; # avoid warning next line
CPAN->debug("prefs[$prefs]") if $CPAN::DEBUG;
if ($prefs) {
for my $x (qw(prefs prefs_file prefs_file_doc)) {
$self->{$x} = $prefs->{$x};
}
my $bs = sprintf(
"%s[%s]",
File::Basename::basename($self->{prefs_file}),
$self->{prefs_file_doc},
);
my $filler1 = "_" x 22;
my $filler2 = int(66 - length($bs))/2;
$filler2 = 0 if $filler2 < 0;
$filler2 = " " x $filler2;
$CPAN::Frontend->myprint("
$filler1 D i s t r o P r e f s $filler1
$filler2 $bs $filler2
");
$CPAN::Frontend->mysleep(1);
return $self->{prefs};
}
}
$self->{negative_prefs_cache} = $CPAN::CurrentCommandId;
return $self->{prefs} = +{};
}
# CPAN::Distribution::_make_phase_arg
sub _make_phase_arg {
my($self, $phase) = @_;
my $_make_phase_arg;
my $prefs = $self->prefs;
if (
$prefs
&& exists $prefs->{$phase}
&& exists $prefs->{$phase}{args}
&& $prefs->{$phase}{args}
) {
$_make_phase_arg = join(" ",
map {CPAN::HandleConfig
->safe_quote($_)} @{$prefs->{$phase}{args}},
);
}
# cpan[2]> o conf make[TAB]
# make make_install_make_command
# make_arg makepl_arg
# make_install_arg
# cpan[2]> o conf mbuild[TAB]
# mbuild_arg mbuild_install_build_command
# mbuild_install_arg mbuildpl_arg
my $mantra; # must switch make/mbuild here
if ($self->{modulebuild}) {
$mantra = "mbuild";
} else {
$mantra = "make";
}
my %map = (
pl => "pl_arg",
make => "_arg",
test => "_test_arg", # does not really exist but maybe
# will some day and now protects
# us from unini warnings
install => "_install_arg",
);
my $phase_underscore_meshup = $map{$phase};
my $what = sprintf "%s%s", $mantra, $phase_underscore_meshup;
$_make_phase_arg ||= $CPAN::Config->{$what};
return $_make_phase_arg;
}
# CPAN::Distribution::_make_command
sub _make_command {
my ($self) = @_;
if ($self) {
return
CPAN::HandleConfig
->safe_quote(
CPAN::HandleConfig->prefs_lookup($self,
q{make})
|| $Config::Config{make}
|| 'make'
);
} else {
# Old style call, without object. Deprecated
Carp::confess("CPAN::_make_command() used as function. Don't Do That.");
return
safe_quote(undef,
CPAN::HandleConfig->prefs_lookup($self,q{make})
|| $CPAN::Config->{make}
|| $Config::Config{make}
|| 'make');
}
}
#-> sub CPAN::Distribution::follow_prereqs ;
sub follow_prereqs {
my($self) = shift;
my($slot) = shift;
my(@prereq_tuples) = grep {$_->[0] ne "perl"} @_;
return unless @prereq_tuples;
my(@good_prereq_tuples);
for my $p (@prereq_tuples) {
# promote if possible
if ($p->[1] =~ /^(r|c)$/) {
push @good_prereq_tuples, $p;
} elsif ($p->[1] =~ /^(b)$/) {
my $reqtype = CPAN::Queue->reqtype_of($p->[0]);
if ($reqtype =~ /^(r|c)$/) {
push @good_prereq_tuples, [$p->[0], $reqtype];
} else {
push @good_prereq_tuples, $p;
}
} else {
die "Panic: in follow_prereqs: reqtype[$p->[1]] seen, should never happen";
}
}
my $pretty_id = $self->pretty_id;
my %map = (
b => "build_requires",
r => "requires",
c => "commandline",
);
my($filler1,$filler2,$filler3,$filler4);
my $unsat = "Unsatisfied dependencies detected during";
my $w = length($unsat) > length($pretty_id) ? length($unsat) : length($pretty_id);
{
my $r = int(($w - length($unsat))/2);
my $l = $w - length($unsat) - $r;
$filler1 = "-"x4 . " "x$l;
$filler2 = " "x$r . "-"x4 . "\n";
}
{
my $r = int(($w - length($pretty_id))/2);
my $l = $w - length($pretty_id) - $r;
$filler3 = "-"x4 . " "x$l;
$filler4 = " "x$r . "-"x4 . "\n";
}
$CPAN::Frontend->
myprint("$filler1 $unsat $filler2".
"$filler3 $pretty_id $filler4".
join("", map {" $_->[0] \[$map{$_->[1]}]\n"} @good_prereq_tuples),
);
my $follow = 0;
if ($CPAN::Config->{prerequisites_policy} eq "follow") {
$follow = 1;
} elsif ($CPAN::Config->{prerequisites_policy} eq "ask") {
my $answer = CPAN::Shell::colorable_makemaker_prompt(
"Shall I follow them and prepend them to the queue
of modules we are processing right now?", "yes");
$follow = $answer =~ /^\s*y/i;
} else {
my @prereq = map { $_->[0] } @good_prereq_tuples;
local($") = ", ";
$CPAN::Frontend->
myprint(" Ignoring dependencies on modules @prereq\n");
}
if ($follow) {
my $id = $self->id;
# color them as dirty
for my $gp (@good_prereq_tuples) {
# warn "calling color_cmd_tmps(0,1)";
my $p = $gp->[0];
my $any = CPAN::Shell->expandany($p);
$self->{$slot . "_for"}{$any->id}++;
if ($any) {
$any->color_cmd_tmps(0,2);
} else {
$CPAN::Frontend->mywarn("Warning (maybe a bug): Cannot expand prereq '$p'\n");
$CPAN::Frontend->mysleep(2);
}
}
# queue them and re-queue yourself
CPAN::Queue->jumpqueue({qmod => $id, reqtype => $self->{reqtype}},
map {+{qmod=>$_->[0],reqtype=>$_->[1]}} reverse @good_prereq_tuples);
$self->{$slot} = "Delayed until after prerequisites";
return 1; # signal success to the queuerunner
}
return;
}
sub _feature_depends {
my($self) = @_;
my $meta_yml = $self->parse_meta_yml();
my $optf = $meta_yml->{optional_features} or return;
if (!ref $optf or ref $optf ne "HASH"){
$CPAN::Frontend->mywarn("The content of optional_features is not a HASH reference. Cannot use it.\n");
$optf = {};
}
my $wantf = $self->prefs->{features} or return;
if (!ref $wantf or ref $wantf ne "ARRAY"){
$CPAN::Frontend->mywarn("The content of 'features' is not an ARRAY reference. Cannot use it.\n");
$wantf = [];
}
my $dep = +{};
for my $wf (@$wantf) {
if (my $f = $optf->{$wf}) {
$CPAN::Frontend->myprint("Found the demanded feature '$wf' that ".
"is accompanied by this description:\n".
$f->{description}.
"\n\n"
);
# configure_requires currently not in the spec, unlikely to be useful anyway
for my $reqtype (qw(configure_requires build_requires requires)) {
my $reqhash = $f->{$reqtype} or next;
while (my($k,$v) = each %$reqhash) {
$dep->{$reqtype}{$k} = $v;
}
}
} else {
$CPAN::Frontend->mywarn("The demanded feature '$wf' was not ".
"found in the META.yml file".
"\n\n"
);
}
}
$dep;
}
#-> sub CPAN::Distribution::unsat_prereq ;
# return ([Foo,"r"],[Bar,"b"]) for normal modules
# return ([perl=>5.008]) if we need a newer perl than we are running under
# (sorry for the inconsistency, it was an accident)
sub unsat_prereq {
my($self,$slot) = @_;
my(%merged,$prereq_pm);
my $prefs_depends = $self->prefs->{depends}||{};
my $feature_depends = $self->_feature_depends();
if ($slot eq "configure_requires_later") {
my $meta_configure_requires = $self->configure_requires();
%merged = (
%{$meta_configure_requires||{}},
%{$prefs_depends->{configure_requires}||{}},
%{$feature_depends->{configure_requires}||{}},
);
if (-f "Build.PL"
&& ! -f "Makefile.PL"
&& ! exists $merged{"Module::Build"}
&& ! $CPAN::META->has_inst("Module::Build")
) {
$CPAN::Frontend->mywarn(
" Warning: CPAN.pm discovered Module::Build as undeclared prerequisite.\n".
" Adding it now as such.\n"
);
$CPAN::Frontend->mysleep(5);
$merged{"Module::Build"} = 0;
delete $self->{writemakefile};
}
$prereq_pm = {}; # configure_requires defined as "b"
} elsif ($slot eq "later") {
my $prereq_pm_0 = $self->prereq_pm || {};
for my $reqtype (qw(requires build_requires)) {
$prereq_pm->{$reqtype} = {%{$prereq_pm_0->{$reqtype}||{}}}; # copy to not pollute it
for my $dep ($prefs_depends,$feature_depends) {
for my $k (keys %{$dep->{$reqtype}||{}}) {
$prereq_pm->{$reqtype}{$k} = $dep->{$reqtype}{$k};
}
}
}
%merged = (%{$prereq_pm->{requires}||{}},%{$prereq_pm->{build_requires}||{}});
} else {
die "Panic: illegal slot '$slot'";
}
my(@need);
my @merged = %merged;
CPAN->debug("all merged_prereqs[@merged]") if $CPAN::DEBUG;
NEED: while (my($need_module, $need_version) = each %merged) {
my($available_version,$inst_file,$available_file,$nmo);
if ($need_module eq "perl") {
$available_version = $];
$available_file = CPAN::find_perl();
} else {
if (CPAN::_sqlite_running()) {
CPAN::Index->reload;
$CPAN::SQLite->search("CPAN::Module",$need_module);
}
$nmo = $CPAN::META->instance("CPAN::Module",$need_module);
next if $nmo->uptodate;
$inst_file = $nmo->inst_file || '';
$available_file = $nmo->available_file || '';
# if they have not specified a version, we accept any installed one
if ( $available_file
and ( # a few quick shortcurcuits
not defined $need_version
or $need_version eq '0' # "==" would trigger warning when not numeric
or $need_version eq "undef"
)) {
unless ($nmo->inst_deprecated) {
next NEED;
}
}
$available_version = $nmo->available_version;
}
# We only want to install prereqs if either they're not installed
# or if the installed version is too old. We cannot omit this
# check, because if 'force' is in effect, nobody else will check.
# But we don't want to accept a deprecated module installed as part
# of the Perl core, so we continue if the available file is the installed
# one and is deprecated
if ( $available_file ) {
if ( $inst_file && $available_file eq $inst_file && $nmo->inst_deprecated ) {
# continue installing as a prereq
} elsif ($self->{reqtype} =~ /^(r|c)$/ && exists $prereq_pm->{requires}{$need_module} && $nmo && !$inst_file) {
# continue installing as a prereq; this may be a
# distro we already used when it was a build_requires
# so we did not install it. But suddenly somebody
# wants it as a requires
my $need_distro = $nmo->distribution;
if ($need_distro->{install} && $need_distro->{install}->failed && $need_distro->{install}->text =~ /is only/) {
CPAN->debug("promotion from build_requires to requires") if $CPAN::DEBUG;
delete $need_distro->{install}; # promote to another installation attempt
$need_distro->{reqtype} = "r";
$need_distro->install;
next NEED;
}
}
else {
next NEED if $self->_fulfills_all_version_rqs(
$need_module,$available_file,$available_version,$need_version
);
}
}
if ($need_module eq "perl") {
return ["perl", $need_version];
}
$self->{sponsored_mods}{$need_module} ||= 0;
CPAN->debug("need_module[$need_module]s/s/n[$self->{sponsored_mods}{$need_module}]") if $CPAN::DEBUG;
if (my $sponsoring = $self->{sponsored_mods}{$need_module}++) {
# We have already sponsored it and for some reason it's still
# not available. So we do ... what??
# if we push it again, we have a potential infinite loop
# The following "next" was a very problematic construct.
# It helped a lot but broke some day and had to be
# replaced.
# We must be able to deal with modules that come again and
# again as a prereq and have themselves prereqs and the
# queue becomes long but finally we would find the correct
# order. The RecursiveDependency check should trigger a
# die when it's becoming too weird. Unfortunately removing
# this next breaks many other things.
# The bug that brought this up is described in Todo under
# "5.8.9 cannot install Compress::Zlib"
# next; # this is the next that had to go away
# The following "next NEED" are fine and the error message
# explains well what is going on. For example when the DBI
# fails and consequently DBD::SQLite fails and now we are
# processing CPAN::SQLite. Then we must have a "next" for
# DBD::SQLite. How can we get it and how can we identify
# all other cases we must identify?
my $do = $nmo->distribution;
next NEED unless $do; # not on CPAN
if (CPAN::Version->vcmp($need_version, $nmo->ro->{CPAN_VERSION}) > 0){
$CPAN::Frontend->mywarn("Warning: Prerequisite ".
"'$need_module => $need_version' ".
"for '$self->{ID}' seems ".
"not available according to the indices\n"
);
next NEED;
}
NOSAYER: for my $nosayer (
"unwrapped",
"writemakefile",
"signature_verify",
"make",
"make_test",
"install",
"make_clean",
) {
if ($do->{$nosayer}) {
my $selfid = $self->pretty_id;
my $did = $do->pretty_id;
if (UNIVERSAL::can($do->{$nosayer},"failed") ?
$do->{$nosayer}->failed :
$do->{$nosayer} =~ /^NO/) {
if ($nosayer eq "make_test"
&&
$do->{make_test}{COMMANDID} != $CPAN::CurrentCommandId
) {
next NOSAYER;
}
$CPAN::Frontend->mywarn("Warning: Prerequisite ".
"'$need_module => $need_version' ".
"for '$selfid' failed when ".
"processing '$did' with ".
"'$nosayer => $do->{$nosayer}'. Continuing, ".
"but chances to succeed are limited.\n"
);
$CPAN::Frontend->mysleep($sponsoring/10);
next NEED;
} else { # the other guy succeeded
if ($nosayer =~ /^(install|make_test)$/) {
# we had this with
# DMAKI/DateTime-Calendar-Chinese-0.05.tar.gz
# in 2007-03 for 'make install'
# and 2008-04: #30464 (for 'make test')
$CPAN::Frontend->mywarn("Warning: Prerequisite ".
"'$need_module => $need_version' ".
"for '$selfid' already built ".
"but the result looks suspicious. ".
"Skipping another build attempt, ".
"to prevent looping endlessly.\n"
);
next NEED;
}
}
}
}
}
my $needed_as;
if (0) {
} elsif (exists $prereq_pm->{requires}{$need_module}) {
$needed_as = "r";
} elsif ($slot eq "configure_requires_later") {
# in ae872487d5 we said: C< we have not yet run the
# {Build,Makefile}.PL, we must presume "r" >; but the
# meta.yml standard says C< These dependencies are not
# required after the distribution is installed. >; so now
# we change it back to "b" and care for the proper
# promotion later.
$needed_as = "b";
} else {
$needed_as = "b";
}
push @need, [$need_module,$needed_as];
}
my @unfolded = map { "[".join(",",@$_)."]" } @need;
CPAN->debug("returning from unsat_prereq[@unfolded]") if $CPAN::DEBUG;
@need;
}
sub _fulfills_all_version_rqs {
my($self,$need_module,$available_file,$available_version,$need_version) = @_;
my(@all_requirements) = split /\s*,\s*/, $need_version;
local($^W) = 0;
my $ok = 0;
RQ: for my $rq (@all_requirements) {
if ($rq =~ s|>=\s*||) {
} elsif ($rq =~ s|>\s*||) {
# 2005-12: one user
if (CPAN::Version->vgt($available_version,$rq)) {
$ok++;
}
next RQ;
} elsif ($rq =~ s|!=\s*||) {
# 2005-12: no user
if (CPAN::Version->vcmp($available_version,$rq)) {
$ok++;
next RQ;
} else {
$ok=0;
last RQ;
}
} elsif ($rq =~ m|<=?\s*|) {
# 2005-12: no user
$CPAN::Frontend->mywarn("Downgrading not supported (rq[$rq])\n");
$ok++;
next RQ;
} elsif ($rq =~ s|==\s*||) {
# 2009-07: ELLIOTJS/Perl-Critic-1.099_002.tar.gz
if (CPAN::Version->vcmp($available_version,$rq)) {
$ok=0;
last RQ;
} else {
$ok++;
next RQ;
}
}
if (! CPAN::Version->vgt($rq, $available_version)) {
$ok++;
}
CPAN->debug(sprintf("need_module[%s]available_file[%s]".
"available_version[%s]rq[%s]ok[%d]",
$need_module,
$available_file,
$available_version,
CPAN::Version->readable($rq),
$ok,
)) if $CPAN::DEBUG;
}
my $ret = $ok == @all_requirements;
CPAN->debug(sprintf("need_module[%s]ok[%s]all_requirements[%d]",$need_module, $ok, scalar @all_requirements)) if $CPAN::DEBUG;
return $ret;
}
#-> sub CPAN::Distribution::read_meta
# read any sort of meta files, return CPAN::Meta object if no errors
sub read_meta {
my($self) = @_;
my $meta_file = $self->pick_meta_file
or return;
return unless $CPAN::META->has_usable("CPAN::Meta");
my $meta = eval { CPAN::Meta->load_file($meta_file)}
or return;
# Very old EU::MM could have wrong META
if ($meta_file eq 'META.yml'
&& $meta->generated_by =~ /ExtUtils::MakeMaker version ([\d\._]+)/
) {
my $eummv = do { local $^W = 0; $1+0; };
return if $eummv < 6.2501;
}
return $meta;
}
#-> sub CPAN::Distribution::read_yaml ;
# XXX This should be DEPRECATED -- dagolden, 2011-02-05
sub read_yaml {
my($self) = @_;
my $meta_file = $self->pick_meta_file;
$self->debug("meta_file[$meta_file]") if $CPAN::DEBUG;
return unless $meta_file;
my $yaml;
eval { $yaml = $self->parse_meta_yml($meta_file) };
if ($@ or ! $yaml) {
return undef; # if we die, then we cannot read YAML's own META.yml
}
# not "authoritative"
if (defined $yaml && (! ref $yaml || ref $yaml ne "HASH")) {
$CPAN::Frontend->mywarn("META.yml does not seem to be conforming, cannot use it.\n");
$yaml = undef;
}
$self->debug(sprintf "yaml[%s]", $yaml || "UNDEF")
if $CPAN::DEBUG;
$self->debug($yaml) if $CPAN::DEBUG && $yaml;
# MYMETA.yml is static and authoritative by definition
if ( $meta_file =~ /MYMETA\.yml/ ) {
return $yaml;
}
# META.yml is authoritative only if dynamic_config is defined and false
if ( defined $yaml->{dynamic_config} && ! $yaml->{dynamic_config} ) {
return $yaml;
}
# otherwise, we can't use what we found
return undef;
}
#-> sub CPAN::Distribution::configure_requires ;
sub configure_requires {
my($self) = @_;
return unless my $meta_file = $self->pick_meta_file('^META');
if (my $meta_obj = $self->read_meta) {
my $prereqs = $meta_obj->effective_prereqs;
my $cr = $prereqs->requirements_for(qw/configure requires/);
return $cr ? $cr->as_string_hash : undef;
}
else {
my $yaml = eval { $self->parse_meta_yml($meta_file) };
return $yaml->{configure_requires};
}
}
#-> sub CPAN::Distribution::prereq_pm ;
sub prereq_pm {
my($self) = @_;
return unless $self->{writemakefile} # no need to have succeeded
# but we must have run it
|| $self->{modulebuild};
unless ($self->{build_dir}) {
return;
}
CPAN->debug(sprintf "writemakefile[%s]modulebuild[%s]",
$self->{writemakefile}||"",
$self->{modulebuild}||"",
) if $CPAN::DEBUG;
my($req,$breq);
my $meta_obj = $self->read_meta;
# META/MYMETA is only authoritative if dynamic_config is false
if ($meta_obj && ! $meta_obj->dynamic_config) {
my $prereqs = $meta_obj->effective_prereqs;
my $requires = $prereqs->requirements_for(qw/runtime requires/);
my $build_requires = $prereqs->requirements_for(qw/build requires/);
my $test_requires = $prereqs->requirements_for(qw/test requires/);
# XXX we don't yet distinguish build vs test, so merge them for now
$build_requires->add_requirements($test_requires);
$req = $requires->as_string_hash;
$breq = $build_requires->as_string_hash;
}
elsif (my $yaml = $self->read_yaml) { # often dynamic_config prevents a result here
$req = $yaml->{requires} || {};
$breq = $yaml->{build_requires} || {};
undef $req unless ref $req eq "HASH" && %$req;
if ($req) {
if ($yaml->{generated_by} &&
$yaml->{generated_by} =~ /ExtUtils::MakeMaker version ([\d\._]+)/) {
my $eummv = do { local $^W = 0; $1+0; };
if ($eummv < 6.2501) {
# thanks to Slaven for digging that out: MM before
# that could be wrong because it could reflect a
# previous release
undef $req;
}
}
my $areq;
my $do_replace;
while (my($k,$v) = each %{$req||{}}) {
next unless defined $v;
if ($v =~ /\d/) {
$areq->{$k} = $v;
} elsif ($k =~ /[A-Za-z]/ &&
$v =~ /[A-Za-z]/ &&
$CPAN::META->exists("CPAN::Module",$v)
) {
$CPAN::Frontend->mywarn("Suspicious key-value pair in META.yml's ".
"requires hash: $k => $v; I'll take both ".
"key and value as a module name\n");
$CPAN::Frontend->mysleep(1);
$areq->{$k} = 0;
$areq->{$v} = 0;
$do_replace++;
}
}
$req = $areq if $do_replace;
}
}
else {
$CPAN::Frontend->mywarnonce("Could not read metadata file. Falling back to other ".
"methods to determine prerequisites\n");
}
unless ($req || $breq) {
my $build_dir;
unless ( $build_dir = $self->{build_dir} ) {
return;
}
my $makefile = File::Spec->catfile($build_dir,"Makefile");
my $fh;
if (-f $makefile
and
$fh = FileHandle->new("<$makefile\0")) {
CPAN->debug("Getting prereq from Makefile") if $CPAN::DEBUG;
local($/) = "\n";
while (<$fh>) {
last if /MakeMaker post_initialize section/;
my($p) = m{^[\#]
\s+PREREQ_PM\s+=>\s+(.+)
}x;
next unless $p;
# warn "Found prereq expr[$p]";
# Regexp modified by A.Speer to remember actual version of file
# PREREQ_PM hash key wants, then add to
while ( $p =~ m/(?:\s)([\w\:]+)=>(q\[.*?\]|undef),?/g ) {
my($m,$n) = ($1,$2);
# When a prereq is mentioned twice: let the bigger
# win; usual culprit is that they declared
# build_requires separately from requires; see
# rt.cpan.org #47774
my($prevn);
if ( defined $req->{$m} ) {
$prevn = $req->{$m};
}
if ($n =~ /^q\[(.*?)\]$/) {
$n = $1;
}
if (!$prevn || CPAN::Version->vlt($prevn, $n)){
$req->{$m} = $n;
}
}
last;
}
}
}
unless ($req || $breq) {
my $build_dir = $self->{build_dir} or die "Panic: no build_dir?";
my $buildfile = File::Spec->catfile($build_dir,"Build");
if (-f $buildfile) {
CPAN->debug("Found '$buildfile'") if $CPAN::DEBUG;
my $build_prereqs = File::Spec->catfile($build_dir,"_build","prereqs");
if (-f $build_prereqs) {
CPAN->debug("Getting prerequisites from '$build_prereqs'") if $CPAN::DEBUG;
my $content = do { local *FH;
open FH, $build_prereqs
or $CPAN::Frontend->mydie("Could not open ".
"'$build_prereqs': $!");
local $/;
<FH>;
};
my $bphash = eval $content;
if ($@) {
} else {
$req = $bphash->{requires} || +{};
$breq = $bphash->{build_requires} || +{};
}
}
}
}
if ($req || $breq) {
return $self->{prereq_pm} = { requires => $req, build_requires => $breq };
}
}
#-> sub CPAN::Distribution::test ;
sub test {
my($self) = @_;
if (my $goto = $self->prefs->{goto}) {
return $self->goto($goto);
}
$self->make;
return if $self->prefs->{disabled} && ! $self->{force_update};
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
# warn "XDEBUG: checking for notest: $self->{notest} $self";
if ($self->{notest}) {
$CPAN::Frontend->myprint("Skipping test because of notest pragma\n");
return 1;
}
my $make = $self->{modulebuild} ? "Build" : "make";
local $ENV{PERL5LIB} = defined($ENV{PERL5LIB})
? $ENV{PERL5LIB}
: ($ENV{PERLLIB} || "");
local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : "";
$CPAN::META->set_perl5lib;
local $ENV{MAKEFLAGS}; # protect us from outer make calls
$CPAN::Frontend->myprint("Running $make test\n");
EXCUSE: {
my @e;
if ($self->{make} or $self->{later}) {
# go ahead
} else {
push @e,
"Make had some problems, won't test";
}
exists $self->{make} and
(
UNIVERSAL::can($self->{make},"failed") ?
$self->{make}->failed :
$self->{make} =~ /^NO/
) and push @e, "Can't test without successful make";
$self->{badtestcnt} ||= 0;
if ($self->{badtestcnt} > 0) {
require Data::Dumper;
CPAN->debug(sprintf "NOREPEAT[%s]", Data::Dumper::Dumper($self)) if $CPAN::DEBUG;
push @e, "Won't repeat unsuccessful test during this command";
}
push @e, $self->{later} if $self->{later};
push @e, $self->{configure_requires_later} if $self->{configure_requires_later};
if (exists $self->{build_dir}) {
if (exists $self->{make_test}) {
if (
UNIVERSAL::can($self->{make_test},"failed") ?
$self->{make_test}->failed :
$self->{make_test} =~ /^NO/
) {
if (
UNIVERSAL::can($self->{make_test},"commandid")
&&
$self->{make_test}->commandid == $CPAN::CurrentCommandId
) {
push @e, "Has already been tested within this command";
}
} else {
push @e, "Has already been tested successfully";
# if global "is_tested" has been cleared, we need to mark this to
# be added to PERL5LIB if not already installed
if ($self->tested_ok_but_not_installed) {
$CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME});
}
}
}
} elsif (!@e) {
push @e, "Has no own directory";
}
$CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e;
unless (chdir $self->{build_dir}) {
push @e, "Couldn't chdir to '$self->{build_dir}': $!";
}
$CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e;
}
$self->debug("Changed directory to $self->{build_dir}")
if $CPAN::DEBUG;
if ($^O eq 'MacOS') {
Mac::BuildTools::make_test($self);
return;
}
if ($self->{modulebuild}) {
my $thm = CPAN::Shell->expand("Module","Test::Harness");
my $v = $thm->inst_version;
if (CPAN::Version->vlt($v,2.62)) {
# XXX Eric Wilhelm reported this as a bug: klapperl:
# Test::Harness 3.0 self-tests, so that should be 'unless
# installing Test::Harness'
unless ($self->id eq $thm->distribution->id) {
$CPAN::Frontend->mywarn(qq{The version of your Test::Harness is only
'$v', you need at least '2.62'. Please upgrade your Test::Harness.\n});
$self->{make_test} = CPAN::Distrostatus->new("NO Test::Harness too old");
return;
}
}
}
if ( ! $self->{force_update} ) {
# bypass actual tests if "trust_test_report_history" and have a report
my $have_tested_fcn;
if ( $CPAN::Config->{trust_test_report_history}
&& $CPAN::META->has_inst("CPAN::Reporter::History")
&& ( $have_tested_fcn = CPAN::Reporter::History->can("have_tested" ))) {
if ( my @reports = $have_tested_fcn->( dist => $self->base_id ) ) {
# Do nothing if grade was DISCARD
if ( $reports[-1]->{grade} =~ /^(?:PASS|UNKNOWN)$/ ) {
$self->{make_test} = CPAN::Distrostatus->new("YES");
# if global "is_tested" has been cleared, we need to mark this to
# be added to PERL5LIB if not already installed
if ($self->tested_ok_but_not_installed) {
$CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME});
}
$CPAN::Frontend->myprint("Found prior test report -- OK\n");
return;
}
elsif ( $reports[-1]->{grade} =~ /^(?:FAIL|NA)$/ ) {
$self->{make_test} = CPAN::Distrostatus->new("NO");
$self->{badtestcnt}++;
$CPAN::Frontend->mywarn("Found prior test report -- NOT OK\n");
return;
}
}
}
}
my $system;
my $prefs_test = $self->prefs->{test};
if (my $commandline
= exists $prefs_test->{commandline} ? $prefs_test->{commandline} : "") {
$system = $commandline;
$ENV{PERL} = CPAN::find_perl();
} elsif ($self->{modulebuild}) {
$system = sprintf "%s test", $self->_build_command();
unless (-e "Build") {
my $id = $self->pretty_id;
$CPAN::Frontend->mywarn("Alert: no 'Build' file found while trying to test '$id'");
}
} else {
$system = join " ", $self->_make_command(), "test";
}
my $make_test_arg = $self->_make_phase_arg("test");
$system = sprintf("%s%s",
$system,
$make_test_arg ? " $make_test_arg" : "",
);
my($tests_ok);
my %env;
while (my($k,$v) = each %ENV) {
next unless defined $v;
$env{$k} = $v;
}
local %ENV = %env;
my $test_env;
if ($self->prefs->{test}) {
$test_env = $self->prefs->{test}{env};
}
if ($test_env) {
for my $e (keys %$test_env) {
$ENV{$e} = $test_env->{$e};
}
}
my $expect_model = $self->_prefs_with_expect("test");
my $want_expect = 0;
if ( $expect_model && @{$expect_model->{talk}} ) {
my $can_expect = $CPAN::META->has_inst("Expect");
if ($can_expect) {
$want_expect = 1;
} else {
$CPAN::Frontend->mywarn("Expect not installed, falling back to ".
"testing without\n");
}
}
if ($want_expect) {
if ($self->_should_report('test')) {
$CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is currently ".
"not supported when distroprefs specify ".
"an interactive test\n");
}
$tests_ok = $self->_run_via_expect($system,'test',$expect_model) == 0;
} elsif ( $self->_should_report('test') ) {
$tests_ok = CPAN::Reporter::test($self, $system);
} else {
$tests_ok = system($system) == 0;
}
$self->introduce_myself;
my $but = $self->_make_test_illuminate_prereqs();
if ( $tests_ok ) {
if ($but) {
$CPAN::Frontend->mywarn("Tests succeeded but $but\n");
$self->{make_test} = CPAN::Distrostatus->new("NO $but");
$self->store_persistent_state;
return $self->goodbye("[dependencies] -- NA");
}
$CPAN::Frontend->myprint(" $system -- OK\n");
$self->{make_test} = CPAN::Distrostatus->new("YES");
$CPAN::META->is_tested($self->{build_dir},$self->{make_test}{TIME});
# probably impossible to need the next line because badtestcnt
# has a lifespan of one command
delete $self->{badtestcnt};
} else {
if ($but) {
$but .= "; additionally test harness failed";
$CPAN::Frontend->mywarn("$but\n");
$self->{make_test} = CPAN::Distrostatus->new("NO $but");
} else {
$self->{make_test} = CPAN::Distrostatus->new("NO");
}
$self->{badtestcnt}++;
$CPAN::Frontend->mywarn(" $system -- NOT OK\n");
CPAN::Shell->optprint
("hint",
sprintf
("//hint// to see the cpan-testers results for installing this module, try:
reports %s\n",
$self->pretty_id));
}
$self->store_persistent_state;
}
sub _make_test_illuminate_prereqs {
my($self) = @_;
my @prereq;
# local $CPAN::DEBUG = 16; # Distribution
for my $m (keys %{$self->{sponsored_mods}}) {
next unless $self->{sponsored_mods}{$m} > 0;
my $m_obj = CPAN::Shell->expand("Module",$m) or next;
# XXX we need available_version which reflects
# $ENV{PERL5LIB} so that already tested but not yet
# installed modules are counted.
my $available_version = $m_obj->available_version;
my $available_file = $m_obj->available_file;
if ($available_version &&
!CPAN::Version->vlt($available_version,$self->{prereq_pm}{$m})
) {
CPAN->debug("m[$m] good enough available_version[$available_version]")
if $CPAN::DEBUG;
} elsif ($available_file
&& (
!$self->{prereq_pm}{$m}
||
$self->{prereq_pm}{$m} == 0
)
) {
# lex Class::Accessor::Chained::Fast which has no $VERSION
CPAN->debug("m[$m] have available_file[$available_file]")
if $CPAN::DEBUG;
} else {
push @prereq, $m;
}
}
my $but;
if (@prereq) {
my $cnt = @prereq;
my $which = join ",", @prereq;
$but = $cnt == 1 ? "one dependency not OK ($which)" :
"$cnt dependencies missing ($which)";
}
$but;
}
sub _prefs_with_expect {
my($self,$where) = @_;
return unless my $prefs = $self->prefs;
return unless my $where_prefs = $prefs->{$where};
if ($where_prefs->{expect}) {
return {
mode => "deterministic",
timeout => 15,
talk => $where_prefs->{expect},
};
} elsif ($where_prefs->{"eexpect"}) {
return $where_prefs->{"eexpect"};
}
return;
}
#-> sub CPAN::Distribution::clean ;
sub clean {
my($self) = @_;
my $make = $self->{modulebuild} ? "Build" : "make";
$CPAN::Frontend->myprint("Running $make clean\n");
unless (exists $self->{archived}) {
$CPAN::Frontend->mywarn("Distribution seems to have never been unzipped".
"/untarred, nothing done\n");
return 1;
}
unless (exists $self->{build_dir}) {
$CPAN::Frontend->mywarn("Distribution has no own directory, nothing to do.\n");
return 1;
}
if (exists $self->{writemakefile}
and $self->{writemakefile}->failed
) {
$CPAN::Frontend->mywarn("No Makefile, don't know how to 'make clean'\n");
return 1;
}
EXCUSE: {
my @e;
exists $self->{make_clean} and $self->{make_clean} eq "YES" and
push @e, "make clean already called once";
$CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e;
}
chdir $self->{build_dir} or
Carp::confess("Couldn't chdir to $self->{build_dir}: $!");
$self->debug("Changed directory to $self->{build_dir}") if $CPAN::DEBUG;
if ($^O eq 'MacOS') {
Mac::BuildTools::make_clean($self);
return;
}
my $system;
if ($self->{modulebuild}) {
unless (-f "Build") {
my $cwd = CPAN::anycwd();
$CPAN::Frontend->mywarn("Alert: no Build file available for 'clean $self->{id}".
" in cwd[$cwd]. Danger, Will Robinson!");
$CPAN::Frontend->mysleep(5);
}
$system = sprintf "%s clean", $self->_build_command();
} else {
$system = join " ", $self->_make_command(), "clean";
}
my $system_ok = system($system) == 0;
$self->introduce_myself;
if ( $system_ok ) {
$CPAN::Frontend->myprint(" $system -- OK\n");
# $self->force;
# Jost Krieger pointed out that this "force" was wrong because
# it has the effect that the next "install" on this distribution
# will untar everything again. Instead we should bring the
# object's state back to where it is after untarring.
for my $k (qw(
force_update
install
writemakefile
make
make_test
)) {
delete $self->{$k};
}
$self->{make_clean} = CPAN::Distrostatus->new("YES");
} else {
# Hmmm, what to do if make clean failed?
$self->{make_clean} = CPAN::Distrostatus->new("NO");
$CPAN::Frontend->mywarn(qq{ $system -- NOT OK\n});
# 2006-02-27: seems silly to me to force a make now
# $self->force("make"); # so that this directory won't be used again
}
$self->store_persistent_state;
}
#-> sub CPAN::Distribution::goto ;
sub goto {
my($self,$goto) = @_;
$goto = $self->normalize($goto);
my $why = sprintf(
"Goto '$goto' via prefs file '%s' doc %d",
$self->{prefs_file},
$self->{prefs_file_doc},
);
$self->{unwrapped} = CPAN::Distrostatus->new("NO $why");
# 2007-07-16 akoenig : Better than NA would be if we could inherit
# the status of the $goto distro but given the exceptional nature
# of 'goto' I feel reluctant to implement it
my $goodbye_message = "[goto] -- NA $why";
$self->goodbye($goodbye_message);
# inject into the queue
CPAN::Queue->delete($self->id);
CPAN::Queue->jumpqueue({qmod => $goto, reqtype => $self->{reqtype}});
# and run where we left off
my($method) = (caller(1))[3];
CPAN->instance("CPAN::Distribution",$goto)->$method();
CPAN::Queue->delete_first($goto);
}
#-> sub CPAN::Distribution::install ;
sub install {
my($self) = @_;
if (my $goto = $self->prefs->{goto}) {
return $self->goto($goto);
}
unless ($self->{badtestcnt}) {
$self->test;
}
if ($CPAN::Signal) {
delete $self->{force_update};
return;
}
my $make = $self->{modulebuild} ? "Build" : "make";
$CPAN::Frontend->myprint("Running $make install\n");
EXCUSE: {
my @e;
if ($self->{make} or $self->{later}) {
# go ahead
} else {
push @e,
"Make had some problems, won't install";
}
exists $self->{make} and
(
UNIVERSAL::can($self->{make},"failed") ?
$self->{make}->failed :
$self->{make} =~ /^NO/
) and
push @e, "Make had returned bad status, install seems impossible";
if (exists $self->{build_dir}) {
} elsif (!@e) {
push @e, "Has no own directory";
}
if (exists $self->{make_test} and
(
UNIVERSAL::can($self->{make_test},"failed") ?
$self->{make_test}->failed :
$self->{make_test} =~ /^NO/
)) {
if ($self->{force_update}) {
$self->{make_test}->text("FAILED but failure ignored because ".
"'force' in effect");
} else {
push @e, "make test had returned bad status, ".
"won't install without force"
}
}
if (exists $self->{install}) {
my $text = UNIVERSAL::can($self->{install},"text") ?
$self->{install}->text :
$self->{install};
if ($text =~ /^YES/) {
$CPAN::Frontend->myprint(" Already done\n");
$CPAN::META->is_installed($self->{build_dir});
return 1;
} elsif ($text =~ /is only/) {
push @e, $text;
} else {
# comment in Todo on 2006-02-11; maybe retry?
push @e, "Already tried without success";
}
}
push @e, $self->{later} if $self->{later};
push @e, $self->{configure_requires_later} if $self->{configure_requires_later};
$CPAN::Frontend->myprint(join "", map {" $_\n"} @e) and return if @e;
unless (chdir $self->{build_dir}) {
push @e, "Couldn't chdir to '$self->{build_dir}': $!";
}
$CPAN::Frontend->mywarn(join "", map {" $_\n"} @e) and return if @e;
}
$self->debug("Changed directory to $self->{build_dir}")
if $CPAN::DEBUG;
if ($^O eq 'MacOS') {
Mac::BuildTools::make_install($self);
return;
}
my $system;
if (my $commandline = $self->prefs->{install}{commandline}) {
$system = $commandline;
$ENV{PERL} = CPAN::find_perl();
} elsif ($self->{modulebuild}) {
my($mbuild_install_build_command) =
exists $CPAN::HandleConfig::keys{mbuild_install_build_command} &&
$CPAN::Config->{mbuild_install_build_command} ?
$CPAN::Config->{mbuild_install_build_command} :
$self->_build_command();
$system = sprintf("%s install %s",
$mbuild_install_build_command,
$CPAN::Config->{mbuild_install_arg},
);
} else {
my($make_install_make_command) =
CPAN::HandleConfig->prefs_lookup($self,
q{make_install_make_command})
|| $self->_make_command();
$system = sprintf("%s install %s",
$make_install_make_command,
$CPAN::Config->{make_install_arg},
);
}
my($stderr) = $^O eq "MSWin32" ? "" : " 2>&1 ";
my $brip = CPAN::HandleConfig->prefs_lookup($self,
q{build_requires_install_policy});
$brip ||="ask/yes";
my $id = $self->id;
my $reqtype = $self->{reqtype} ||= "c"; # in doubt it was a command
my $want_install = "yes";
if ($reqtype eq "b") {
if ($brip eq "no") {
$want_install = "no";
} elsif ($brip =~ m|^ask/(.+)|) {
my $default = $1;
$default = "yes" unless $default =~ /^(y|n)/i;
$want_install =
CPAN::Shell::colorable_makemaker_prompt
("$id is just needed temporarily during building or testing. ".
"Do you want to install it permanently?",
$default);
}
}
unless ($want_install =~ /^y/i) {
my $is_only = "is only 'build_requires'";
$CPAN::Frontend->mywarn("Not installing because $is_only\n");
$self->{install} = CPAN::Distrostatus->new("NO -- $is_only");
delete $self->{force_update};
return;
}
local $ENV{PERL5LIB} = defined($ENV{PERL5LIB})
? $ENV{PERL5LIB}
: ($ENV{PERLLIB} || "");
local $ENV{PERL5OPT} = defined $ENV{PERL5OPT} ? $ENV{PERL5OPT} : "";
$CPAN::META->set_perl5lib;
my($pipe) = FileHandle->new("$system $stderr |") || Carp::croak
("Can't execute $system: $!");
my($makeout) = "";
while (<$pipe>) {
print $_; # intentionally NOT use Frontend->myprint because it
# looks irritating when we markup in color what we
# just pass through from an external program
$makeout .= $_;
}
$pipe->close;
my $close_ok = $? == 0;
$self->introduce_myself;
if ( $close_ok ) {
$CPAN::Frontend->myprint(" $system -- OK\n");
$CPAN::META->is_installed($self->{build_dir});
$self->{install} = CPAN::Distrostatus->new("YES");
} else {
$self->{install} = CPAN::Distrostatus->new("NO");
$CPAN::Frontend->mywarn(" $system -- NOT OK\n");
my $mimc =
CPAN::HandleConfig->prefs_lookup($self,
q{make_install_make_command});
if (
$makeout =~ /permission/s
&& $> > 0
&& (
! $mimc
|| $mimc eq (CPAN::HandleConfig->prefs_lookup($self,
q{make}))
)
) {
$CPAN::Frontend->myprint(
qq{----\n}.
qq{ You may have to su }.
qq{to root to install the package\n}.
qq{ (Or you may want to run something like\n}.
qq{ o conf make_install_make_command 'sudo make'\n}.
qq{ to raise your permissions.}
);
}
}
delete $self->{force_update};
$self->store_persistent_state;
}
sub introduce_myself {
my($self) = @_;
$CPAN::Frontend->myprint(sprintf(" %s\n",$self->pretty_id));
}
#-> sub CPAN::Distribution::dir ;
sub dir {
shift->{build_dir};
}
#-> sub CPAN::Distribution::perldoc ;
sub perldoc {
my($self) = @_;
my($dist) = $self->id;
my $package = $self->called_for;
if ($CPAN::META->has_inst("Pod::Perldocs")) {
my($perl) = $self->perl
or $CPAN::Frontend->mydie("Couldn't find executable perl\n");
my @args = ($perl, q{-MPod::Perldocs}, q{-e},
q{Pod::Perldocs->run()}, $package);
my($wstatus);
unless ( ($wstatus = system(@args)) == 0 ) {
my $estatus = $wstatus >> 8;
$CPAN::Frontend->myprint(qq{
Function system("@args")
returned status $estatus (wstat $wstatus)
});
}
}
else {
$self->_display_url( $CPAN::Defaultdocs . $package );
}
}
#-> sub CPAN::Distribution::_check_binary ;
sub _check_binary {
my ($dist,$shell,$binary) = @_;
my ($pid,$out);
$CPAN::Frontend->myprint(qq{ + _check_binary($binary)\n})
if $CPAN::DEBUG;
if ($CPAN::META->has_inst("File::Which")) {
return File::Which::which($binary);
} else {
local *README;
$pid = open README, "which $binary|"
or $CPAN::Frontend->mywarn(qq{Could not fork 'which $binary': $!\n});
return unless $pid;
while (<README>) {
$out .= $_;
}
close README
or $CPAN::Frontend->mywarn("Could not run 'which $binary': $!\n")
and return;
}
$CPAN::Frontend->myprint(qq{ + $out \n})
if $CPAN::DEBUG && $out;
return $out;
}
#-> sub CPAN::Distribution::_display_url ;
sub _display_url {
my($self,$url) = @_;
my($res,$saved_file,$pid,$out);
$CPAN::Frontend->myprint(qq{ + _display_url($url)\n})
if $CPAN::DEBUG;
# should we define it in the config instead?
my $html_converter = "html2text.pl";
my $web_browser = $CPAN::Config->{'lynx'} || undef;
my $web_browser_out = $web_browser
? CPAN::Distribution->_check_binary($self,$web_browser)
: undef;
if ($web_browser_out) {
# web browser found, run the action
my $browser = CPAN::HandleConfig->safe_quote($CPAN::Config->{'lynx'});
$CPAN::Frontend->myprint(qq{system[$browser $url]})
if $CPAN::DEBUG;
$CPAN::Frontend->myprint(qq{
Displaying URL
$url
with browser $browser
});
$CPAN::Frontend->mysleep(1);
system("$browser $url");
if ($saved_file) { 1 while unlink($saved_file) }
} else {
# web browser not found, let's try text only
my $html_converter_out =
CPAN::Distribution->_check_binary($self,$html_converter);
$html_converter_out = CPAN::HandleConfig->safe_quote($html_converter_out);
if ($html_converter_out ) {
# html2text found, run it
$saved_file = CPAN::Distribution->_getsave_url( $self, $url );
$CPAN::Frontend->mydie(qq{ERROR: problems while getting $url\n})
unless defined($saved_file);
local *README;
$pid = open README, "$html_converter $saved_file |"
or $CPAN::Frontend->mydie(qq{
Could not fork '$html_converter $saved_file': $!});
my($fh,$filename);
if ($CPAN::META->has_usable("File::Temp")) {
$fh = File::Temp->new(
dir => File::Spec->tmpdir,
template => 'cpan_htmlconvert_XXXX',
suffix => '.txt',
unlink => 0,
);
$filename = $fh->filename;
} else {
$filename = "cpan_htmlconvert_$$.txt";
$fh = FileHandle->new();
open $fh, ">$filename" or die;
}
while (<README>) {
$fh->print($_);
}
close README or
$CPAN::Frontend->mydie(qq{Could not run '$html_converter $saved_file': $!});
my $tmpin = $fh->filename;
$CPAN::Frontend->myprint(sprintf(qq{
Run '%s %s' and
saved output to %s\n},
$html_converter,
$saved_file,
$tmpin,
)) if $CPAN::DEBUG;
close $fh;
local *FH;
open FH, $tmpin
or $CPAN::Frontend->mydie(qq{Could not open "$tmpin": $!});
my $fh_pager = FileHandle->new;
local($SIG{PIPE}) = "IGNORE";
my $pager = $CPAN::Config->{'pager'} || "cat";
$fh_pager->open("|$pager")
or $CPAN::Frontend->mydie(qq{
Could not open pager '$pager': $!});
$CPAN::Frontend->myprint(qq{
Displaying URL
$url
with pager "$pager"
});
$CPAN::Frontend->mysleep(1);
$fh_pager->print(<FH>);
$fh_pager->close;
} else {
# coldn't find the web browser or html converter
$CPAN::Frontend->myprint(qq{
You need to install lynx or $html_converter to use this feature.});
}
}
}
#-> sub CPAN::Distribution::_getsave_url ;
sub _getsave_url {
my($dist, $shell, $url) = @_;
$CPAN::Frontend->myprint(qq{ + _getsave_url($url)\n})
if $CPAN::DEBUG;
my($fh,$filename);
if ($CPAN::META->has_usable("File::Temp")) {
$fh = File::Temp->new(
dir => File::Spec->tmpdir,
template => "cpan_getsave_url_XXXX",
suffix => ".html",
unlink => 0,
);
$filename = $fh->filename;
} else {
$fh = FileHandle->new;
$filename = "cpan_getsave_url_$$.html";
}
my $tmpin = $filename;
if ($CPAN::META->has_usable('LWP')) {
$CPAN::Frontend->myprint("Fetching with LWP:
$url
");
my $Ua;
CPAN::LWP::UserAgent->config;
eval { $Ua = CPAN::LWP::UserAgent->new; };
if ($@) {
$CPAN::Frontend->mywarn("ERROR: CPAN::LWP::UserAgent->new dies with $@\n");
return;
} else {
my($var);
$Ua->proxy('http', $var)
if $var = $CPAN::Config->{http_proxy} || $ENV{http_proxy};
$Ua->no_proxy($var)
if $var = $CPAN::Config->{no_proxy} || $ENV{no_proxy};
}
my $req = HTTP::Request->new(GET => $url);
$req->header('Accept' => 'text/html');
my $res = $Ua->request($req);
if ($res->is_success) {
$CPAN::Frontend->myprint(" + request successful.\n")
if $CPAN::DEBUG;
print $fh $res->content;
close $fh;
$CPAN::Frontend->myprint(qq{ + saved content to $tmpin \n})
if $CPAN::DEBUG;
return $tmpin;
} else {
$CPAN::Frontend->myprint(sprintf(
"LWP failed with code[%s], message[%s]\n",
$res->code,
$res->message,
));
return;
}
} else {
$CPAN::Frontend->mywarn(" LWP not available\n");
return;
}
}
#-> sub CPAN::Distribution::_build_command
sub _build_command {
my($self) = @_;
if ($^O eq "MSWin32") { # special code needed at least up to
# Module::Build 0.2611 and 0.2706; a fix
# in M:B has been promised 2006-01-30
my($perl) = $self->perl or $CPAN::Frontend->mydie("Couldn't find executable perl\n");
return "$perl ./Build";
}
return "./Build";
}
#-> sub CPAN::Distribution::_should_report
sub _should_report {
my($self, $phase) = @_;
die "_should_report() requires a 'phase' argument"
if ! defined $phase;
# configured
my $test_report = CPAN::HandleConfig->prefs_lookup($self,
q{test_report});
return unless $test_report;
# don't repeat if we cached a result
return $self->{should_report}
if exists $self->{should_report};
# don't report if we generated a Makefile.PL
if ( $self->{had_no_makefile_pl} ) {
$CPAN::Frontend->mywarn(
"Will not send CPAN Testers report with generated Makefile.PL.\n"
);
return $self->{should_report} = 0;
}
# available
if ( ! $CPAN::META->has_inst("CPAN::Reporter")) {
$CPAN::Frontend->mywarnonce(
"CPAN::Reporter not installed. No reports will be sent.\n"
);
return $self->{should_report} = 0;
}
# capable
my $crv = CPAN::Reporter->VERSION;
if ( CPAN::Version->vlt( $crv, 0.99 ) ) {
# don't cache $self->{should_report} -- need to check each phase
if ( $phase eq 'test' ) {
return 1;
}
else {
$CPAN::Frontend->mywarn(
"Reporting on the '$phase' phase requires CPAN::Reporter 0.99, but \n" .
"you only have version $crv\. Only 'test' phase reports will be sent.\n"
);
return;
}
}
# appropriate
if ($self->is_dot_dist) {
$CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ".
"for local directories\n");
return $self->{should_report} = 0;
}
if ($self->prefs->{patches}
&&
@{$self->prefs->{patches}}
&&
$self->{patched}
) {
$CPAN::Frontend->mywarn("Reporting via CPAN::Reporter is disabled ".
"when the source has been patched\n");
return $self->{should_report} = 0;
}
# proceed and cache success
return $self->{should_report} = 1;
}
#-> sub CPAN::Distribution::reports
sub reports {
my($self) = @_;
my $pathname = $self->id;
$CPAN::Frontend->myprint("Distribution: $pathname\n");
unless ($CPAN::META->has_inst("CPAN::DistnameInfo")) {
$CPAN::Frontend->mydie("CPAN::DistnameInfo not installed; cannot continue");
}
unless ($CPAN::META->has_usable("LWP")) {
$CPAN::Frontend->mydie("LWP not installed; cannot continue");
}
unless ($CPAN::META->has_usable("File::Temp")) {
$CPAN::Frontend->mydie("File::Temp not installed; cannot continue");
}
my $d = CPAN::DistnameInfo->new($pathname);
my $dist = $d->dist; # "CPAN-DistnameInfo"
my $version = $d->version; # "0.02"
my $maturity = $d->maturity; # "released"
my $filename = $d->filename; # "CPAN-DistnameInfo-0.02.tar.gz"
my $cpanid = $d->cpanid; # "GBARR"
my $distvname = $d->distvname; # "CPAN-DistnameInfo-0.02"
my $url = sprintf "http://www.cpantesters.org/show/%s.yaml", $dist;
CPAN::LWP::UserAgent->config;
my $Ua;
eval { $Ua = CPAN::LWP::UserAgent->new; };
if ($@) {
$CPAN::Frontend->mydie("CPAN::LWP::UserAgent->new dies with $@\n");
}
$CPAN::Frontend->myprint("Fetching '$url'...");
my $resp = $Ua->get($url);
unless ($resp->is_success) {
$CPAN::Frontend->mydie(sprintf "Could not download '%s': %s\n", $url, $resp->code);
}
$CPAN::Frontend->myprint("DONE\n\n");
my $yaml = $resp->content;
# was fuer ein Umweg!
my $fh = File::Temp->new(
dir => File::Spec->tmpdir,
template => 'cpan_reports_XXXX',
suffix => '.yaml',
unlink => 0,
);
my $tfilename = $fh->filename;
print $fh $yaml;
close $fh or $CPAN::Frontend->mydie("Could not close '$tfilename': $!");
my $unserialized = CPAN->_yaml_loadfile($tfilename)->[0];
unlink $tfilename or $CPAN::Frontend->mydie("Could not unlink '$tfilename': $!");
my %other_versions;
my $this_version_seen;
for my $rep (@$unserialized) {
my $rversion = $rep->{version};
if ($rversion eq $version) {
unless ($this_version_seen++) {
$CPAN::Frontend->myprint ("$rep->{version}:\n");
}
my $arch = $rep->{archname} || $rep->{platform} || '????';
my $grade = $rep->{action} || $rep->{status} || '????';
my $ostext = $rep->{ostext} || ucfirst($rep->{osname}) || '????';
$CPAN::Frontend->myprint
(sprintf("%1s%1s%-4s %s on %s %s (%s)\n",
$arch eq $Config::Config{archname}?"*":"",
$grade eq "PASS"?"+":$grade eq"FAIL"?"-":"",
$grade,
$rep->{perl},
$ostext,
$rep->{osvers},
$arch,
));
} else {
$other_versions{$rep->{version}}++;
}
}
unless ($this_version_seen) {
$CPAN::Frontend->myprint("No reports found for version '$version'
Reports for other versions:\n");
for my $v (sort keys %other_versions) {
$CPAN::Frontend->myprint(" $v\: $other_versions{$v}\n");
}
}
$url =~ s/\.yaml/.html/;
$CPAN::Frontend->myprint("See $url for details\n");
}
1;
| Dokaponteam/ITF_Project | xampp/perl/lib/CPAN/Distribution.pm | Perl | mit | 148,573 |
package OIDC::Lite::Server::GrantHandlers;
use strict;
use warnings;
use OIDC::Lite::Server::GrantHandler::AuthorizationCode;
use OAuth::Lite2::Server::GrantHandler::Password;
use OAuth::Lite2::Server::GrantHandler::RefreshToken;
use OAuth::Lite2::Server::GrantHandler::ClientCredentials;
use OAuth::Lite2::Server::GrantHandler::GroupingRefreshToken;
use OAuth::Lite2::Server::GrantHandler::ServerState;
my %HANDLERS;
sub add_handler {
my ($class, $type, $handler) = @_;
$HANDLERS{$type} = $handler;
}
__PACKAGE__->add_handler( 'authorization_code' =>
OIDC::Lite::Server::GrantHandler::AuthorizationCode->new );
__PACKAGE__->add_handler( 'password' =>
OAuth::Lite2::Server::GrantHandler::Password->new );
__PACKAGE__->add_handler( 'refresh_token' =>
OAuth::Lite2::Server::GrantHandler::RefreshToken->new );
__PACKAGE__->add_handler( 'client_credentials' =>
OAuth::Lite2::Server::GrantHandler::ClientCredentials->new );
# Grant types which is not defined in RFC
__PACKAGE__->add_handler( 'grouping_refresh_token' =>
OAuth::Lite2::Server::GrantHandler::GroupingRefreshToken->new );
__PACKAGE__->add_handler( 'server_state' =>
OAuth::Lite2::Server::GrantHandler::ServerState->new );
__PACKAGE__->add_handler( 'external_service' =>
OAuth::Lite2::Server::GrantHandler::ExternalService->new );
#__PACKAGE__->add_handler( 'assertion' => );
#__PACKAGE__->add_handler( 'none' => );
sub get_handler {
my ($class, $type) = @_;
return $HANDLERS{$type};
}
=head1 NAME
OIDC::Lite::Server::GrantHandlers - store of handlers for each grant_type.
=head1 SYNOPSIS
my $handler = OIDC::Lite::Server::GrantHandlers->get_handler( $grant_type );
$handler->handle_request( $ctx );
=head1 DESCRIPTION
store of handlers for each grant_type.
=head1 METHODS
=head2 add_handler( $grant_type, $handler )
add GrantHandler instance
=head2 get_handler( $grant_type )
get GrantHandler instance
=head1 SEE ALSO
L<OIDC::Lite::Server::GrantHandler>
L<OIDC::Lite::Server::GrantHandler::AuthorizationCode>
L<OAuth::Lite2::Server::GrantHandler::ClientCredentials>
L<OAuth::Lite2::Server::GrantHandler::Password>
L<OAuth::Lite2::Server::GrantHandler::RefreshToken>
L<OAuth::Lite2::Server::GrantHandler::GroupingRefreshToken>
L<OAuth::Lite2::Server::GrantHandler::ServerState>
=head1 AUTHOR
Ryo Ito, E<lt>ritou.06@gmail.comE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2012 by Ryo Ito
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
| movabletype/mt-plugin-google-openid-connect | plugins/GoogleOpenIDConnect/extlib/OIDC/Lite/Server/GrantHandlers.pm | Perl | mit | 2,640 |
remove([H | T], H, T).
remove([H | T], E, [H | Tr]) :-
H =\= E,
remove(T, E, Tr).
eqset([], []).
eqset([H1 | T1], X) :-
remove(X, H1, Y),
eqset(T1, Y).
getNth([H | _], 1, H).
getNth([_ | T], N, X) :-
N > 1,
N1 is N - 1,
getNth(T, N1, X).
| rusucosmin/courses | ubb/plf/P1/14.pl | Perl | mit | 271 |
#!/usr/bin/perl -w
# Copyright 2001, 20002 Rob Edwards
# For updates, more information, or to discuss the scripts
# please contact Rob Edwards at redwards@utmem.edu or via http://www.salmonella.org/
#
# This file is part of The Phage Proteome Scripts developed by Rob Edwards.
#
# Tnese scripts are free software; you can redistribute and/or modify
# them 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.
#
# They are distributed in the hope that they 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
# in the file (COPYING) along with these scripts; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
use DBI;
use strict;
use OGD;
use constant IMAGE_WIDTH => 900;
use constant LEFT_MARGIN => 200;
my $dbh=DBI->connect("DBI:mysql:phage", "SQLUSER", "SQLPASSWORD") or die "Can't connect to database\n";
my $file= shift || &niceexit("drawtras.pl <file of prot transfers>\n");
my @transfer; my %max;
open (IN, "$file") || &niceexit("Can't open $file\n");
while (<IN>) {
chomp;
my ($genome, $gene, $count) =split /\t/;
$transfer[$genome][$gene] = $count;
unless ($max{$genome}) {$max{$genome}=$transfer[$genome][$gene]}
if ($transfer[$genome][$gene] > $max{$genome}) {$max{$genome}=$transfer[$genome][$gene]}
}
close IN;
my ($genomelength, $beg, $end, $organismname, $orfs, $complement) = &getdata(\%max);
#generate the image. This is largely taken from projection_map.cgi (part of ERGO).
my $template_color = 'tan';
my $template_highlight_color = 'wheat';
my $contig_bar_width = 25;
my $vspace = 10;
my $l_margin = LEFT_MARGIN;
my $t_margin = 10;
my $bgcolor = 'white';
my $image_height = $vspace + (@transfer+3) * ($contig_bar_width + $vspace) + 25;
my $image = Image->new(IMAGE_WIDTH, $image_height)->fill('white');
my %templateFrame;
my $longestgenome = 1;
foreach my $alllength (keys %$genomelength) {
if ($$genomelength{$alllength} > $longestgenome) {$longestgenome=$$genomelength{$alllength}}
}
my $offset = ${l_margin}-5;
{
$templateFrame{'sizemarker'} = $image->Frame->place(-coords => ["${l_margin}p", "${t_margin}p", 0.95, ".+${contig_bar_width}p"]);
my $fivekb = 5000/$longestgenome;
$templateFrame{'sizemarker'}->line(-coords=>['0', '1', $fivekb, '1'], -fill=>'black', -width=>'0.01');
$templateFrame{'sizemarker'}->line(-coords=>['0', '0.75', '0', '1'], -fill=>'black', -width=>'0.01');
$templateFrame{'sizemarker'}->line(-coords=>[$fivekb, '0.75', $fivekb, '1'], -fill=>'black', -width=>'0.01');
$templateFrame{'sizemarker'}->string(-coords => ['0', '0'], -text => '0', -color => 'navy');
$templateFrame{'sizemarker'}->string(-coords => [$fivekb, '0'], -text => '5 kb', -color => 'navy');
$templateFrame{'sizemarker'}->line(-coords=>["-${offset}p", '1.2', '1.5', '1.2'], -fill=>'grey', -width=>'0.01');
}
foreach my $genome (1 .. $#transfer) {
print STDERR "Adding $genome\n";
my $origin;
if ($genome > 1) {
my $oldgenome = $genome-1;
$origin = ($templateFrame{$oldgenome}->coords)[3];
$origin += $vspace;
}
else {$origin = $t_margin+50}
#generate the frame for each genome and add the organism name
$templateFrame{$genome} = $image->Frame->place(-coords => ["${l_margin}p", "${origin}p", 0.95, ".+${contig_bar_width}p"]);
unless ($$organismname{$genome}) {print STDERR "WARNING: No genome name for $genome\n"}
my $name = int($$genomelength{$genome}/1000);
$name = $$organismname{$genome}." (".$name."kb)";
if (length($name) > 27) {
$name =~ /(.{0,27})\s+(.*?)$/;
my $name1 = $1; my $name2 = $2;
print STDERR "Name1 : $name1 Name2: $name2\n";
$templateFrame{$genome}->string(-coords => ["-${offset}p", '0p'], -text => $name1, -color => 'navy');
$templateFrame{$genome}->string(-coords => ["-${offset}p", '.5'], -text => $name2, -color => 'navy');
}
else {
$templateFrame{$genome}->string(-coords => ["-${offset}p", '0p'], -text => $name, -color => 'navy');
}
# add a line around the genome, and a line for the transfer charts;
#add the arrows for the ORFS
foreach my $orf (@{$$orfs{$genome}}) {
my ($start, $stop) = ($$beg{$orf}, $$end{$orf});
if ($start > $stop) {($stop, $start) = ($start, $stop)}
# $start = $start/$$genomelength{$genome};
# $stop = $stop/$$genomelength{$genome};
$start = $start/$longestgenome;
$stop = $stop/$longestgenome;
if ($$complement{$orf}) {
$templateFrame{$genome}->line(-coords=>[$start, '0', $stop, '0'], -fill=>'red', -arrow=>'first', -width=>'0.05');
}
else {
$templateFrame{$genome}->line(-coords=>[$start, '0', $stop, '0'], -fill=>'red', -arrow=>'last', -width=>'0.05');
}
}
# add the proteins and their arrows
foreach my $gene (1 .. $#{$transfer[$genome]}) {
if ($transfer[$genome][$gene]) {
# calculate the percent transfer. The one that is transferred the most will be 100%
my $height = 1-(($transfer[$genome][$gene]/$max{$genome})*0.8);
# now add the rectangles for the transfer frequency
my ($start, $stop) = ($$beg{$gene}, $$end{$gene});
# $start = $start/$$genomelength{$genome};
# $stop = $stop/$$genomelength{$genome};
$start = $start/$longestgenome;
$stop = $stop/$longestgenome;
$templateFrame{$genome}->filledRectangle($start, $height, $stop, '1', 'blue');
}
}
my $genomefraction = $$genomelength{$genome}/$longestgenome;
$templateFrame{$genome}->line(-coords=>['0', '1', "$genomefraction", '1'], -fill=>'black', -width=>'0.01');
$templateFrame{$genome}->line(-coords=>['0', '0.2', '0', '1'], -fill=>'black', -width=>'0.01');
$templateFrame{$genome}->line(-coords=>["-${offset}p", '1.2', '1.5', '1.2'], -fill=>'grey', -width=>'0.01');
}
open IMG, ">$file.scaled.png";
print IMG $image->png;
close IMG;
&niceexit();
sub niceexit {
my $reason = shift;
$dbh->disconnect;
if ($reason) {print STDERR $reason; exit(-1)}
else {exit(0)}
}
sub getdata {
print STDERR "Getting data\n";
my $genomes = shift;
my %genomelength; my %start; my %stop; my %organismname; my %orfs; my %complement;
my $exc = $dbh->prepare("SELECT count, organism, sequence from phage" ) or croak $dbh->errstr;
$exc->execute or die $dbh->errstr;
while (my @retrieved = $exc->fetchrow_array) {
$organismname{$retrieved[0]} = $retrieved[1];
$genomelength{$retrieved[0]} = length($retrieved[2]);
}
foreach my $key (keys %$genomes) {
print STDERR "\tGetting $key\n";
$exc = $dbh->prepare("SELECT count,start,stop,complement from protein where organism = $key" ) or croak $dbh->errstr;
$exc->execute or die $dbh->errstr;
while (my @retrieved = $exc->fetchrow_array) {
($start{$retrieved[0]}, $stop{$retrieved[0]}) = ($retrieved[1], $retrieved[2]);
push (@{$orfs{$key}}, $retrieved[0]);
$complement{$retrieved[0]} = $retrieved[3];
}
}
print STDERR "\tDone\n";
return \%genomelength, \%start, \%stop, \%organismname, \%orfs, \%complement;
}
| linsalrob/bioinformatics | phage_tree/drawtras.scaled.pl | Perl | mit | 7,203 |
:- use_module(library(lists)).
:- use_module(library(random)).
:- use_module(library(clpfd)).
:- use_module(library(samsort)).
config_file('tp2_config.pl').
read_config :-
config_file(F),
open(F, read, Str),
read_file(Str, _),
close(Str).
read_file(Stream, []) :-
at_end_of_stream(Stream).
read_file(Stream, [X|L]) :-
\+ at_end_of_stream(Stream),
read(Stream, X),
assert(X),
read_file(Stream, L).
all_equal([], _).
all_equal([X|T], X) :-
all_equal(T, X).
generate_task_types(L, AuthR, ScriptsR, StorageR) :-
requests(R),
auth_percentage(AP),
scripts_percentage(SP),
storage_percentage(StP),
AuthR is round(R * (AP / 100)),
ScriptsR is round(R * (SP / 100)),
StorageR is round(R * (StP / 100)),
length(AuthL, AuthR),
length(ScriptsL, ScriptsR),
length(StorageL, StorageR),
all_equal(AuthL, 0),
all_equal(ScriptsL, 1),
all_equal(StorageL, 2),
append([AuthL, ScriptsL, StorageL], List),
random_permutation(List, L).
highest_request_time(Time) :-
auth_request_time(Auth), storage_request_time(Storage), script_request_time(Script),
max_member(Time, [Auth, Storage, Script]).
%% indexed by machine id (0 - auth, 1 - storage, 2 - script)
request_time(0, X) :- auth_request_time(X).
request_time(1, X) :- storage_request_time(X).
request_time(2, X) :- script_request_time(X).
request_disk(0, X) :- auth_request_disk(X).
request_disk(1, X) :- storage_request_disk(X).
request_disk(2, X) :- script_request_disk(X).
request_ram(0, X) :- auth_request_ram(X).
request_ram(1, X) :- storage_request_ram(X).
request_ram(2, X) :- script_request_ram(X).
request_cpu(0, X) :- auth_request_cpu(X).
request_cpu(1, X) :- storage_request_cpu(X).
request_cpu(2, X) :- script_request_cpu(X).
generate_tasks([], [], [], [], [], []).
generate_tasks([TaskType|TaskTypes], [TaskDisk|TaskDisks], [TaskRAM|TaskRAMs], [TaskCPU|TaskCPUs], [TaskST|TaskSTs], [TaskET|TaskETs]) :-
request_time(TaskType, Time),
request_disk(TaskType, Disk),
request_ram(TaskType, RAM),
request_cpu(TaskType, CPU),
TaskDisk = task(TaskST, Time, TaskET, Disk, TaskType),
TaskRAM = task(TaskST, Time, TaskET, RAM, TaskType),
TaskCPU = task(TaskST, Time, TaskET, CPU, TaskType),
generate_tasks(TaskTypes, TaskDisks, TaskRAMs, TaskCPUs, TaskSTs, TaskETs).
generate_machines_disk([machine(0, A), machine(1, B), machine(2, C)]) :-
server_auth_disk(A),
server_storage_disk(B),
server_script_disk(C).
generate_machines_ram([machine(0, A), machine(1, B), machine(2, C)]) :-
server_auth_ram(A),
server_storage_ram(B),
server_script_ram(C).
generate_machines_cpu([machine(0, A), machine(1, B), machine(2, C)]) :-
server_auth_cpu(A),
server_storage_cpu(B),
server_script_cpu(C).
calculate_cost_queues(_, [], _, TempSlots, TempSlots).
calculate_cost_queues([StartTime|StartTimes], [NextTime|NextTimes], OldestTime, TempSlots, TotalSlots) :-
DT is NextTime - StartTime,
calc_time_and_slots(StartTime, OldestTime, DT, NewOldestTime, TempSlots, NewSlots),
calculate_cost_queues(StartTimes, NextTimes, NewOldestTime, NewSlots, TotalSlots).
calc_time_and_slots(StartTime, OldestTime, DT, StartTime, TempSlots, TempSlots) :-
routing_spd_time(RouteTime),
highest_request_time(ReqTime),
DT >= RouteTime,
DTOld is StartTime - OldestTime,
DTOld >= ReqTime.
calc_time_and_slots(StartTime, OldestTime, DT, OldestTime, TempSlots, TempSlots) :-
routing_spd_time(RouteTime),
highest_request_time(ReqTime),
DT >= RouteTime,
DTOld is StartTime - OldestTime,
DTOld < ReqTime.
calc_time_and_slots(StartTime, OldestTime, DT, OldestTime, TempSlots, NewSlots) :-
routing_spd_time(RouteTime),
highest_request_time(ReqTime),
DT < RouteTime,
DTOld is StartTime - OldestTime,
DTOld < ReqTime,
NewSlots is TempSlots + 1.
calc_time_and_slots(StartTime, OldestTime, DT, StartTime, TempSlots, NewSlots) :-
routing_spd_time(RouteTime),
highest_request_time(ReqTime),
DT < RouteTime,
DTOld is StartTime - OldestTime,
DTOld >= ReqTime,
NewSlots is TempSlots + 1.
ordered_start_times([], TempList, List) :-
samsort(TempList, List). %% samsort does not remove duplicates
ordered_start_times([Task|Tasks], TempList, List) :-
arg(1, Task, ST), %% task(ST, DT, ET, Resc, Mach), arg is 1-indexed
append(TempList, [ST], TempList1),
ordered_start_times(Tasks, TempList1, List).
euro_unicode(8364).
write_profit_or_loss(X) :-
X > 0,
write('+'), write(X).
write_profit_or_loss(X) :-
write(X).
init :-
read_config,
generate_task_types(Types, AuthR, StorageR, ScriptsR),
requests(R),
length(TaskDisks, R), length(TaskRAMs, R), length(TaskCPUs, R), %% needed?
length(TaskSTs, R), length(TaskETs, R),
generate_tasks(Types, TaskDisks, TaskRAMs, TaskCPUs, TaskSTs, TaskETs),
generate_machines_disk(MachineDisks),
generate_machines_ram(MachineRAMs),
generate_machines_cpu(MachineCPUs),
routing_spd_time(RouteTime),
MaxTaskTime is 1000*60*60*24,
domain(TaskSTs, RouteTime, MaxTaskTime),
domain(TaskETs, RouteTime, MaxTaskTime),
domain([End], RouteTime, MaxTaskTime),
maximum(End, TaskETs),
cumulatives(TaskDisks, MachineDisks, [bound(upper)]),
cumulatives(TaskRAMs, MachineRAMs, [bound(upper)]),
cumulatives(TaskCPUs, MachineCPUs, [bound(upper)]),
append(TaskSTs, [End], Vars),
labeling([], Vars), %% program doesn't run if we use [minimize(End)]
write('===== FD Statistics ====='), nl,
fd_statistics, nl,
ordered_start_times(TaskDisks, [], [StartTime|StartTimes]),
calculate_cost_queues([StartTime|StartTimes], StartTimes, StartTime, 0, Slots),
write('======= Statistics ======'), nl,
statistics, nl,
spd_slot_price(SlotPrice),
server_auth_price(AuthPrice),
server_storage_price(StoragePrice),
server_script_price(ScriptPrice),
Cost is AuthPrice + StoragePrice + ScriptPrice + (Slots * SlotPrice), %% SPD slots only
budget(Budget),
euro_unicode(Euro),
ProfitLoss is Budget - Cost,
write('======== Results ========'), nl,
write('Number of Authentication Requests: '), write(AuthR), nl,
write('Number of Storage Requests: '), write(StorageR), nl,
write('Number of Script Execution Requests: '), write(ScriptsR), nl,
write('Number of SPD slots bought: '), write(Slots), nl,
write('Number of SSD slots bought: '), write(0), nl,
write('Number of Authentication Servers: '), write(1), nl,
write('Number of Storage Servers: '), write(1), nl,
write('Number of Script Execution Servers: '), write(1), nl,
write('Available budget: '), write(Budget), put_code(Euro), nl,
write('Total cost: '), write(Cost), put_code(Euro), nl,
write('Profit/Loss: '), write_profit_or_loss(ProfitLoss), put_code(Euro), nl.
| DDuarte/feup-plog-cequis_cloud | tp2.pl | Perl | mit | 7,019 |
use v6;
sub load_input {
my %replacements;
my @input = open("input").lines;
my $molecule = @input.pop;
@input.pop;
for (@input) {
my ($a,$b) = .split(/ \s* \=\> \s* /);
%replacements{$a}.push($b);
}
return ($molecule, %replacements);
}
sub locations_of {
my ($str1, $str2) = @_;
my @loc = ();
my $offset = 0;
my Int $i = $str1.index($str2, $offset);
while (defined($i)) {
@loc.push($i);
$offset = $i + $str2.chars;
$i = $str1.index($str2, $offset);
}
return @loc;
}
sub solve_part1($molecule, %replacements) {
my $total = 0;
my $new_molecules = SetHash.new();
for %replacements.keys -> $a {
if ($molecule.contains($a)) {
my @loc = locations_of($molecule, $a);
for @loc -> $loc {
for %replacements{$a}.values -> $b {
my $new_molecule = $molecule.substr(0, $loc) ~ $b ~ $molecule.substr($loc + $a.chars);
$new_molecules{$new_molecule} = 1;
$total++;
}
}
}
}
say "Part 1: {$new_molecules.elems}";
}
sub common_prefix_length(Str $a, Str $b) {
return (1..([min] $a.chars, $b.chars)).reverse.first({ $a.substr(0,$_) eq $b.substr(0,$_) })//-Inf;
}
sub common_suffix_length(Str $a, Str $b) {
return common_prefix_length($a.flip, $b.flip);
}
sub solve-part2-breakdown($molecule, %replacements) {
my %inv-rep;
for %replacements.keys -> $a {
for %replacements{$a}.values -> $b {
die "FAIL" if defined %inv-rep{$b};
%inv-rep{$b} = $a;
}
}
my @mug;
@mug.push([ 0, $molecule ]);
my %seen;
while (@mug.elems > 0) {
my ($step, $m) = @mug.pop;
if ($m eq "e") {
say "Part 2: $step";
last;
}
my @mug2;
for %inv-rep.keys -> $b {
my $i = $m.index($b);
next unless defined($i);
my $nm = $m.subst($b, %inv-rep{$b}, :nth(1));
@mug2.push([$i, $nm]);
}
my $nstep = $step + 1;
@mug2 = @mug2.grep({ !defined(%seen{$_[1]}) && !($_[1].chars > 1 && $_[1].contains("e")) }).unique(:as({ $_[1] })).sort({ $^a[0] <=> $^b[0] }).map({ %seen{$_[1]}=True; [$nstep, $_[1]] });
@mug.append(@mug2);
}
return;
}
sub MAIN {
my ($molecule, %replacements) = load_input();
solve-part2-breakdown($molecule, %replacements);
solve_part1($molecule, %replacements);
}
| gugod/advent-of-code | 2015/day-19/solve.perl6.pl | Perl | cc0-1.0 | 2,531 |
package Paws::DataPipeline::ReportTaskProgress;
use Moose;
has Fields => (is => 'ro', isa => 'ArrayRef[Paws::DataPipeline::Field]', traits => ['NameInRequest'], request_name => 'fields' );
has TaskId => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'taskId' , required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ReportTaskProgress');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::DataPipeline::ReportTaskProgressOutput');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::DataPipeline::ReportTaskProgress - Arguments for method ReportTaskProgress on Paws::DataPipeline
=head1 DESCRIPTION
This class represents the parameters used for calling the method ReportTaskProgress on the
AWS Data Pipeline service. Use the attributes of this class
as arguments to method ReportTaskProgress.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ReportTaskProgress.
As an example:
$service_obj->ReportTaskProgress(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 Fields => ArrayRef[L<Paws::DataPipeline::Field>]
Key-value pairs that define the properties of the
ReportTaskProgressInput object.
=head2 B<REQUIRED> TaskId => Str
The ID of the task assigned to the task runner. This value is provided
in the response for PollForTask.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ReportTaskProgress in L<Paws::DataPipeline>
=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/DataPipeline/ReportTaskProgress.pm | Perl | apache-2.0 | 2,050 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Services::InvoiceService;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);
sub list {
my $self = shift;
my $request_body = shift;
my $http_method = 'GET';
my $request_path = 'v8/customers/{+customerId}/invoices';
my $response_type =
'Google::Ads::GoogleAds::V8::Services::InvoiceService::ListInvoicesResponse';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Services/InvoiceService.pm | Perl | apache-2.0 | 1,071 |
package Paws::Lightsail::Region;
use Moose;
has AvailabilityZones => (is => 'ro', isa => 'ArrayRef[Paws::Lightsail::AvailabilityZone]', request_name => 'availabilityZones', traits => ['NameInRequest']);
has ContinentCode => (is => 'ro', isa => 'Str', request_name => 'continentCode', traits => ['NameInRequest']);
has Description => (is => 'ro', isa => 'Str', request_name => 'description', traits => ['NameInRequest']);
has DisplayName => (is => 'ro', isa => 'Str', request_name => 'displayName', traits => ['NameInRequest']);
has Name => (is => 'ro', isa => 'Str', request_name => 'name', traits => ['NameInRequest']);
1;
### main pod documentation begin ###
=head1 NAME
Paws::Lightsail::Region
=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::Lightsail::Region object:
$service_obj->Method(Att1 => { AvailabilityZones => $value, ..., Name => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::Lightsail::Region object:
$result = $service_obj->Method(...);
$result->Att1->AvailabilityZones
=head1 DESCRIPTION
Describes the AWS Region.
=head1 ATTRIBUTES
=head2 AvailabilityZones => ArrayRef[L<Paws::Lightsail::AvailabilityZone>]
The Availability Zones. Follows the format C<us-east-1a>
(case-sensitive).
=head2 ContinentCode => Str
The continent code (e.g., C<NA>, meaning North America).
=head2 Description => Str
The description of the AWS Region (e.g., C<This region is recommended
to serve users in the eastern United States and eastern Canada>).
=head2 DisplayName => Str
The display name (e.g., C<Virginia>).
=head2 Name => Str
The region name (e.g., C<us-east-1>).
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::Lightsail>
=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/Lightsail/Region.pm | Perl | apache-2.0 | 2,274 |
#
# 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 hardware::server::dell::cmc::snmp::mode::hardware;
use base qw(centreon::plugins::templates::hardware);
use strict;
use warnings;
use centreon::plugins::misc;
sub set_system {
my ($self, %options) = @_;
$self->{regexp_threshold_overload_check_section_option} = '^(health|chassis|temperature|psu)$';
$self->{regexp_threshold_numeric_check_section_option} = '^(temperature|psu\.(voltage|power|current)|chassis\.(power|current))$';
$self->{cb_hook2} = 'snmp_execute';
$self->{thresholds} = {
health => [
['other', 'UNKNOWN'],
['unknown', 'UNKNOWN'],
['ok', 'OK'],
['nonCritical', 'WARNING'],
['critical', 'CRITICAL'],
['nonRecoverable', 'CRITICAL'],
],
};
$self->{components_path} = 'hardware::server::dell::cmc::snmp::mode::components';
$self->{components_module} = ['health', 'chassis', 'temperature', 'psu'];
}
sub snmp_execute {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request});
$self->display_system_information();
}
sub display_system_information {
my ($self, %options) = @_;
my $oid_drsProductShortName = '.1.3.6.1.4.1.674.10892.2.1.1.2.0';
my $oid_drsChassisServiceTag = '.1.3.6.1.4.1.674.10892.2.1.1.6.0';
my $oid_drsFirmwareVersion = '.1.3.6.1.4.1.674.10892.2.1.2.1.0';
my $snmp_result = $self->{snmp}->get_leef(oids => [$oid_drsProductShortName, $oid_drsChassisServiceTag, $oid_drsFirmwareVersion]);
$self->{output}->output_add(
long_msg => sprintf("Product Name: %s, Service Tag: %s, Firmware Version: %s",
defined($snmp_result->{$oid_drsProductShortName}) ? centreon::plugins::misc::trim($snmp_result->{$oid_drsProductShortName}) : 'unknown',
defined($snmp_result->{$oid_drsChassisServiceTag}) ? $snmp_result->{$oid_drsChassisServiceTag} : 'unknown',
defined($snmp_result->{$oid_drsFirmwareVersion}) ? $snmp_result->{$oid_drsFirmwareVersion} : 'unknown'
)
);
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {});
return $self;
}
1;
__END__
=head1 MODE
Check Hardware (Health, Temperatures, Power supplies metrics and chassis metrics).
=over 8
=item B<--component>
Which component to check (Default: '.*').
Can be: 'health', 'temperature', 'chassis', 'psu'.
=item B<--filter>
Exclude some parts (comma seperated list) (Example: --filter=fan)
Can also exclude specific instance: --filter=health,2
=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,status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='health,CRITICAL,^(?!(ok)$)'
=item B<--warning>
Set warning threshold for temperatures (syntax: type,regexp,threshold)
Example: --warning='temperature,.*,30'
=item B<--critical>
Set critical threshold for temperatures (syntax: type,regexp,threshold)
Example: --critical='temperature,.*,40'
=back
=cut
| Sims24/centreon-plugins | hardware/server/dell/cmc/snmp/mode/hardware.pm | Perl | apache-2.0 | 4,101 |
=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::Variation::Utils::VariationEffect
=head1 DESCRIPTION
This module defines a set of predicate subroutines that check the effect of a
Bio::EnsEMBL::Variation::VariationFeature on some other Bio::EnsEMBL::Feature.
All of these predicates take a VariationFeatureOverlapAllele as their first and
only argument and return a true or false value depending on whether the effect
being checked for holds or not. The link between these predicates and the
specific effect is configured in the Bio::EnsEMBL::Variation::Utils::Config
module and a list of OverlapConsequence objects that represent a link between,
for example, a Sequence Ontology consequence term, and the predicate that
checks for it is provided in the Bio::EnsEMBL::Variation::Utils::Constants
module. If you want to add a new consequence you should write a predicate in
this module and then add an entry in the configuration file.
=cut
package Bio::EnsEMBL::Variation::Utils::VariationEffect;
use strict;
use warnings;
use base qw(Exporter);
our @EXPORT_OK = qw(overlap within_cds MAX_DISTANCE_FROM_TRANSCRIPT);
use constant MAX_DISTANCE_FROM_TRANSCRIPT => 5000;
#package Bio::EnsEMBL::Variation::VariationFeatureOverlapAllele;
sub overlap {
my ( $f1_start, $f1_end, $f2_start, $f2_end ) = @_;
return ( ($f1_end >= $f2_start) and ($f1_start <= $f2_end) );
}
sub within_feature {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return overlap(
$vf->start,
$vf->end,
$feat->start,
$feat->end
);
}
sub _before_start {
my ($vf, $feat, $dist) = @_;
return ( ($vf->end >= ($feat->start - $dist)) and
($vf->end < $feat->start) );
}
sub _after_end {
my ($vf, $feat, $dist) = @_;
return ( ($vf->start <= ($feat->end + $dist))
and ($vf->start > $feat->end) );
}
sub _upstream {
my ($vf, $feat, $dist) = @_;
return $feat->strand == 1 ?
_before_start($vf, $feat, $dist) :
_after_end($vf, $feat, $dist);
}
sub _downstream {
my ($vf, $feat, $dist) = @_;
return $feat->strand == 1 ?
_after_end($vf, $feat, $dist) :
_before_start($vf, $feat, $dist);
}
#package Bio::EnsEMBL::Variation::TranscriptVariationAllele;
sub upstream_5KB {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return (_upstream($vf, $feat, 5000) and not upstream_2KB($vfoa));
}
sub downstream_5KB {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return (_downstream($vf, $feat, 5000) and not downstream_500B($vfoa));
}
sub upstream_2KB {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return _upstream($vf, $feat, 2000);
}
sub downstream_2KB {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return _downstream($vf, $feat, 2000);
}
sub downstream_500B {
my $vfoa = shift;
my $vf = $vfoa->variation_feature;
my $feat = $vfoa->feature;
return _downstream($vf, $feat, 500);
}
sub affects_transcript {
my ($vf, $tran) = @_;
return 0 unless $tran->isa('Bio::EnsEMBL::Transcript');
return overlap(
$vf->start,
$vf->end,
$tran->start - 5000,
$tran->end + 5000
);
}
sub within_transcript {
my $tva = shift;
return within_feature($tva);
}
sub within_nmd_transcript {
my $tva = shift;
my $tran = $tva->transcript;
return ( within_transcript($tva) and ($tran->biotype eq 'nonsense_mediated_decay') );
}
sub within_non_coding_gene {
my $tva = shift;
my $tran = $tva->transcript;
return ( within_transcript($tva) and (not $tran->translation) and (not within_mature_miRNA($tva)));
}
sub within_miRNA {
my $tva = shift;
my $tran = $tva->transcript;
# don't call this for now
return 0;
return ( within_transcript($tva) and ($tran->biotype eq 'miRNA') );
}
sub within_mature_miRNA {
my $tva = shift;
my $tv = $tva->transcript_variation;
my $vf = $tva->variation_feature;
my $tran = $tva->transcript;
return 0 unless ( within_transcript($tva) and ($tran->biotype eq 'miRNA') );
my ($attribute) = @{ $tran->get_all_Attributes('miRNA') };
if (defined $attribute && $attribute->value =~ /(\d+)-(\d+)/) {
for my $coord ($tv->_mapper->cdna2genomic($1, $2, $tran->strand)) {
if ($coord->isa('Bio::EnsEMBL::Mapper::Coordinate')) {
if (overlap(
$vf->start,
$vf->end,
$coord->start,
$coord->end) ) {
return 1;
}
}
}
}
return 0;
}
sub donor_splice_site {
my $tva = shift;
my $tran = $tva->transcript;
return $tran->strand == 1 ?
$tva->transcript_variation->_intron_effects->{start_splice_site} :
$tva->transcript_variation->_intron_effects->{end_splice_site};
}
sub acceptor_splice_site {
my $tva = shift;
my $tran = $tva->transcript;
return $tran->strand == 1 ?
$tva->transcript_variation->_intron_effects->{end_splice_site} :
$tva->transcript_variation->_intron_effects->{start_splice_site};
}
sub essential_splice_site {
my $tva = shift;
return ( acceptor_splice_site($tva) or donor_splice_site($tva) );
}
sub splice_region {
my $tva = shift;
return $tva->transcript_variation->_intron_effects->{splice_region};
}
sub within_intron {
my $tva = shift;
return $tva->transcript_variation->_intron_effects->{intronic};
}
sub within_cds {
my $tva = shift;
my $vf = $tva->variation_feature;
my $tran = $tva->transcript;
my $tv = $tva->transcript_variation;
my $cds_coords = $tva->transcript_variation->cds_coords;
if (@$cds_coords > 0) {
for my $coord (@$cds_coords) {
if ($coord->isa('Bio::EnsEMBL::Mapper::Coordinate')) {
if ($coord->end > 0 && $coord->start <= length($tv->_translateable_seq)) {
return 1;
}
}
}
}
return 0;
}
sub within_cdna {
my $tva = shift;
my $vf = $tva->variation_feature;
my $tran = $tva->transcript;
my $tv = $tva->transcript_variation;
my $cdna_coords = $tv->cdna_coords;
if (@$cdna_coords > 0) {
for my $coord (@$cdna_coords) {
if ($coord->isa('Bio::EnsEMBL::Mapper::Coordinate')) {
if ($coord->end > 0 && $coord->start <= $tran->length) {
return 1;
}
}
}
}
return 0;
}
sub _before_coding {
my ($vf, $tran) = @_;
return 0 unless defined $tran->translation;
my $vf_s = $vf->start;
my $vf_e = $vf->end;
my $t_s = $tran->start;
my $cds_s = $tran->coding_region_start;
# we need to special case insertions just before the CDS start
if ($vf_s == $vf_e+1 && $vf_s == $cds_s) {
return 1;
}
return overlap($vf_s, $vf_e, $t_s, $cds_s-1);
}
sub _after_coding {
my ($vf, $tran) = @_;
return 0 unless defined $tran->translation;
my $vf_s = $vf->start;
my $vf_e = $vf->end;
my $t_e = $tran->end;
my $cds_e = $tran->coding_region_end;
# we need to special case insertions just after the CDS end
if ($vf_s == $vf_e+1 && $vf_e == $cds_e) {
return 1;
}
return overlap($vf_s, $vf_e, $cds_e+1, $t_e);
}
sub within_5_prime_utr {
my $tva = shift;
my $vf = $tva->variation_feature;
my $tran = $tva->transcript;
my $five_prime_of_coding =
$tran->strand == 1 ?
_before_coding($vf, $tran) :
_after_coding($vf, $tran);
return ( $five_prime_of_coding and within_cdna($tva) );
}
sub within_3_prime_utr {
my $tva = shift;
my $vf = $tva->variation_feature;
my $tran = $tva->transcript;
my $three_prime_of_coding =
$tran->strand == 1 ?
_after_coding($vf, $tran) :
_before_coding($vf, $tran);
return ( $three_prime_of_coding and within_cdna($tva) );
}
sub complex_indel {
my $tva = shift;
my $vf = $tva->variation_feature;
# pass the no_db flag to var_class to ensure we don't rely on the database for it
# as it may not have been set at this stage in the pipeline
my $class = $vf->var_class(1);
return 0 unless $class =~ /^(in|del)/;
return @{ $tva->transcript_variation->cds_coords } > 1;
}
sub _get_peptide_alleles {
my $tva = shift;
my $tv = $tva->transcript_variation;
return () if frameshift($tva);
my $alt_pep = $tva->peptide;
return () unless defined $alt_pep;
my $ref_pep = $tv->get_reference_TranscriptVariationAllele->peptide;
$ref_pep = '' if $ref_pep eq '-';
$alt_pep = '' if $alt_pep eq '-';
return ($ref_pep, $alt_pep);
}
sub _get_codon_alleles {
my $tva = shift;
my $tv = $tva->transcript_variation;
return () if frameshift($tva);
my $alt_codon = $tva->codon;
return () unless defined $alt_codon;
my $ref_codon = $tv->get_reference_TranscriptVariationAllele->codon;
$ref_codon = '' if $ref_codon eq '-';
$alt_codon = '' if $alt_codon eq '-';
return ($ref_codon, $alt_codon);
}
sub stop_retained {
my $tva = shift;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless $ref_pep;
return ( $alt_pep =~ /\*/ && $ref_pep =~ /\*/ );
}
sub affects_start_codon {
my $tva = shift;
my $tv = $tva->transcript_variation;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless $ref_pep;
return ( ($tv->translation_start == 1) and (substr($ref_pep,0,1) ne substr($alt_pep,0,1)) );
}
sub synonymous_codon {
my $tva = shift;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless $ref_pep;
return ( ($alt_pep eq $ref_pep) and (not stop_retained($tva)) );
}
sub non_synonymous_codon {
my $tva = shift;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless defined $ref_pep;
return 0 if affects_start_codon($tva);
return 0 if stop_lost($tva);
return 0 if stop_gained($tva);
return 0 if partial_codon($tva);
return 0 if inframe_codon_loss($tva);
return 0 if inframe_codon_gain($tva);
return ( $ref_pep ne $alt_pep );
}
sub inframe_codon_gain {
my $tva = shift;
my ($ref_codon, $alt_codon) = _get_codon_alleles($tva);
return 0 unless defined $ref_codon;
return (
(length($alt_codon) > length ($ref_codon)) &&
( ($alt_codon =~ /^\Q$ref_codon\E/) || ($alt_codon =~ /\Q$ref_codon\E$/) )
);
}
sub inframe_codon_loss {
my $tva = shift;
my ($ref_codon, $alt_codon) = _get_codon_alleles($tva);
return 0 unless defined $ref_codon;
return (
(length($alt_codon) < length ($ref_codon)) &&
( ($ref_codon =~ /^\Q$alt_codon\E/) || ($ref_codon =~ /\Q$alt_codon\E$/) )
);
}
sub stop_gained {
my $tva = shift;
my $tv = $tva->transcript_variation;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless defined $ref_pep;
return ( ($alt_pep =~ /\*/) and ($ref_pep !~ /\*/) );
}
sub stop_lost {
my $tva = shift;
my ($ref_pep, $alt_pep) = _get_peptide_alleles($tva);
return 0 unless defined $ref_pep;
return ( ($alt_pep !~ /\*/) and ($ref_pep =~ /\*/) );
}
sub frameshift {
my $tva = shift;
return 0 if partial_codon($tva);
my $tv = $tva->transcript_variation;
return 0 unless defined $tv->cds_start;
my $var_len = $tv->cds_end - $tv->cds_start + 1;
my $allele_len = $tva->seq_length;
# if the allele length is undefined then we can't call a frameshift
return 0 unless defined $allele_len;
return abs( $allele_len - $var_len ) % 3;
}
sub partial_codon {
my $tva = shift;
my $tv = $tva->transcript_variation;
return 0 unless defined $tv->translation_start;
my $cds_length = length $tv->_translateable_seq;
my $codon_cds_start = ($tv->translation_start * 3) - 2;
my $last_codon_length = $cds_length - ($codon_cds_start - 1);
return ( $last_codon_length < 3 and $last_codon_length > 0 );
}
sub within_coding_frameshift_intron {
my $tva = shift;
return (within_cds($tva) and
$tva->transcript_variation->_intron_effects->{within_frameshift_intron});
}
sub coding_other {
my $tva = shift;
return (within_cds($tva) and (not $tva->peptide) and (not frameshift($tva)));
}
sub coding_unknown {
my $tva = shift;
return (within_coding_frameshift_intron($tva) or coding_other($tva));
}
#package Bio::EnsEMBL::Variation::RegulatoryFeatureVariationAllele;
sub within_regulatory_feature {
my $rfva = shift;
return within_feature($rfva);
}
#package Bio::EnsEMBL::Variation::ExternalFeatureVariationAllele;
sub within_external_feature {
my $efva = shift;
return (within_feature($efva) and (not within_miRNA_target_site($efva)));
}
#sub within_miRNA_target_site {
# my $efva = shift;
#
# my $fset = $efva->variation_feature_overlap->feature->feature_set;
#
# return ($fset && $fset->name eq 'miRanda miRNA targets');
#}
#package Bio::EnsEMBL::Variation::MotifFeatureVariationAllele;
#sub within_motif_feature {
# my $mfva = shift;
# return (
# within_feature($mfva) and
# !increased_binding_affinity($mfva) and
# !decreased_binding_affinity($mfva)
# );
#}
sub within_motif_feature {
my $mfva = shift;
return within_feature($mfva);
}
#sub increased_binding_affinity {
# my $mfva = shift;
# my $change = $mfva->binding_affinity_change;
# return (within_feature($mfva) and (defined $change) and ($change > 0));
#}
#
#sub decreased_binding_affinity {
# my $mfva = shift;
# my $change = $mfva->binding_affinity_change;
# return (within_feature($mfva) and (defined $change) and ($change < 0));
#}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl-variation/modules/Bio/EnsEMBL/Variation/Utils/VariationEffect.pm | Perl | apache-2.0 | 15,002 |
package Paws::RedShift::DeleteEventSubscription;
use Moose;
has SubscriptionName => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DeleteEventSubscription');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::RedShift::DeleteEventSubscription - Arguments for method DeleteEventSubscription on Paws::RedShift
=head1 DESCRIPTION
This class represents the parameters used for calling the method DeleteEventSubscription on the
Amazon Redshift service. Use the attributes of this class
as arguments to method DeleteEventSubscription.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DeleteEventSubscription.
As an example:
$service_obj->DeleteEventSubscription(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> SubscriptionName => Str
The name of the Amazon Redshift event notification subscription to be
deleted.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DeleteEventSubscription in L<Paws::RedShift>
=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/RedShift/DeleteEventSubscription.pm | Perl | apache-2.0 | 1,717 |
package Paws::CloudWatchLogs::CreateLogGroup;
use Moose;
has KmsKeyId => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'kmsKeyId' );
has LogGroupName => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'logGroupName' , required => 1);
has Tags => (is => 'ro', isa => 'Paws::CloudWatchLogs::Tags', traits => ['NameInRequest'], request_name => 'tags' );
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'CreateLogGroup');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CloudWatchLogs::CreateLogGroup - Arguments for method CreateLogGroup on Paws::CloudWatchLogs
=head1 DESCRIPTION
This class represents the parameters used for calling the method CreateLogGroup on the
Amazon CloudWatch Logs service. Use the attributes of this class
as arguments to method CreateLogGroup.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to CreateLogGroup.
As an example:
$service_obj->CreateLogGroup(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 KmsKeyId => Str
The Amazon Resource Name (ARN) of the CMK to use when encrypting log
data. For more information, see Amazon Resource Names - AWS Key
Management Service (AWS KMS).
=head2 B<REQUIRED> LogGroupName => Str
The name of the log group.
=head2 Tags => L<Paws::CloudWatchLogs::Tags>
The key-value pairs to use for the tags.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method CreateLogGroup in L<Paws::CloudWatchLogs>
=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/CloudWatchLogs/CreateLogGroup.pm | Perl | apache-2.0 | 2,172 |
#!/usr/bin/env perl
=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>.
=cut
use strict;
use warnings;
use Bio::EnsEMBL::Registry;
my $registry = 'Bio::EnsEMBL::Registry';
$registry->load_registry_from_db(
-host => 'ensembldb.ensembl.org',
-user => 'anonymous'
);
# 1. Cell Types
# Get the list of all cell types in the Human eFG. For each one print its name, gender and description
# Hint: not all cells have a determined gender
#Grab the eFG adaptor
my $cta = $registry->get_adaptor('Human', 'funcgen', 'celltype');
my @human_cell_types = @{$cta->fetch_all()};
foreach my $cell (@human_cell_types){
my $gender = $cell->gender || "Undetermined gender";
print $cell->name."\t".$gender."\t".$cell->description."\n";
}
__END__
>perl metadata_1.pl
HeLa-S3 female Human Epithelial Carcinoma Cells
GM06990 female Human B-Lymphocyte cell line
U2OS female Human Bone Osteosarcoma Epithelial Cells
CD4 Undetermined gender Human CD4 T-Cells
IMR90 female Human Fetal Lung Fibroblast
HL-60 female Human Promyelotic Leukemia Cells
HepG2 male Human hepatocellular liver carcinoma cell line
Lymphoblastoid Undetermined gender Lymphoblastoid cells
CD133 Undetermined gender Human CD133+ Hematopoietic Stem Cell
CD36 Undetermined gender Human CD36+ Erythrocyte Precursor Cell
K562 female Human myelogenous leukaemia cell line
GM12878 female Human B-Lymphocyte cell line
HUVEC Undetermined gender Human umbilical vein endothelial cell line
NHEK female Normal human epidermal keratinocyte cell line
H1ESC Undetermined gender Human Embryonic Stem Cells
MultiCell Undetermined gender Multiple CellTypes used in core RegulatoryFeature set
K562b female Human myelogenous leukaemia line (alternative)
NH-A Undetermined gender Normal Human Astrocytes
HSMM Undetermined gender Human Skeletal Muscle Myoblasts
HMEC Undetermined gender Human Mammary Epithelial Cells
| Ensembl/ensembl-funcgen | scripts/examples/solutions/metadata_1.pl | Perl | apache-2.0 | 2,858 |
package Paws::StorageGateway::ListLocalDisks;
use Moose;
has GatewayARN => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListLocalDisks');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::StorageGateway::ListLocalDisksOutput');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::StorageGateway::ListLocalDisks - Arguments for method ListLocalDisks on Paws::StorageGateway
=head1 DESCRIPTION
This class represents the parameters used for calling the method ListLocalDisks on the
AWS Storage Gateway service. Use the attributes of this class
as arguments to method ListLocalDisks.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListLocalDisks.
As an example:
$service_obj->ListLocalDisks(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> GatewayARN => Str
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ListLocalDisks in L<Paws::StorageGateway>
=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/StorageGateway/ListLocalDisks.pm | Perl | apache-2.0 | 1,597 |
#
# 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 centreon::common::adic::tape::snmp::mode::components::global;
use strict;
use warnings;
my %map_status = (
1 => 'good',
2 => 'failed',
3 => 'degraded',
4 => 'warning',
5 => 'informational',
6 => 'unknown',
7 => 'invalid',
);
my %map_agent_status = (
1 => 'other',
2 => 'unknown',
3 => 'ok',
4 => 'non-critical',
5 => 'critical',
6 => 'non-recoverable',
);
# In MIB 'ADIC-TAPE-LIBRARY-MIB'
my $mapping = {
GlobalStatus => { oid => '.1.3.6.1.4.1.3764.1.10.10.1.8', map => \%map_status }, # libraryGlobalStatus
};
# In MIB 'ADIC-INTELLIGENT-STORAGE-MIB'
my $mapping2 = {
GlobalStatus => { oid => '.1.3.6.1.4.1.3764.1.1.20.1', map => \%map_agent_status }, # agentGlobalStatus
};
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $mapping->{GlobalStatus}->{oid} },
{ oid => $mapping2->{GlobalStatus}->{oid} };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking global");
$self->{components}->{global} = {name => 'global', total => 0, skip => 0};
return if ($self->check_filter(section => 'global'));
my $instance = '0';
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$mapping->{GlobalStatus}->{oid}}, instance => $instance);
if (!defined($result->{GlobalStatus})) {
$result = $self->{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$mapping2->{GlobalStatus}->{oid}}, instance => $instance);
}
if (!defined($result->{GlobalStatus})) {
$self->{output}->output_add(long_msg => "skipping global status: no value.");
return ;
}
return if ($self->check_filter(section => 'global', instance => $instance));
$self->{components}->{global}->{total}++;
$self->{output}->output_add(long_msg => sprintf("library global status is %s [instance: %s].",
$result->{GlobalStatus}, $instance
));
my $exit = $self->get_severity(section => 'global', label => 'default', value => $result->{GlobalStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Library global status is %s",
$result->{GlobalStatus}));
}
}
1; | centreon/centreon-plugins | centreon/common/adic/tape/snmp/mode/components/global.pm | Perl | apache-2.0 | 3,247 |
package VMOMI::VirtualMachineConfigInfoNpivWwnType;
use parent 'VMOMI::SimpleType';
use strict;
use warnings;
1;
| stumpr/p5-vmomi | lib/VMOMI/VirtualMachineConfigInfoNpivWwnType.pm | Perl | apache-2.0 | 115 |
###########################################################################
#
# This file is partially auto-generated by the DateTime::Locale generator
# tools (v0.10). This code generator comes with the DateTime::Locale
# distribution in the tools/ directory, and is called generate-modules.
#
# This file was generated from the CLDR JSON locale data. See the LICENSE.cldr
# file included in this distribution for license details.
#
# Do not edit this file directly unless you are sure the part you are editing
# is not created by the generator.
#
###########################################################################
=pod
=encoding UTF-8
=head1 NAME
DateTime::Locale::el_GR - Locale data examples for the el-GR locale.
=head1 DESCRIPTION
This pod file contains examples of the locale data available for the
Greek Greece locale.
=head2 Days
=head3 Wide (format)
Δευτέρα
Τρίτη
Τετάρτη
Πέμπτη
Παρασκευή
Σάββατο
Κυριακή
=head3 Abbreviated (format)
Δευ
Τρί
Τετ
Πέμ
Παρ
Σάβ
Κυρ
=head3 Narrow (format)
Δ
Τ
Τ
Π
Π
Σ
Κ
=head3 Wide (stand-alone)
Δευτέρα
Τρίτη
Τετάρτη
Πέμπτη
Παρασκευή
Σάββατο
Κυριακή
=head3 Abbreviated (stand-alone)
Δευ
Τρί
Τετ
Πέμ
Παρ
Σάβ
Κυρ
=head3 Narrow (stand-alone)
Δ
Τ
Τ
Π
Π
Σ
Κ
=head2 Months
=head3 Wide (format)
Ιανουαρίου
Φεβρουαρίου
Μαρτίου
Απριλίου
Μαΐου
Ιουνίου
Ιουλίου
Αυγούστου
Σεπτεμβρίου
Οκτωβρίου
Νοεμβρίου
Δεκεμβρίου
=head3 Abbreviated (format)
Ιαν
Φεβ
Μαρ
Απρ
Μαΐ
Ιουν
Ιουλ
Αυγ
Σεπ
Οκτ
Νοε
Δεκ
=head3 Narrow (format)
Ι
Φ
Μ
Α
Μ
Ι
Ι
Α
Σ
Ο
Ν
Δ
=head3 Wide (stand-alone)
Ιανουάριος
Φεβρουάριος
Μάρτιος
Απρίλιος
Μάιος
Ιούνιος
Ιούλιος
Αύγουστος
Σεπτέμβριος
Οκτώβριος
Νοέμβριος
Δεκέμβριος
=head3 Abbreviated (stand-alone)
Ιαν
Φεβ
Μάρ
Απρ
Μάι
Ιούν
Ιούλ
Αύγ
Σεπ
Οκτ
Νοέ
Δεκ
=head3 Narrow (stand-alone)
Ι
Φ
Μ
Α
Μ
Ι
Ι
Α
Σ
Ο
Ν
Δ
=head2 Quarters
=head3 Wide (format)
1ο τρίμηνο
2ο τρίμηνο
3ο τρίμηνο
4ο τρίμηνο
=head3 Abbreviated (format)
Τ1
Τ2
Τ3
Τ4
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
1ο τρίμηνο
2ο τρίμηνο
3ο τρίμηνο
4ο τρίμηνο
=head3 Abbreviated (stand-alone)
Τ1
Τ2
Τ3
Τ4
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide (format)
προ Χριστού
μετά Χριστόν
=head3 Abbreviated (format)
π.Χ.
μ.Χ.
=head3 Narrow (format)
π.Χ.
μ.Χ.
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = Τρίτη, 5 Φεβρουαρίου 2008
1995-12-22T09:05:02 = Παρασκευή, 22 Δεκεμβρίου 1995
-0010-09-15T04:44:23 = Σάββατο, 15 Σεπτεμβρίου -10
=head3 Long
2008-02-05T18:30:30 = 5 Φεβρουαρίου 2008
1995-12-22T09:05:02 = 22 Δεκεμβρίου 1995
-0010-09-15T04:44:23 = 15 Σεπτεμβρίου -10
=head3 Medium
2008-02-05T18:30:30 = 5 Φεβ 2008
1995-12-22T09:05:02 = 22 Δεκ 1995
-0010-09-15T04:44:23 = 15 Σεπ -10
=head3 Short
2008-02-05T18:30:30 = 5/2/08
1995-12-22T09:05:02 = 22/12/95
-0010-09-15T04:44:23 = 15/9/-10
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 6:30:30 μ.μ. UTC
1995-12-22T09:05:02 = 9:05:02 π.μ. UTC
-0010-09-15T04:44:23 = 4:44:23 π.μ. UTC
=head3 Long
2008-02-05T18:30:30 = 6:30:30 μ.μ. UTC
1995-12-22T09:05:02 = 9:05:02 π.μ. UTC
-0010-09-15T04:44:23 = 4:44:23 π.μ. UTC
=head3 Medium
2008-02-05T18:30:30 = 6:30:30 μ.μ.
1995-12-22T09:05:02 = 9:05:02 π.μ.
-0010-09-15T04:44:23 = 4:44:23 π.μ.
=head3 Short
2008-02-05T18:30:30 = 6:30 μ.μ.
1995-12-22T09:05:02 = 9:05 π.μ.
-0010-09-15T04:44:23 = 4:44 π.μ.
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = Τρίτη, 5 Φεβρουαρίου 2008 - 6:30:30 μ.μ. UTC
1995-12-22T09:05:02 = Παρασκευή, 22 Δεκεμβρίου 1995 - 9:05:02 π.μ. UTC
-0010-09-15T04:44:23 = Σάββατο, 15 Σεπτεμβρίου -10 - 4:44:23 π.μ. UTC
=head3 Long
2008-02-05T18:30:30 = 5 Φεβρουαρίου 2008 - 6:30:30 μ.μ. UTC
1995-12-22T09:05:02 = 22 Δεκεμβρίου 1995 - 9:05:02 π.μ. UTC
-0010-09-15T04:44:23 = 15 Σεπτεμβρίου -10 - 4:44:23 π.μ. UTC
=head3 Medium
2008-02-05T18:30:30 = 5 Φεβ 2008, 6:30:30 μ.μ.
1995-12-22T09:05:02 = 22 Δεκ 1995, 9:05:02 π.μ.
-0010-09-15T04:44:23 = 15 Σεπ -10, 4:44:23 π.μ.
=head3 Short
2008-02-05T18:30:30 = 5/2/08, 6:30 μ.μ.
1995-12-22T09:05:02 = 22/12/95, 9:05 π.μ.
-0010-09-15T04:44:23 = 15/9/-10, 4:44 π.μ.
=head2 Available Formats
=head3 E (ccc)
2008-02-05T18:30:30 = Τρί
1995-12-22T09:05:02 = Παρ
-0010-09-15T04:44:23 = Σάβ
=head3 EHm (E HH:mm)
2008-02-05T18:30:30 = Τρί 18:30
1995-12-22T09:05:02 = Παρ 09:05
-0010-09-15T04:44:23 = Σάβ 04:44
=head3 EHms (E HH:mm:ss)
2008-02-05T18:30:30 = Τρί 18:30:30
1995-12-22T09:05:02 = Παρ 09:05:02
-0010-09-15T04:44:23 = Σάβ 04:44:23
=head3 Ed (E d)
2008-02-05T18:30:30 = Τρί 5
1995-12-22T09:05:02 = Παρ 22
-0010-09-15T04:44:23 = Σάβ 15
=head3 Ehm (E h:mm a)
2008-02-05T18:30:30 = Τρί 6:30 μ.μ.
1995-12-22T09:05:02 = Παρ 9:05 π.μ.
-0010-09-15T04:44:23 = Σάβ 4:44 π.μ.
=head3 Ehms (E h:mm:ss a)
2008-02-05T18:30:30 = Τρί 6:30:30 μ.μ.
1995-12-22T09:05:02 = Παρ 9:05:02 π.μ.
-0010-09-15T04:44:23 = Σάβ 4:44:23 π.μ.
=head3 Gy (y G)
2008-02-05T18:30:30 = 2008 μ.Χ.
1995-12-22T09:05:02 = 1995 μ.Χ.
-0010-09-15T04:44:23 = -10 π.Χ.
=head3 GyMMM (LLL y G)
2008-02-05T18:30:30 = Φεβ 2008 μ.Χ.
1995-12-22T09:05:02 = Δεκ 1995 μ.Χ.
-0010-09-15T04:44:23 = Σεπ -10 π.Χ.
=head3 GyMMMEd (E, d MMM y G)
2008-02-05T18:30:30 = Τρί, 5 Φεβ 2008 μ.Χ.
1995-12-22T09:05:02 = Παρ, 22 Δεκ 1995 μ.Χ.
-0010-09-15T04:44:23 = Σάβ, 15 Σεπ -10 π.Χ.
=head3 GyMMMd (d MMM y G)
2008-02-05T18:30:30 = 5 Φεβ 2008 μ.Χ.
1995-12-22T09:05:02 = 22 Δεκ 1995 μ.Χ.
-0010-09-15T04:44:23 = 15 Σεπ -10 π.Χ.
=head3 H (HH)
2008-02-05T18:30:30 = 18
1995-12-22T09:05:02 = 09
-0010-09-15T04:44:23 = 04
=head3 Hm (HH:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head3 Hms (HH:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Hmsv (HH:mm:ss v)
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Hmv (HH:mm v)
2008-02-05T18:30:30 = 18:30 UTC
1995-12-22T09:05:02 = 09:05 UTC
-0010-09-15T04:44:23 = 04:44 UTC
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 MEd (E, d/M)
2008-02-05T18:30:30 = Τρί, 5/2
1995-12-22T09:05:02 = Παρ, 22/12
-0010-09-15T04:44:23 = Σάβ, 15/9
=head3 MMM (LLL)
2008-02-05T18:30:30 = Φεβ
1995-12-22T09:05:02 = Δεκ
-0010-09-15T04:44:23 = Σεπ
=head3 MMMEd (E, d MMM)
2008-02-05T18:30:30 = Τρί, 5 Φεβ
1995-12-22T09:05:02 = Παρ, 22 Δεκ
-0010-09-15T04:44:23 = Σάβ, 15 Σεπ
=head3 MMMMEd (E, d MMMM)
2008-02-05T18:30:30 = Τρί, 5 Φεβρουαρίου
1995-12-22T09:05:02 = Παρ, 22 Δεκεμβρίου
-0010-09-15T04:44:23 = Σάβ, 15 Σεπτεμβρίου
=head3 MMMMd (d MMMM)
2008-02-05T18:30:30 = 5 Φεβρουαρίου
1995-12-22T09:05:02 = 22 Δεκεμβρίου
-0010-09-15T04:44:23 = 15 Σεπτεμβρίου
=head3 MMMd (d MMM)
2008-02-05T18:30:30 = 5 Φεβ
1995-12-22T09:05:02 = 22 Δεκ
-0010-09-15T04:44:23 = 15 Σεπ
=head3 Md (d/M)
2008-02-05T18:30:30 = 5/2
1995-12-22T09:05:02 = 22/12
-0010-09-15T04:44:23 = 15/9
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 h (h a)
2008-02-05T18:30:30 = 6 μ.μ.
1995-12-22T09:05:02 = 9 π.μ.
-0010-09-15T04:44:23 = 4 π.μ.
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 μ.μ.
1995-12-22T09:05:02 = 9:05 π.μ.
-0010-09-15T04:44:23 = 4:44 π.μ.
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 μ.μ.
1995-12-22T09:05:02 = 9:05:02 π.μ.
-0010-09-15T04:44:23 = 4:44:23 π.μ.
=head3 hmsv (h:mm:ss a v)
2008-02-05T18:30:30 = 6:30:30 μ.μ. UTC
1995-12-22T09:05:02 = 9:05:02 π.μ. UTC
-0010-09-15T04:44:23 = 4:44:23 π.μ. UTC
=head3 hmv (h:mm a v)
2008-02-05T18:30:30 = 6:30 μ.μ. UTC
1995-12-22T09:05:02 = 9:05 π.μ. UTC
-0010-09-15T04:44:23 = 4:44 π.μ. UTC
=head3 ms (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 y (y)
2008-02-05T18:30:30 = 2008
1995-12-22T09:05:02 = 1995
-0010-09-15T04:44:23 = -10
=head3 yM (M/y)
2008-02-05T18:30:30 = 2/2008
1995-12-22T09:05:02 = 12/1995
-0010-09-15T04:44:23 = 9/-10
=head3 yMEd (E, d/M/y)
2008-02-05T18:30:30 = Τρί, 5/2/2008
1995-12-22T09:05:02 = Παρ, 22/12/1995
-0010-09-15T04:44:23 = Σάβ, 15/9/-10
=head3 yMMM (MMM y)
2008-02-05T18:30:30 = Φεβ 2008
1995-12-22T09:05:02 = Δεκ 1995
-0010-09-15T04:44:23 = Σεπ -10
=head3 yMMMEd (E, d MMM y)
2008-02-05T18:30:30 = Τρί, 5 Φεβ 2008
1995-12-22T09:05:02 = Παρ, 22 Δεκ 1995
-0010-09-15T04:44:23 = Σάβ, 15 Σεπ -10
=head3 yMMMM (MMMM y)
2008-02-05T18:30:30 = Φεβρουαρίου 2008
1995-12-22T09:05:02 = Δεκεμβρίου 1995
-0010-09-15T04:44:23 = Σεπτεμβρίου -10
=head3 yMMMd (d MMM y)
2008-02-05T18:30:30 = 5 Φεβ 2008
1995-12-22T09:05:02 = 22 Δεκ 1995
-0010-09-15T04:44:23 = 15 Σεπ -10
=head3 yMd (d/M/y)
2008-02-05T18:30:30 = 5/2/2008
1995-12-22T09:05:02 = 22/12/1995
-0010-09-15T04:44:23 = 15/9/-10
=head3 yQQQ (y QQQ)
2008-02-05T18:30:30 = 2008 Τ1
1995-12-22T09:05:02 = 1995 Τ4
-0010-09-15T04:44:23 = -10 Τ3
=head3 yQQQQ (y QQQQ)
2008-02-05T18:30:30 = 2008 1ο τρίμηνο
1995-12-22T09:05:02 = 1995 4ο τρίμηνο
-0010-09-15T04:44:23 = -10 3ο τρίμηνο
=head2 Miscellaneous
=head3 Prefers 24 hour time?
No
=head3 Local first day of the week
1 (Δευτέρα)
=head1 SUPPORT
See L<DateTime::Locale>.
=cut
| jkb78/extrajnm | local/lib/perl5/DateTime/Locale/el_GR.pod | Perl | mit | 10,959 |
package Agua::Common::User;
use Moose::Role;
use Moose::Util::TypeConstraints;
=head2
PACKAGE Agua::Common::User
PURPOSE
USER METHODS FOR Agua::Common
=cut
use Data::Dumper;
#has 'requestor' => ( isa => 'Str|Undef', is => 'rw', default => '' );
sub getUsers {
my $self = shift;
$self->logDebug("()");
my $json = $self->json();
#### GET USERNAME AND SESSION ID
my $username = $self->username();
#### VALIDATE USER USING SESSION ID
$self->logError("User $username not validated") and exit unless $self->validate($username);
#### GET ALL SOURCES
my $query = qq{SELECT DISTINCT username, firstname, lastname, email, description FROM users ORDER BY username};
$query = qq{SELECT username, firstname, lastname, email, description FROM users WHERE username='$username'} if not $self->isAdminUser($username);
$self->logDebug("$query"); ;
my $users = $self->db()->queryhasharray($query);
$users = [] if not defined $users;
return $users;
}
sub updateUser {
=head2
SUBROUTINE updateUser
PURPOSE
SAVE USER INFORMATION TO users TABLE IN TWO
SCENARIOS:
1. THE USER UPDATES THEIR OWN INFORMATION
A PASSWORD CHECK IS REQUIRED.
2. IF THE USER IS AN ADMIN USER. NO oldpassword
IS REQUIRED. THIS ALLOWS ADMIN USERS TO CHANGE
THE PASSWORD OF THE data->{username} USER.
=cut
my $self = shift;
$self->logDebug("");
my $json = $self->json();
$self->logError("json->{data}->{oldpassword} is not defined}") and exit unless defined $json->{data}->{oldpassword}
or $self->isAdminUser($json->{username});
my $userobject = $json->{data};
#### ONLY AN ADMIN USER CAN CHANGE THE PASSWORD WITHOUT
#### PROVIDING THE OLD PASSWORD
my $old_password = $userobject->{oldpassword};
#$self->logDebug("old_password", $old_password);
my $new_password = $userobject->{newpassword};
#$self->logDebug("new_password", $new_password);
if ( not defined $new_password and not $new_password )
{
$self->logError("newpassword not defined") and return;
}
my $is_admin = $self->isAdminUser($json->{username});
if ( not defined $old_password and not $old_password and not $is_admin )
{
$self->logError("oldpassword not defined") and return;
}
#### GET USERNAME TO BE CHANGED
my $changer_username = $json->{username};
my $changed_username = $userobject->{username};
#### GET USER PASSWORD AND COMPARE TO INPUT oldpassword
$self->logDebug("Retrieving password");
my $query = "SELECT password FROM users WHERE username='$changed_username'";
$self->logDebug("query", $query);
my $stored_password = $self->db()->query($query);
#$self->logDebug("stored_password", $stored_password);
#### QUIT IF NO STORED PASSWORD AND NOT ADMIN USER
if ( not defined $stored_password and not $stored_password and not $is_admin)
{
$self->logError("No password for user in database") and return;
}
#### QUIT IF CHANGING SOMEONE ELSE'S PASSWORD AND NOT ADMIN USER
if ( $changer_username ne $changed_username and not $is_admin )
{
$self->logError("User does not have sufficient privileges: $changer_username") and return;
}
#### QUIT IF THE PASSWORD DOES NOT MATCH AND NOT ADMIN USER
if ( $stored_password ne $old_password and not $is_admin )
{
$self->logError("Incorrect password") and return;
}
#### QUIT IF THE PASSWORD DOES NOT MATCH AND ADMIN USER CHANGING OWN PASSWORD
if ( $stored_password ne $old_password
and $changer_username eq $changed_username and $is_admin )
{
$self->logError("Incorrect password") and return;
}
#### REMOVE FROM users TABLE IF EXISTS ALREADY
my ($success, $user) = $self->_removeUser($userobject);
$self->logError("Could not remove user $json->{username} from users table") if not defined $success and not $success;
#### ADD TO users TABLE
$userobject->{password} = $userobject->{newpassword};
$success = $self->_addUser($userobject);
$self->logDebug("'_addUser' success", $success);
$self->logError("Could not update user $userobject->{username}") and exit if not defined $success;
#### CHANGE USER PASSWORD
my $password = $userobject->{newpassword};
# #### FEDORA:
# (NB: CAN'T LOGIN ...)
# my $passwd = "echo $password | passwd --stdin $changed_username";
# $self->logDebug("passwd", $passwd);
# print `$passwd`;
#### UBUNTU
if ( $password ) {
my $change_password = "echo '$changed_username:$password' | chpasswd";
#$self->logDebug("change_password", $change_password);
print `$change_password`;
}
$self->logStatus("Updated user $changed_username");
}
sub addUser {
my $self = shift;
$self->logDebug("Common::addUser()");
my $username = $self->username();
$self->logError("requestor is not an admin user: $username") and exit if not $self->isAdminUser($username);
#### SET USER OBJECT
my $userobject = $self->json()->{data};
#### ADD USER TO DATABASE
my $success = $self->_addUser($userobject);
$self->logDebug("self->_addUser($username) success", $success);
$self->logError("Could not add user $userobject->{username}") and exit if not $success;
#### ADD LINUX USER
$self->_addLinuxUser($userobject);
$self->logStatus("Created user $userobject->{username}");
}
sub _addUser {
my $self = shift;
my $object = shift;
$self->logDebug("object", $object);
my $username = $object->{username};
$self->logError("username not defined") and exit if not defined $username;
#### SET TABLE AND REQUIRED FIELDS
my $table = "users";
my $required_fields = ["username", "email"];
#### CHECK REQUIRED FIELDS ARE DEFINED
my $not_defined = $self->db()->notDefined($object, $required_fields);
$self->logError("undefined values: @$not_defined") and exit if @$not_defined;
#### LATER: FIX THIS SO THAT THE DATE IS ADDED PROPERLY
$object->{datetime} = $self->db()->now();
#### DO THE ADD
return $self->_addToTable($table, $object, $required_fields);
}
sub _addLinuxDaemon {
my $self = shift;
my $object = shift;
$self->logDebug("object", $object);
my $username = $object->{username};
$self->logError("username not defined") and exit if not defined $username;
my $userid = $object->{userid};
$self->logError("userid not defined") and exit if not defined $userid;
my $removegroup = "groupdel $username 2> /dev/null 1> /dev/null";
$self->logDebug("$removegroup");
print `$removegroup`;
my $addgroup = "groupadd $username -g $userid 2> /dev/null 1> /dev/null";
$self->logDebug("$addgroup");
print `$addgroup`;
my $adduser = "useradd -r -s /bin/false $username --uid $userid -g $userid 2> /dev/null 1> /dev/null";
$self->logDebug("$adduser");
print `$adduser`;
}
sub _addLinuxUser {
#### CREATE USER ACCOUNT AND HOME DIRECTORY
my $self = shift;
my $object = shift;
my $arch = shift;
$self->logDebug("object", $object);
$self->logDebug("arch", $arch);
my $username = $object->{username};
$self->logError("username not defined") and exit if not defined $username;
#### GET USER DIR
my $userdir = $self->conf()->getKey("agua", 'USERDIR');
$self->logDebug("userdir", $userdir);
#### REDHAT:
#my $addgroup = "/usr/sbin/groupadd $username";
#my $adduser = "useradd -g $username -s/bin/bash -p $username -d $userdir/$username -m $username";
#### UBUNTU
my $set_home = "useradd -D -b $userdir 2> /dev/null 1> /dev/null";
$self->logDebug("$set_home");
print `$set_home`;
my $removegroup = "groupdel $username 2> /dev/null 1> /dev/null";
$self->logDebug("$removegroup");
print `$removegroup`;
my $adduser = "useradd -m $username -s /bin/bash 2> /dev/null 1> /dev/null";
$self->logDebug("$adduser");
print `$adduser`;
#### CREATE 'AGUA' DIR IN USER'S HOME FOLDER
my $aguadir = $self->conf()->getKey("agua", 'AGUADIR');
my $mkdir = "mkdir -p $userdir/$username/$aguadir";
$self->logDebug("$mkdir");
print `$mkdir`;
#### CHOWN USER HOME DIR
my $chown = "chown -R $username:$username $userdir/$username";
$self->logDebug("$chown");
print `$chown`;
#### SET chmod SO THAT agua USER CAN ACCESS AND CREATE FILES
my $chmod = "chmod 775 $userdir/$username $userdir/$username/$aguadir";
$self->logDebug("$chmod");
print `$chmod`;
#### SET USER UMASK (APACHE'S UMASK IS ALREADY SET AT 002)
my $umask = qq{echo "umask 0002" >> $userdir/$username/.bashrc};
$self->logDebug("$umask");
print `$umask`;
my $test = qq{echo "test file" >> $userdir/$username/$aguadir/testfile.txt};
$self->logDebug("$test");
print `$test`;
}
sub removeUser {
my $self = shift;
$self->logDebug("Common::removeUser()");
#### DO THE REMOVE
my $json = $self->json();
my $object = $json->{data};
my $success = $self->_removeUser($object);
$self->logError("Could not remove user $object->{username} from user table") and exit if not defined $success;
$self->_removeLinuxUser($object);
$self->logStatus("Removed user $object->{username}");
}
sub _removeUser {
my $self = shift;
my $object = shift;
$self->logDebug("object", $object);
#### CHECK REQUIRED FIELDS ARE DEFINED
my $table = "users";
my $required_fields = ["username"];
$self->logDebug("DOING self->db->notDefined");
my $not_defined = $self->db()->notDefined($object, $required_fields);
$self->logError("undefined values: @$not_defined") and exit if defined $not_defined and @$not_defined;
#### DO THE REMOVE
$self->logDebug("BEFORE self->removeFromTable object: $object");
return if not $self->_removeFromTable($table, $object, $required_fields);
$self->logDebug("AFTER self->removeFromTable");
#### REMOVE FROM GROUPS
$object->{owner} = $object->{username};
$object->{name} = $object->{username};
$object->{type} = "user";
$self->logDebug("DOING self->removeFromTable(groupmember, object, ['owner']");
$self->_removeFromTable("groupmember", $object, ["owner"]);
$self->_removeFromTable("groupmember", $object, ["name", "type"]);
}
sub _removeLinuxUser {
#### DELETE USER ACCOUNT AND HOME DIRECTORY
my $self = shift;
my $object = shift;
$self->logDebug("object", $object);
my $username = $object->{username};
$self->logError("username not defined") and exit if not defined $username;
#### DELETE USER
my $userdel = "userdel $username";
$self->logDebug("userdel", $userdel);
print `$userdel`;
#### DELETE GROUP
my $groupdel = "groupdel $username 2> /dev/null 1> /dev/null";
$self->logDebug("groupdel", $groupdel);
print `$groupdel`;
#### DELETE USER HOME DIR
my $userdir = $self->conf()->getKey("agua", 'USERDIR');
$self->logDebug("userdir", $userdir);
my $aguadir = $self->conf()->getKey("agua", 'AGUADIR');
my $mkdir = "rm -fr $userdir/$username/$aguadir";
$self->logDebug("$mkdir");
print `$mkdir`;
}
1; | agua/agua | lib/Agua/Common/User.pm | Perl | mit | 10,731 |
package PPOBackend::MySQL;
# PPOBackend::MySQL - MySQL backend for PPO
# $Id: MySQL.pm,v 1.11 2010-03-23 13:57:51 paczian Exp $
use strict;
use warnings;
use DBI;
use base qw( PPOBackend );
1;
=pod
=head1 NAME
PPOBackend::MySQL - MySQL backend for PPO
=head1 DESCRIPTION
This package implements the abstract PPOBackend wrapper for use with MySQL database
server (based on the DBI perl module).
=head1 METHODS
=over 4
=item * B<new> (I<host>, I<port>, I<database>, I<user>, I<password>, I<create_flag>)
Connects to the database backend using the database host I<host> on port I<port>.
If either I<host> or I<port> is false (undef), it uses the default host or port.
The parameter I<database_name> specifies the database to use and is mandatory.
The parameters I<user> and I<password> are optional. If set to a username and it's
cleartext password, those information will be used to authenticate with the database.
If I<create_flag> is set, new will create the database before connecting
to it.
=cut
sub new {
my ($class, $host, $port, $database, $user, $password, $create, $socket, $file) = @_;
# build connect string from parameters
my $connect = "DBI:mysql:".( ($create) ? '' : "database=$database" );
$connect .= ";host=$host" if ($host);
$connect .= ";port=$port" if ($port);
$connect .= ";mysql_socket=$socket" if ($socket);
my $dbsock = $Conf::dbsock;
$connect .= ";mysql_socket=$dbsock" if ($dbsock);
$user = (defined $user) ? $user : '';
$password = (defined $password) ? $password : '';
# initialize database handle.
my $dbh = DBI->connect($connect, $user, $password,
{ RaiseError => 1, AutoCommit => 0, PrintError => 0 }) ||
Confess("Database connect error.");
my $self = { 'dbhandle' => $dbh,
'source' => $database,
'connect' => $connect,
'database_name' => $database,
'file' => $file
};
bless ($self,$class);
# create database if necessary
if ($create && !$file) {
eval {
$self->dbh->do( "CREATE DATABASE $database");
$self->dbh->do( "USE $database");
$self->dbh->commit;
};
if ($@) {
eval { $self->dbh->rollback };
if ($@) {
Confess("Rollback failed: $@");
}
return undef;
}
}
return $self;
}
=pod
=item * B<new_from_connect_data> (I<connect_data>, I<database>, I<user>, I<password>)
Connects to the database backend using the I<connect_data> string which is stored
by the PPO when an object reference is created. The parameter I<database_name>
specifies the database to use and is mandatory.
The parameters I<user> and I<password> are optional. If set to a username and it's
cleartext password, those information will be used to authenticate with the database.
=cut
sub new_from_connect_data {
my ($class, $connect, $database, $user, $password) = @_;
$user = (defined $user) ? $user : '';
$password = (defined $password) ? $password : '';
# initialize database handle
my $dbh = DBI->connect($connect, $user, $password,
{ RaiseError => 1, AutoCommit => 0, PrintError => 0 }) ||
Confess("Database connect error.");
my $self = { 'dbhandle' => $dbh,
'source' => $database,
'connect' => $connect,
'database_name' => $database,
};
bless ($self,$class);
return $self;
}
=pod
=item * B<last_insert_id> ()
Returns the row id of the last insert command.
=cut
sub last_insert_id {
return $_[0]->dbh->{'mysql_insertid'};
}
=pod
=item * B<map_data_type> (I<data_type>)
Returns the mapping of a PPO datatype (read from the xml definition file) to
the column data type of the database table.
=cut
sub map_data_type {
my ($self, $type) = @_;
$type = uc($type);
my $types = { 'BOOLEAN' => 'BOOLEAN',
'INTEGER' => 'INTEGER',
'BIGINT' => 'BIGINT',
'FLOAT' => 'DOUBLE',
'TIMESTAMP' => 'TIMESTAMP',
'CHAR' => 'VARCHAR',
'TEXT' => 'TEXT',
'TEXT LONG' => 'LONGTEXT',
'BLOB' => 'BLOB',
'BLOB LONG' => 'LONGBLOB',
};
# simple data type
if (exists($types->{$type})) {
return $types->{$type};
}
# special case for CHAR(n)
elsif ($type =~ /^CHAR\((\d+)\)$/ or $type =~ /^CHAR \((\d+)\)$/) {
return "VARCHAR($1)";
}
# error
else {
Confess("Unknown data type '$type'.");
}
}
=pod
=item * B<create_table> (I<table>, I<columns>)
Create a new table I<table> in the database with the columns described in
I<columns>. The parameter I<columns> is an array of hashes. Each hash describes
one column and has the fields 'name', 'type', 'not_null', 'auto_increment' and
'primary_key'.
=cut
sub create_table {
my ($self, $table, $columns) = @_;
my @cols;
foreach my $c (@$columns) {
unless ($c->{name} and $c->{type}) {
die 'Method create_table called with incomplete parameters.';
}
my $column = $c->{name}.' '.$self->map_data_type($c->{type});
$column .= ' NOT NULL' if ($c->{not_null});
$column .= ' PRIMARY KEY' if ($c->{primary_key});
$column .= ' AUTO_INCREMENT' if ($c->{auto_increment});
push @cols, $column;
}
my $statement = sprintf ("CREATE TABLE %s ( %s )", $table, join(', ', @cols));
eval {
if ($self->{file}) {
open(FH, ">>".$self->{file}) or die "could not open sql output file ".$self->{file}.": $@ $!\n";
print FH $statement."\n";
close FH;
} else {
$self->dbh->do($statement);
$self->dbh->commit;
}
};
if ($@) {
eval { $self->dbh->rollback };
if ($@) {
Confess("Rollback failed: $@");
}
return undef;
}
return 1;
}
=pod
=item * B<create_index> (I<table>, I<columns>, I<unique>)
Create a new index on table I<table> in the database with the columns indexed given
in I<columns>. The parameter I<columns> is a reference to an array of column names.
If I<unique> is given and evaluates to true, the method will create an unique index.
=cut
sub create_index {
my ($self, $table, $index_name, $columns, $unique) = @_;
my $unique_string = ($unique) ? ' UNIQUE' : '';
my $statement = sprintf ("CREATE%s INDEX %s ON %s ( %s )",
$unique_string, $index_name, $table, join(', ', @{$columns}));
eval {
if ($self->{file}) {
open(FH, ">>".$self->{file}) or die "could not open sql output file ".$self->{file}.": $@ $!\n";
print FH $statement."\n";
close FH;
} else {
$self->dbh->do($statement);
$self->dbh->commit;
}
};
if ($@) {
eval { $self->dbh->rollback };
if ($@) {
Confess("Rollback failed: $@");
}
return undef;
}
return 1;
}
| wilke/MG-RAST | src/PPO/PPOBackend/MySQL.pm | Perl | bsd-2-clause | 6,628 |
#!/usr/bin/env perl
# Pragmas.
use strict;
use warnings;
# Modules.
use Person::ID::CZ::RC;
# Object.
my $obj = Person::ID::CZ::RC->new(
'rc' => '840229/1330',
);
# Get error.
my $error = $obj->error || '-';
# Print out.
print "Personal number: ".$obj->rc."\n";
print "Year: ".$obj->year."\n";
print "Month: ".$obj->month."\n";
print "Day: ".$obj->day."\n";
print "Sex: ".$obj->sex."\n";
print "Serial: ".$obj->serial."\n";
print "Checksum: ".$obj->checksum."\n";
print "Alternate: ".$obj->alternate."\n";
print "Valid: ".$obj->is_valid."\n";
print "Error: ".$error."\n";
# Output:
# Personal number: 840229/1330
# Year: 1984
# Month: 02
# Day: 29
# Sex: male
# Serial: 133
# Checksum: 0
# Alternate: 0
# Valid: 0
# Error: Checksum isn't valid. | tupinek/Person-ID-CZ-RC | examples/ex3.pl | Perl | bsd-2-clause | 758 |
## This file is part of simpleserver
## Copyright (C) 2000-2015 Index Data.
## All rights reserved.
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of Index Data 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 REGENTS 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 REGENTS AND 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.
package Net::Z3950::GRS1;
use strict;
use IO::Handle;
use Carp;
sub new {
my ($class, $href, $map) = @_;
my $self = {};
$self->{ELEMENTS} = [];
$self->{FH} = *STDOUT; ## Default output handle is STDOUT
$self->{MAP} = $map;
bless $self, $class;
if (defined($href) && ref($href) eq 'HASH') {
if (!defined($map)) {
croak 'Usage: new Net::Z3950::GRS1($href, $map);';
}
$self->Hash2grs($href, $map);
}
return $self;
}
sub Hash2grs {
my ($self, $href, $mapping) = @_;
my $key;
my $content;
my $aref;
my $issue;
$mapping = defined($mapping) ? $mapping : $self->{MAP};
$self->{MAP} = $mapping;
foreach $key (keys %$href) {
$content = $href->{$key};
next unless defined($content);
if (!defined($aref = $mapping->{$key})) {
print STDERR "Hash2grs: Unmapped key: '$key'\n";
next;
}
if (ref($content) eq 'HASH') { ## Subtree?
my $subtree = new Net::Z3950::GRS1($content, $mapping);
$self->AddElement($aref->[0], $aref->[1], &Net::Z3950::GRS1::ElementData::Subtree, $subtree);
} elsif (!ref($content)) { ## Regular string?
$self->AddElement($aref->[0], $aref->[1], &Net::Z3950::GRS1::ElementData::String, $content);
} elsif (ref($content) eq 'ARRAY') {
my $issues = new Net::Z3950::GRS1;
foreach $issue (@$content) {
my $entry = new Net::Z3950::GRS1($issue, $mapping);
$issues->AddElement(5, 1, &Net::Z3950::GRS1::ElementData::Subtree, $entry);
}
$self->AddElement($aref->[0], $aref->[1], &Net::Z3950::GRS1::ElementData::Subtree, $issues);
} else {
print STDERR "Hash2grs: Unsupported content type\n";
next;
}
}
}
sub GetElementList {
my $self = shift;
return $self->{ELEMENTS};
}
sub CreateTaggedElement {
my ($self, $type, $value, $element_data) = @_;
my $tagged = {};
$tagged->{TYPE} = $type;
$tagged->{VALUE} = $value;
$tagged->{OCCURANCE} = undef;
$tagged->{META} = undef;
$tagged->{VARIANT} = undef;
$tagged->{ELEMENTDATA} = $element_data;
return $tagged;
}
sub GetTypeValue {
my ($self, $TaggedElement) = @_;
return ($TaggedElement->{TYPE}, $TaggedElement->{VALUE});
}
sub GetElementData {
my ($self, $TaggedElement) = @_;
return $TaggedElement->{ELEMENTDATA};
}
sub CheckTypes {
my ($self, $which, $content) = @_;
if ($which == &Net::Z3950::GRS1::ElementData::String) {
if (ref($content) eq '') {
return 1;
} else {
croak "Wrong content type, expected a scalar";
}
} elsif ($which == &Net::Z3950::GRS1::ElementData::Subtree) {
if (ref($content) eq __PACKAGE__) {
return 1;
} else {
croak "Wrong content type, expected a blessed reference";
}
} else {
croak "Content type currently not supported";
}
}
sub CreateElementData {
my ($self, $which, $content) = @_;
my $ElementData = {};
$self->CheckTypes($which, $content);
$ElementData->{WHICH} = $which;
$ElementData->{CONTENT} = $content;
return $ElementData;
}
sub AddElement {
my ($self, $type, $value, $which, $content) = @_;
my $Elements = $self->GetElementList;
my $ElmData = $self->CreateElementData($which, $content);
my $TaggedElm = $self->CreateTaggedElement($type, $value, $ElmData);
push(@$Elements, $TaggedElm);
}
sub _Indent {
my ($self, $level) = @_;
my $space = "";
foreach (1..$level - 1) {
$space .= " ";
}
return $space;
}
sub _RecordLine {
my ($self, $level, $pool, @args) = @_;
my $fh = $self->{FH};
my $str = sprintf($self->_Indent($level) . shift(@args), @args);
print $fh $str;
if (defined($pool)) {
$$pool .= $str;
}
}
sub Render {
my $self = shift;
my %args = (
FORMAT => &Net::Z3950::GRS1::Render::Plain,
FILE => '/dev/null',
LEVEL => 0,
HANDLE => undef,
POOL => undef,
@_ );
my @Elements = @{$self->GetElementList};
my $TaggedElement;
my $fh = $args{HANDLE};
my $level = ++$args{LEVEL};
my $ref = $args{POOL};
if (!defined($fh) && defined($args{FILE})) {
open(FH, '> ' . $args{FILE}) or croak "Render: Unable to open file '$args{FILE}' for writing: $!";
FH->autoflush(1);
$fh = *FH;
}
$self->{FH} = defined($fh) ? $fh : $self->{FH};
$args{HANDLE} = $fh;
foreach $TaggedElement (@Elements) {
my ($type, $value) = $self->GetTypeValue($TaggedElement);
if ($self->GetElementData($TaggedElement)->{WHICH} == &Net::Z3950::GRS1::ElementData::String) {
$self->_RecordLine($level, $ref, "(%s,%s) %s\n", $type, $value, $self->GetElementData($TaggedElement)->{CONTENT});
} elsif ($self->GetElementData($TaggedElement)->{WHICH} == &Net::Z3950::GRS1::ElementData::Subtree) {
$self->_RecordLine($level, $ref, "(%s,%s) {\n", $type, $value);
$self->GetElementData($TaggedElement)->{CONTENT}->Render(%args);
$self->_RecordLine($level, $ref, "}\n");
}
}
if ($level == 1) {
$self->_RecordLine($level, $ref, "(0,0)\n");
}
}
package Net::Z3950::GRS1::ElementData;
## Define some constants according to the GRS-1 specification
sub Octets { 1 }
sub Numeric { 2 }
sub Date { 3 }
sub Ext { 4 }
sub String { 5 }
sub TrueOrFalse { 6 }
sub OID { 7 }
sub IntUnit { 8 }
sub ElementNotThere { 9 }
sub ElementEmpty { 10 }
sub NoDataRequested { 11 }
sub Diagnostic { 12 }
sub Subtree { 13 }
package Net::Z3950::GRS1::Render;
## Define various types of rendering formats
sub Plain { 1 }
sub XML { 2 }
sub Raw { 3 }
1;
__END__
=head1 NAME
Net::Z3950::Record::GRS1 - Perl package used to encode GRS-1 records.
=head1 SYNOPSIS
use Net::Z3950::GRS1;
my $a_grs1_record = new Net::Z3950::Record::GRS1;
my $another_grs1_record = new Net::Z3950::Record::GRS1;
$a_grs1_record->AddElement($type, $value, $content);
$a_grs1_record->Render();
=head1 DESCRIPTION
This Perl module helps you to create and manipulate GRS-1 records (generic record syntax).
So far, you have only access to three methods:
=head2 new
Creates a new GRS-1 object,
my $grs1 = new Net::Z3950::GRS1;
=head2 AddElement
Lets you add entries to a GRS-1 object. The method should be called this way,
$grs1->AddElement($type, $value, $which, $content);
where $type should be an integer, and $value is free text. The $which argument should
contain one of the constants listed in Appendix A. Finally, $content contains the "thing"
that should be stored in this entry. The structure of $content should match the chosen
element data type. For
$which == Net::Z3950::GRS1::ElementData::String;
$content should be some kind of scalar. If on the other hand,
$which == Net::Z3950::GRS1::ElementData::Subtree;
$content should be a GRS1 object.
=head2 Render
This method digs through the GRS-1 data structure and renders the record. You call it
this way,
$grs1->Render();
If you want to access the rendered record through a variable, you can do it like this,
my $record_as_string;
$grs1->Render(POOL => \$record_as_string);
If you want it stored in a file, Render should be called this way,
$grs1->Render(FILE => 'record.grs1');
When no file name is specified, you can choose to stream the rendered record, for instance,
$grs1->Render(HANDLE => *STDOUT); ## or
$grs1->Render(HANDLE => *STDERR); ## or
$grs1->Render(HANDLE => *MY_HANDLE);
=head2 Hash2grs
This method converts a hash into a GRS-1 object. Scalar entries within the hash are converted
into GRS-1 string elements. A hash entry can itself be a reference to another hash. In this case,
the new referenced hash will be converted into a GRS-1 subtree. The method is called this way,
$grs1->Hash2grs($href, $mapping);
where $href is the hash to be converted and $mapping is referenced hash specifying the mapping
between keys in $href and (type, value) pairs in the $grs1 object. The $mapping hash could
for instance look like this,
my $mapping = {
title => [2, 1],
author => [1, 1],
issn => [3, 1]
};
If the $grs1 object contains data prior to the invocation of Hash2grs, the new data represented
by the hash is simply added.
=head1 APPENDIX A
These element data types are specified in the Z39.50 protocol:
Net::Z3950::GRS1::ElementData::Octets
Net::Z3950::GRS1::ElementData::Numeric
Net::Z3950::GRS1::ElementData::Date
Net::Z3950::GRS1::ElementData::Ext
Net::Z3950::GRS1::ElementData::String <---
Net::Z3950::GRS1::ElementData::TrueOrFalse
Net::Z3950::GRS1::ElementData::OID
Net::Z3950::GRS1::ElementData::IntUnit
Net::Z3950::GRS1::ElementData::ElementNotThere
Net::Z3950::GRS1::ElementData::ElementEmpty
Net::Z3950::GRS1::ElementData::NoDataRequested
Net::Z3950::GRS1::ElementData::Diagnostic
Net::Z3950::GRS1::ElementData::Subtree <---
Only the '<---' marked types are so far supported in this package.
=head1 AUTHOR
Anders Sønderberg Mortensen <sondberg@indexdata.dk>
Index Data ApS, Copenhagen, Denmark.
2001/03/09
=head1 SEE ALSO
Specification of the GRS-1 standard, for instance in the Z39.50 protocol specification.
=cut
| indexgeo/simpleserver | GRS1.pm | Perl | bsd-3-clause | 10,395 |
#!/usr/bin/env perl
##fix
# Split the multi-allelic sites in a VCF onto multiple rows, one alt allele per row
# Jared Evans evans.jared@mayo.edu
# 10/2014
# David Rider
# 07/2016
# Add the option to supply your own INFO keys on the command line to use for splitting
use strict;
#use warnings;
#use Data::Dumper;
use Getopt::Long;
my @DEFAULT_INFO_KEYS_TO_SPLIT = qw(AC AF TAC EA_AC AA_AC AC_AFR AC_AMR AC_Adj AC_EAS AC_FIN AC_Hemi AC_Het AC_Hom AC_NFE AC_OTH AC_SAS AN AN_AFR AN_AMR AN_Adj AN_EAS AN_FIN AN_NFE AN_OTH AN_SAS GQ_MEAN Het_AFR Het_AMR Het_EAS Het_FIN Het_NFE Het_OTH Het_SAS Hom_AFR Hom_AMR Hom_EAS Hom_FIN Hom_NFE Hom_OTH Hom_SAS MLEAC Hemi_AFR Hemi_AMR Hemi_EAS Hemi_FIN Hemi_NFE Hemi_OTH Hemi_SAS);
# script options
my($input, $output, $info_keys_to_split_delimited, $help);
GetOptions("in|i:s" => \$input,
"out|o:s" => \$output,
"keys|k:s" => \$info_keys_to_split_delimited,
"help|h|?" => \&help);
# read from input file if defined
@ARGV = ();
if(defined $input){
$ARGV[0] = $input;
}
# print to output file if defined
my $fh;
if (defined $output) {
open $fh, '>', $output;
select $fh;
}
my @info_keys_to_split = @DEFAULT_INFO_KEYS_TO_SPLIT;
if (defined $info_keys_to_split_delimited) {
@info_keys_to_split = split(/,/, $info_keys_to_split_delimited);
}
# David Rider - create this to actually check if a key is in the list of keys for splitting - see below
my %info_keys_to_split_map = map { $_ => 1 } @info_keys_to_split;
my $sample_count = 0;
while(<>){
my $row = $_;
chomp $row;
my @line = split("\t",$row);
# deal with header
if(substr($line[0],0,1) eq "#"){
if($line[0] eq "#CHROM"){
# Samples begin at column 10
$sample_count = scalar(@line)-9;
#die("ERROR! No sample information in VCF\n") if $sample_count <= 0;
if ($sample_count <= 0){$row=$row."\tFORMAT\tSAMPLE"}
}
print $row."\n";
next;
}
# parse INFO field
my %info_values = ();
my @info_keys = ();
foreach my $info_pair (split(";",$line[7])){
my @key_value = split("=",$info_pair);
push(@info_keys,$key_value[0]);
if(scalar(@key_value) > 1){
$info_values{$key_value[0]} = join("=",@key_value[1..(scalar(@key_value)-1)]);
}
}
# reformat sample columns and print output
my @alt_alleles = split(",",$line[4]);
# split multiple alt alleles onto seperate lines
for(my $split_rownum = 0; $split_rownum < scalar(@alt_alleles); $split_rownum++){
next if (($alt_alleles[$split_rownum] eq "<NON_REF>")&& ($split_rownum > 0));
print join("\t",@line[0..3])."\t".$alt_alleles[$split_rownum]."\t".join("\t",@line[5..6])."\t";
# print out INFO fields
for(my $j = 0; $j < scalar(@info_keys); $j++){
if(exists $info_values{$info_keys[$j]}){
# these have comma seperated values for each alt allele
# check this key against the list of INFO keys to split
if(exists($info_keys_to_split_map{$info_keys[$j]})){
my @alt_info_values = split(",",$info_values{$info_keys[$j]});
if(scalar(@alt_info_values) > 1){
print $info_keys[$j]."=".$alt_info_values[$split_rownum];
}else{
print $info_keys[$j]."=".$alt_info_values[0];
}
}else{
print $info_keys[$j]."=".$info_values{$info_keys[$j]};
}
}else{
print $info_keys[$j];
}
print ";" if $j < scalar(@info_keys)-1; # only put semicolon between values
}
# Get FORMAT values
my @format_values = split(":",$line[8]);
if (!$line[8]){$line[8]="GT"}
print "\t".$line[8];
# print SAMPLE columns
for(my $sample_num = 0; $sample_num < $sample_count; $sample_num++){
print "\t";
my @sample_fields = split(":",$line[9+$sample_num]);
# special cases for each type of format value
for(my $field_num = 0; $field_num < scalar(@sample_fields); $field_num++){
my $output = "";
if($sample_fields[$field_num] eq "."){
$output = $sample_fields[$field_num];
}elsif($format_values[$field_num] eq "GT"){
my $separator = "/";
$separator = "|" if index($sample_fields[$field_num],"|") != -1; # check if GT is phased
my @gt_index = ();
if($separator eq "|"){
# escape the | symbol so it doesnt interpret as OR
@gt_index = split("\\".$separator,$sample_fields[$field_num]);
}else{
@gt_index = split($separator,$sample_fields[$field_num]);
}
my $ploidy = scalar(@gt_index);
# initialize GT output array
my @gt_out = ();
for(my $i = 0; $i < $ploidy; $i++){
push(@gt_out,".");
}
for(my $gt_ind = 0; $gt_ind < $ploidy; $gt_ind++){
if($gt_index[$gt_ind] ne "."){
if($gt_index[$gt_ind] == $split_rownum+1){
$gt_out[$gt_ind] = 1;
}elsif($gt_index[$gt_ind] == 0){
$gt_out[$gt_ind] = 0;
}
}
}
# don't sort the GTs if phased
if($separator eq "|"){
$output = join($separator,@gt_out);
}else{
$output = join($separator,sort(@gt_out));
}
}elsif($format_values[$field_num] eq "AD"){
my @ad = split(",",$sample_fields[$field_num]);
#ats Accomodate the 0/. GT value where only 1 AD value is present. Normally multiple exist.
if(scalar(@ad) == 1) {
$output = $ad[0];
}else{
$output = $ad[0].",".$ad[$split_rownum+1];
}
}elsif($format_values[$field_num] eq "GL" or $format_values[$field_num] eq "PL" or $format_values[$field_num] eq "GP"){
my @lk = split(",",$sample_fields[$field_num]);
# formula for finding correct GL or PL: F(j/k) = (k*(k+1)/2)+j
$output = $lk[0].",".$lk[((($split_rownum+1)*($split_rownum+2)/2)+0)].",".$lk[((($split_rownum+1)*($split_rownum+2)/2)+$split_rownum+1)];
}elsif($format_values[$field_num] eq "DP4"){
my @dp4 = split(",",$sample_fields[$field_num]);
$output = $dp4[0].",".$dp4[1].",".$dp4[($split_rownum+1)*2].",".$dp4[(($split_rownum+1)*2)+1];
}else{
$output = $sample_fields[$field_num];
}
# print output
if($field_num == 0){
print $output;
}else{
print ":".$output;
}
}
}
if (!$line[9]){print "\t0/1"}
print "\n";
}
}
sub help{
my $default_info_key_str = join(',', @DEFAULT_INFO_KEYS_TO_SPLIT);
print "
DESCRIPTION:
split_multi_vcf.pl will split triallelic and greater sites onto multiple lines ensuring
that each row only has one Alt allele. The script will also fix the necessary INFO and
FORMAT values to preserve valid VCF format.
USAGE:
split_multi_vcf.pl -i input.vcf -o output_split.vcf
cat input.vcf | split_multi_vcf.pl > output_split.vcf
OPTIONS:
--in,-i Optional path to uncompressed input VCF file with multi-allelic sites.
If this option is omitted then the script will read from STDIN.
--out,-o Optional path to output VCF file. If this option is omitted then the
script will print to STDOUT.
--keys,-k Supply the list of comma-delimited keys to split in the INFO field.
By default, the list of keys come from the ExAC VCF and are
$default_info_key_str
--help,-h,-? Display this help documentation.
";
exit;
}
| Steven-N-Hart/VariantDB_Challenge | submissions/StevenNHart/MongoDB_Sharded/scripts/gVCF_split.pl | Perl | mit | 7,214 |
#-----------------------------------------------------------
# svc2.pl
# Plugin for Registry Ripper; Access System hive file to get the
# services, display short format (hence "svc", shortened version
# of service.pl plugin); outputs info in .csv format
#
# Change history
# 20081129 - created
#
# Ref:
# http://msdn.microsoft.com/en-us/library/aa394073(VS.85).aspx
#
# Analysis Tip: Several services keys have Parameters subkeys that point to
# the ServiceDll value; During intrusions, a service key may be added to
# the system's Registry; using this module, send the output to .csv format
# and sort on column B to get the names to line up
#
# copyright 2008 H. Carvey
#-----------------------------------------------------------
package svc2;
#use strict;
my %config = (hive => "System",
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
osmask => 22,
version => 20081129);
sub getConfig{return %config}
sub getShortDescr {
return "Lists Services key contents by LastWrite times (CSV)";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
my %types = (0x001 => "Kernel driver",
0x002 => "File system driver",
0x004 => "Adapter",
0x010 => "Own_Process",
0x020 => "Share_Process",
0x100 => "Interactive");
my %starts = (0x00 => "Boot Start",
0x01 => "System Start",
0x02 => "Auto Start",
0x03 => "Manual",
0x04 => "Disabled");
sub pluginmain {
my $class = shift;
my $hive = shift;
# ::logMsg("Launching svc2 v.".$VERSION);
my $reg = Parse::Win32Registry->new($hive);
my $root_key = $reg->get_root_key;
# First thing to do is get the ControlSet00x marked current...this is
# going to be used over and over again in plugins that access the system
# file
my $current;
my $key_path = 'Select';
my $key;
if ($key = $root_key->get_subkey($key_path)) {
$current = $key->get_value("Current")->get_data();
my $ccs = "ControlSet00".$current;
my $s_path = $ccs."\\Services";
my $svc;
my %svcs;
if ($svc = $root_key->get_subkey($s_path)) {
# ::rptMsg($s_path);
# ::rptMsg(getShortDescr());
# ::rptMsg("");
# Get all subkeys and sort based on LastWrite times
my @subkeys = $svc->get_list_of_subkeys();
if (scalar (@subkeys) > 0) {
foreach my $s (@subkeys) {
$name = $s->get_name();
my $display;
eval {
$display = $s->get_value("DisplayName")->get_data();
# take commas out of the display name, replace w/ semi-colons
$display =~ s/,/;/g;
};
my $type;
eval {
$type = $s->get_value("Type")->get_data();
$type = $types{$type} if (exists $types{$type});
};
my $image;
eval {
$image = $s->get_value("ImagePath")->get_data();
};
my $start;
eval {
$start = $s->get_value("Start")->get_data();
$start = $starts{$start} if (exists $starts{$start});
};
my $object;
eval {
$object = $s->get_value("ObjectName")->get_data();
};
my $str = $name."\|".$display."\|".$image."\|".$type."\|".$start."\|".$object;
push(@{$svcs{$s->get_timestamp()}},$str) unless ($str eq "");
# Get ServiceDll value if there is one
eval {
my $para = $s->get_subkey("Parameters");
my $dll = $para->get_value("ServiceDll")->get_data();
my $str = $name."\\Parameters\|\|".$dll."\|\|\|";
push(@{$svcs{$para->get_timestamp()}},$str);
};
}
foreach my $t (reverse sort {$a <=> $b} keys %svcs) {
# ::rptMsg(gmtime($t)."Z");
foreach my $item (@{$svcs{$t}}) {
my ($n,$d,$i,$t2,$s,$o) = split(/\|/,$item,6);
# ::rptMsg($t.",".$n.",".$d.",".$i.",".$t2.",".$s.",".$o);
::rptMsg(gmtime($t)."Z".",".$n.",".$d.",".$i.",".$t2.",".$s.",".$o);
}
}
}
else {
::rptMsg($s_path." has no subkeys.");
::logMsg("Error: ".$s_path." has no subkeys.");
}
}
else {
::rptMsg($s_path." not found.");
::logMsg($s_path." not found.");
}
}
else {
::rptMsg($key_path." not found.");
::logMsg($key_path." not found.");
}
}
1; | kefir-/autopsy | RecentActivity/release/rr-full/plugins/svc2.pl | Perl | apache-2.0 | 4,457 |
#
# Copyright 2017 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::sql::mode::partitioning;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use POSIX;
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 =>
{
"tablename:s@" => { name => 'tablename' },
"timezone:s" => { name => 'timezone' },
"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->{warn1} . "'.");
$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->{critical} . "'.");
$self->{output}->option_exit();
}
if (!defined($self->{option_results}->{tablename}) || scalar(@{$self->{option_results}->{tablename}}) == 0) {
$self->{output}->add_option_msg(short_msg => "Please set tablename option.");
$self->{output}->option_exit();
}
if (defined($self->{option_results}->{timezone}) && $self->{option_results}->{timezone} ne '') {
$ENV{TZ} = $self->{option_results}->{timezone};
}
}
sub run {
my ($self, %options) = @_;
# $options{sql} = sqlmode object
$self->{sql} = $options{sql};
$self->{sql}->connect();
$self->{output}->output_add(severity => 'OK',
short_msg => sprintf("All table partitions are up to date"));
foreach my $value (@{$self->{option_results}->{tablename}}) {
next if ($value eq '');
if ($value !~ /(\S+)\.(\S+)/) {
$self->{output}->output_add(severity => 'UNKNOWN',
short_msg => sprintf("Wrong table name '%s'", $value));
next;
}
my ($database, $table) = ($1, $2);
$self->{sql}->query(query => "SELECT MAX(CONVERT(PARTITION_DESCRIPTION, SIGNED INTEGER)) as lastPart FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME='" . $table . "' AND TABLE_SCHEMA='" . $database . "' GROUP BY TABLE_NAME;");
my ($last_time) = $self->{sql}->fetchrow_array();
if (!defined($last_time)) {
$self->{output}->output_add(severity => 'UNKNOWN',
short_msg => sprintf("Couldn't get partition infos for table '%s'", $value));
next;
}
my $retention_forward_current = 0;
my ($day,$month,$year) = (localtime(time))[3,4,5];
my $current_time = mktime(0, 0, 0, $day, $month, $year);
while ($current_time < $last_time) {
$retention_forward_current++;
$current_time = mktime(0, 0, 0, ++$day, $month, $year);
}
$self->{output}->output_add(long_msg => sprintf("Table '%s' last partition date is %s (current retention forward in days: %s)", $value, scalar(localtime($last_time)), $retention_forward_current));
my $exit = $self->{perfdata}->threshold_check(value => $retention_forward_current, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Partitions for table '%s' are not up to date (current retention forward in days: %s)", $value, $retention_forward_current));
}
}
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check that partitions for MySQL/MariaDB tables are correctly created.
The mode should be used with mysql plugin and dyn-mode option.
=over 8
=item B<--tablename>
This option is mandatory (can be multiple).
Example: centreon_storage.data_bin
=item B<--warning>
Threshold warning (number of retention forward days)
=item B<--critical>
Threshold critical (number of retention forward days)
=item B<--timezone>
Timezone use for partitioning (If not set, we use current server execution timezone)
=back
=cut
| nichols-356/centreon-plugins | apps/centreon/sql/mode/partitioning.pm | Perl | apache-2.0 | 5,516 |
#
# Copyright 2017 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::lefthand::snmp::mode::components::rcc;
use strict;
use warnings;
use storage::hp::lefthand::snmp::mode::components::resources qw($map_status);
my $mapping = {
infoCacheName => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.2' },
infoCacheBbuState => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.22' },
infoCacheBbuStatus => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.23', map => $map_status },
infoCacheEnabled => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.50' },
infoCacheState => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.90' },
infoCacheStatus => { oid => '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.91', map => $map_status },
};
my $oid_infoCacheEntry = '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_infoCacheEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking raid controller caches");
$self->{components}->{rcc} = {name => 'raid controller caches', total => 0, skip => 0};
return if ($self->check_filter(section => 'rcc'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_infoCacheEntry}})) {
next if ($oid !~ /^$mapping->{infoCacheStatus}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_infoCacheEntry}, instance => $instance);
next if ($self->check_filter(section => 'rcc', instance => $instance));
$self->{components}->{rcc}->{total}++;
$self->{output}->output_add(long_msg => sprintf("raid controller cache '%s' status is '%s' [instance: %s, state: %s].",
$result->{infoCacheName}, $result->{infoCacheStatus},
$instance, $result->{infoCacheState}
));
my $exit = $self->get_severity(label => 'default', section => 'rcc', value => $result->{infoCacheStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("raid controller cache '%s' state is '%s'",
$result->{infoCacheName}, $result->{infoCacheState}));
}
next if ($result->{infoCacheEnabled} != 1);
$self->{output}->output_add(long_msg => sprintf("bbu '%s' status is '%s' [instance: %s, state: %s].",
$result->{infoCacheName}, $result->{infoCacheBbuStatus},
$instance, $result->{infoCacheBbuState}
));
$exit = $self->get_severity(label => 'default', section => 'bbu', value => $result->{infoCacheBbuStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("bbu '%s' state is '%s'",
$result->{infoCacheName}, $result->{infoCacheBbuState}));
}
}
}
1; | nichols-356/centreon-plugins | storage/hp/lefthand/snmp/mode/components/rcc.pm | Perl | apache-2.0 | 4,069 |
#!/usr/bin/env perl
use strict;
use warnings;
use FindBin;
use lib ("$FindBin::Bin/../../PerlLib");
use Fastq_reader;
my $usage = "usage: $0 file.fastq\n\n";
my $fastq_file = $ARGV[0] or die $usage;
main: {
my $fastq_reader = new Fastq_reader($fastq_file);
my $tab_tmp_file = "$fastq_file.tab";
open (my $ofh, ">$tab_tmp_file") or die $!;
while (my $fq_entry = $fastq_reader->next()) {
my $fq_record = $fq_entry->get_fastq_record();
chomp $fq_record;
my @lines = split(/\n/, $fq_record);
print $ofh join("\t", @lines) . "\n";
}
close $ofh;
## sort by read name
my $cmd = "sort -S 4G -T . -k1,1 $tab_tmp_file > $tab_tmp_file.sort";
&process_cmd($cmd);
unlink($tab_tmp_file);
## convert back to fastq file format
$cmd = "cat $tab_tmp_file.sort | sed s/\\\\t/\\\\n/g > $fastq_file.sorted.fq";
&process_cmd($cmd);
unlink("$tab_tmp_file.sort");
exit(0);
}
####
sub process_cmd {
my ($cmd) = @_;
print STDERR "CMD: $cmd\n";
my $ret = system($cmd);
if ($ret) {
die "Error, cmd: $cmd died with ret $ret";
}
return;
}
| HPCHub/trinityrnaseq | util/misc/sort_fastq.pl | Perl | bsd-3-clause | 1,186 |
#------------------------------------------------------------------------------
# File: Ricoh.pm
#
# Description: Ricoh EXIF maker notes tags
#
# Revisions: 03/28/2005 - P. Harvey Created
#
# References: 1) http://www.ozhiker.com/electronics/pjmt/jpeg_info/ricoh_mn.html
# 2) http://homepage3.nifty.com/kamisaka/makernote/makernote_ricoh.htm
#------------------------------------------------------------------------------
package Image::ExifTool::Ricoh;
use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::Exif;
use Image::ExifTool::RIFF;
$VERSION = '1.07';
sub ProcessRicohText($$$);
sub ProcessRicohRMETA($$$);
%Image::ExifTool::Ricoh::Main = (
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
WRITE_PROC => \&Image::ExifTool::Exif::WriteExif,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
WRITABLE => 1,
NOTES => 'These tags are used by Ricoh Caplio camera models.',
0x0001 => { Name => 'MakerNoteType', Writable => 'string' },
0x0002 => { Name => 'MakerNoteVersion', Writable => 'string' },
0x0e00 => {
Name => 'PrintIM',
Writable => 0,
Description => 'Print Image Matching',
SubDirectory => {
TagTable => 'Image::ExifTool::PrintIM::Main',
},
},
0x1001 => {
Name => 'ImageInfo',
SubDirectory => {
TagTable => 'Image::ExifTool::Ricoh::ImageInfo',
},
},
0x1003 => {
Name => 'Sharpness',
Writable => 'int32u',
PrintConv => {
0 => 'Sharp',
1 => 'Normal',
2 => 'Soft',
},
},
0x2001 => [
{
Name => 'RicohSubdir',
Condition => '$self->{Model} !~ /^Caplio RR1\b/',
SubDirectory => {
Validate => '$val =~ /^\[Ricoh Camera Info\]/',
TagTable => 'Image::ExifTool::Ricoh::Subdir',
Start => '$valuePtr + 20',
ByteOrder => 'BigEndian',
},
},
{
Name => 'RicohRR1Subdir',
SubDirectory => {
Validate => '$val =~ /^\[Ricoh Camera Info\]/',
TagTable => 'Image::ExifTool::Ricoh::Subdir',
Start => '$valuePtr + 20',
ByteOrder => 'BigEndian',
# the Caplio RR1 uses a different base address -- doh!
Base => '$start-20',
},
},
],
);
# Ricoh image info (ref 2)
%Image::ExifTool::Ricoh::ImageInfo = (
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
PRIORITY => 0,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
IS_OFFSET => [ 28 ], # tag 28 is 'IsOffset'
0 => {
Name => 'RicohImageWidth',
Format => 'int16u',
},
2 => {
Name => 'RicohImageHeight',
Format => 'int16u',
},
6 => {
Name => 'RicohDate',
Groups => { 2 => 'Time' },
Format => 'int8u[7]',
# (what an insane way to encode the date)
ValueConv => q{
sprintf("%.2x%.2x:%.2x:%.2x %.2x:%.2x:%.2x",
split(' ', $val));
},
ValueConvInv => q{
my @vals = ($val =~ /(\d{1,2})/g);
push @vals, 0 if @vals < 7;
join(' ', map(hex, @vals));
},
},
28 => {
Name => 'PreviewImageStart',
Format => 'int16u',
Flags => 'IsOffset',
OffsetPair => 30, # associated byte count tagID
DataTag => 'PreviewImage',
Protected => 2,
},
30 => {
Name => 'PreviewImageLength',
Format => 'int16u',
OffsetPair => 28, # point to associated offset
DataTag => 'PreviewImage',
Protected => 2,
},
32 => {
Name => 'FlashMode',
PrintConv => {
0 => 'Off',
1 => 'Auto', #PH
2 => 'On',
},
},
33 => {
Name => 'Macro',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
34 => {
Name => 'Sharpness',
PrintConv => {
0 => 'Sharp',
1 => 'Normal',
2 => 'Soft',
},
},
38 => {
Name => 'WhiteBalance',
PrintConv => {
0 => 'Auto',
1 => 'Daylight',
2 => 'Cloudy',
3 => 'Tungsten',
4 => 'Fluorescent',
# 5 (One Pushes, flake setting?)
# 7 (details setting?)
},
},
39 => {
Name => 'ISOSetting',
PrintConv => {
0 => 'Auto',
1 => 64,
2 => 100,
4 => 200,
6 => 400,
7 => 800,
8 => 1600,
},
},
40 => {
Name => 'Saturation',
PrintConv => {
0 => 'High',
1 => 'Normal',
2 => 'Low',
3 => 'None (B&W)',
},
},
);
# NOTE: this subdir is not currently writable because the offsets would require
# special code to handle the funny start location and base offset
%Image::ExifTool::Ricoh::Subdir = (
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
WRITE_PROC => \&Image::ExifTool::Exif::WriteExif,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
0x0004 => { Name => 'RicohDateTime1', Groups => { 2 => 'Time' } }, #PH
0x0005 => { Name => 'RicohDateTime2', Groups => { 2 => 'Time' } }, #PH
# 0x000E ProductionNumber? (ref 2)
);
# Ricoh text-type maker notes (PH)
%Image::ExifTool::Ricoh::Text = (
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
PROCESS_PROC => \&ProcessRicohText,
NOTES => q{
Ricoh RDC models such as the RDC-i700, RDC-5000, RDC-6000, RDC-7 and
RDC-4300 use a text-based format for their maker notes instead of the IFD
format used by the Caplio models. Below is a list of known tags in this
information.
},
Rev => 'Revision',
Rv => 'Revision',
Rg => 'RedGain',
Gg => 'GreenGain',
Bg => 'BlueGain',
);
%Image::ExifTool::Ricoh::RMETA = (
GROUPS => { 0 => 'APP5', 1 => 'RMETA', 2 => 'Image' },
PROCESS_PROC => \&Image::ExifTool::Ricoh::ProcessRicohRMETA,
NOTES => q{
The Ricoh Caplio Pro G3 has the ability to add custom fields to the APP5
"RMETA" segment of JPEG images. While only a few observed tags have been
defined below, ExifTool will extract any information found here.
},
'Sign type' => { Name => 'SignType', PrintConv => {
1 => 'Directional',
2 => 'Warning',
3 => 'Information',
} },
Location => { PrintConv => {
1 => 'Verge',
2 => 'Gantry',
3 => 'Central reservation',
4 => 'Roundabout',
} },
Lit => { PrintConv => {
1 => 'Yes',
2 => 'No',
} },
Condition => { PrintConv => {
1 => 'Good',
2 => 'Fair',
3 => 'Poor',
4 => 'Damaged',
} },
Azimuth => { PrintConv => {
1 => 'N',
2 => 'NNE',
3 => 'NE',
4 => 'ENE',
5 => 'E',
6 => 'ESE',
7 => 'SE',
8 => 'SSE',
9 => 'S',
10 => 'SSW',
11 => 'SW',
12 => 'WSW',
13 => 'W',
14 => 'WNW',
15 => 'NW',
16 => 'NNW',
} },
);
# information stored in Ricoh AVI images (ref PH)
%Image::ExifTool::Ricoh::AVI = (
PROCESS_PROC => \&Image::ExifTool::RIFF::ProcessChunks,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
ucmt => {
Name => 'Comment',
ValueConv => '$_=$val; s/^Unicode//; tr/\0//d; s/\s+$//; $_',
},
mnrt => {
Name => 'MakerNoteRicoh',
SubDirectory => {
TagTable => 'Image::ExifTool::Ricoh::Main',
Start => '$valuePtr + 8',
ByteOrder => 'BigEndian',
Base => '8',
},
},
rdc2 => {
Name => 'RicohRDC2',
Unknown => 1,
ValueConv => 'unpack("H*",$val)',
# have seen values like 0a000444 and 00000000 - PH
},
thum => {
Name => 'ThumbnailImage',
Binary => 1,
},
);
#------------------------------------------------------------------------------
# Process Ricoh text-based maker notes
# Inputs: 0) ExifTool object reference
# 1) Reference to directory information hash
# 2) Pointer to tag table for this directory
# Returns: 1 on success, otherwise returns 0 and sets a Warning
sub ProcessRicohText($$$)
{
my ($exifTool, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $dataLen = $$dirInfo{DataLen};
my $dirStart = $$dirInfo{DirStart} || 0;
my $dirLen = $$dirInfo{DirLen} || $dataLen - $dirStart;
my $verbose = $exifTool->Options('Verbose');
my $data = substr($$dataPt, $dirStart, $dirLen);
return 1 if $data =~ /^\0/; # blank Ricoh maker notes
# validate text maker notes
unless ($data =~ /^(Rev|Rv)/) {
$exifTool->Warn('Bad Ricoh maker notes');
return 0;
}
my $pos = 0;
while ($data =~ m/([A-Z][a-z]{1,2})([0-9A-F]+);/sg) {
my $tag = $1;
my $val = $2;
my $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $tag);
if ($verbose) {
$exifTool->VerboseInfo($tag, $tagInfo,
Table => $tagTablePtr,
Value => $val,
);
}
unless ($tagInfo) {
next unless $exifTool->{OPTIONS}->{Unknown};
$tagInfo = {
Name => "Ricoh_Text_$tag",
Unknown => 1,
PrintConv => 'length($val) > 60 ? substr($val,0,55) . "[...]" : $val',
};
# add tag information to table
Image::ExifTool::AddTagToTable($tagTablePtr, $tag, $tagInfo);
}
$exifTool->FoundTag($tagInfo, $val);
}
return 1;
}
#------------------------------------------------------------------------------
# Process Ricoh APP5 RMETA information
# Inputs: 0) ExifTool object reference
# 1) Reference to directory information hash
# 2) Pointer to tag table for this directory
# Returns: 1 on success, otherwise returns 0 and sets a Warning
sub ProcessRicohRMETA($$$)
{
my ($exifTool, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $dirStart = $$dirInfo{DirStart};
my $dataLen = length($$dataPt);
my $verbose = $exifTool->Options('Verbose');
$dataLen > 6 or $exifTool->Warn('Truncated Ricoh RMETA data'), return 0;
my $byteOrder = substr($$dataPt, $dirStart, 2);
SetByteOrder($byteOrder) or $exifTool->Warn('Bad Ricoh RMETA data'), return 0;
my (@tags, @vals, @nums, $valPos);
my $pos = $dirStart + 6;
while ($pos <= $dataLen - 4) {
my $type = Get16u($dataPt, $pos);
my $size = Get16u($dataPt, $pos + 2);
$pos += 4;
$size -= 2;
if ($size < 0 or $pos + $size > $dataLen) {
$exifTool->Warn('Corrupted Ricoh RMETA data');
last;
}
if ($type eq 1) {
# save the tag names
my $tags = substr($$dataPt, $pos, $size);
$tags =~ s/\0+$//; # remove trailing nulls
@tags = split /\0/, $tags;
} elsif ($type eq 2) {
# save the ASCII tag values
my $vals = substr($$dataPt, $pos, $size);
$vals =~ s/\0+$//;
@vals = split /\0/, $vals;
$valPos = $pos; # save position of first ASCII value
} elsif ($type eq 3) {
# save the numerical tag values
my $nums = substr($$dataPt, $pos, $size);
@nums = unpack($byteOrder eq 'MM' ? 'n*' : 'v*', $nums);
} elsif ($type eq 0) {
$pos += 2; # why 2 extra bytes?
}
$pos += $size;
}
if (@tags or @vals) {
if (@tags != @vals) {
my ($nt, $nv) = (scalar(@tags), scalar(@vals));
$exifTool->Warn("Number of tags ($nt) and values ($nv) differs in Ricoh RMETA");
}
# find next tag in null-delimited list
# unpack numerical values from block of int16u values
my ($tag, $name, $val);
foreach $tag (@tags) {
$val = shift @vals;
last unless defined $val;
($name = $tag) =~ s/\b([a-z])/\U$1/gs; # make capitalize all words
$name =~ s/ (\w)/\U$1/g; # remove special characters
$name = 'RMETA_Unknown' unless length($name);
my $num = shift @nums;
my $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $tag);
if ($tagInfo) {
# make sure print conversion is defined
$$tagInfo{PrintConv} = { } unless $$tagInfo{PrintConv};
} else {
# create tagInfo hash
$tagInfo = { Name => $name, PrintConv => { } };
Image::ExifTool::AddTagToTable($tagTablePtr, $tag, $tagInfo);
}
# use string value directly if no numerical value
$num = $val unless defined $num;
# add conversion for this value (replacing any existing entry)
$tagInfo->{PrintConv}->{$num} = $val;
if ($verbose) {
$exifTool->VerboseInfo($tag, $tagInfo,
Table => $tagTablePtr,
Value => $num,
DataPt => $dataPt,
DataPos => $$dirInfo{DataPos},
Start => $valPos,
Size => length($val),
);
}
$exifTool->FoundTag($tagInfo, $num);
$valPos += length($val) + 1;
}
}
return 1;
}
1; # end
__END__
=head1 NAME
Image::ExifTool::Ricoh - Ricoh EXIF maker notes tags
=head1 SYNOPSIS
This module is loaded automatically by Image::ExifTool when required.
=head1 DESCRIPTION
This module contains definitions required by Image::ExifTool to
interpret Ricoh maker notes EXIF meta information.
=head1 AUTHOR
Copyright 2003-2009, Phil Harvey (phil at owl.phy.queensu.ca)
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 REFERENCES
=over 4
=item L<http://www.ozhiker.com/electronics/pjmt/jpeg_info/ricoh_mn.html>
=back
=head1 SEE ALSO
L<Image::ExifTool::TagNames/Ricoh Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| opf-attic/ref | tools/fits/0.6.1/tools/exiftool/perl/lib/Image/ExifTool/Ricoh.pm | Perl | apache-2.0 | 15,021 |
package Module::Build::Version;
use strict;
use vars qw($VERSION);
$VERSION = '0.87'; ### XXX sync with version of version.pm below
use version 0.87;
our @ISA = qw(version);
1;
=head1 NAME
Module::Build::Version - DEPRECATED
=head1 DESCRIPTION
Module::Build now lists L<version> as a C<configure_requires> dependency
and no longer installs a copy.
=cut
| Dokaponteam/ITF_Project | xampp/perl/lib/Module/Build/Version.pm | Perl | mit | 361 |
package Math::BigInt;
#
# "Mike had an infinite amount to do and a negative amount of time in which
# to do it." - Before and After
#
# The following hash values are used:
# value: unsigned int with actual value (as a Math::BigInt::Calc or similiar)
# sign : +,-,NaN,+inf,-inf
# _a : accuracy
# _p : precision
# _f : flags, used by MBF to flag parts of a float as untouchable
# Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
# underlying lib might change the reference!
my $class = "Math::BigInt";
use 5.006;
$VERSION = '1.89';
@ISA = qw(Exporter);
@EXPORT_OK = qw(objectify bgcd blcm);
# _trap_inf and _trap_nan are internal and should never be accessed from the
# outside
use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode
$upgrade $downgrade $_trap_nan $_trap_inf/;
use strict;
# Inside overload, the first arg is always an object. If the original code had
# it reversed (like $x = 2 * $y), then the third paramater is true.
# In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes
# no difference, but in some cases it does.
# For overloaded ops with only one argument we simple use $_[0]->copy() to
# preserve the argument.
# Thus inheritance of overload operators becomes possible and transparent for
# our subclasses without the need to repeat the entire overload section there.
use overload
'=' => sub { $_[0]->copy(); },
# some shortcuts for speed (assumes that reversed order of arguments is routed
# to normal '+' and we thus can always modify first arg. If this is changed,
# this breaks and must be adjusted.)
'+=' => sub { $_[0]->badd($_[1]); },
'-=' => sub { $_[0]->bsub($_[1]); },
'*=' => sub { $_[0]->bmul($_[1]); },
'/=' => sub { scalar $_[0]->bdiv($_[1]); },
'%=' => sub { $_[0]->bmod($_[1]); },
'^=' => sub { $_[0]->bxor($_[1]); },
'&=' => sub { $_[0]->band($_[1]); },
'|=' => sub { $_[0]->bior($_[1]); },
'**=' => sub { $_[0]->bpow($_[1]); },
'<<=' => sub { $_[0]->blsft($_[1]); },
'>>=' => sub { $_[0]->brsft($_[1]); },
# not supported by Perl yet
'..' => \&_pointpoint,
'<=>' => sub { my $rc = $_[2] ?
ref($_[0])->bcmp($_[1],$_[0]) :
$_[0]->bcmp($_[1]);
$rc = 1 unless defined $rc;
$rc <=> 0;
},
# we need '>=' to get things like "1 >= NaN" right:
'>=' => sub { my $rc = $_[2] ?
ref($_[0])->bcmp($_[1],$_[0]) :
$_[0]->bcmp($_[1]);
# if there was a NaN involved, return false
return '' unless defined $rc;
$rc >= 0;
},
'cmp' => sub {
$_[2] ?
"$_[1]" cmp $_[0]->bstr() :
$_[0]->bstr() cmp "$_[1]" },
'cos' => sub { $_[0]->copy->bcos(); },
'sin' => sub { $_[0]->copy->bsin(); },
'atan2' => sub { $_[2] ?
ref($_[0])->new($_[1])->batan2($_[0]) :
$_[0]->copy()->batan2($_[1]) },
# are not yet overloadable
#'hex' => sub { print "hex"; $_[0]; },
#'oct' => sub { print "oct"; $_[0]; },
# log(N) is log(N, e), where e is Euler's number
'log' => sub { $_[0]->copy()->blog($_[1], undef); },
'exp' => sub { $_[0]->copy()->bexp($_[1]); },
'int' => sub { $_[0]->copy(); },
'neg' => sub { $_[0]->copy()->bneg(); },
'abs' => sub { $_[0]->copy()->babs(); },
'sqrt' => sub { $_[0]->copy()->bsqrt(); },
'~' => sub { $_[0]->copy()->bnot(); },
# for subtract it's a bit tricky to not modify b: b-a => -a+b
'-' => sub { my $c = $_[0]->copy; $_[2] ?
$c->bneg()->badd( $_[1]) :
$c->bsub( $_[1]) },
'+' => sub { $_[0]->copy()->badd($_[1]); },
'*' => sub { $_[0]->copy()->bmul($_[1]); },
'/' => sub {
$_[2] ? ref($_[0])->new($_[1])->bdiv($_[0]) : $_[0]->copy->bdiv($_[1]);
},
'%' => sub {
$_[2] ? ref($_[0])->new($_[1])->bmod($_[0]) : $_[0]->copy->bmod($_[1]);
},
'**' => sub {
$_[2] ? ref($_[0])->new($_[1])->bpow($_[0]) : $_[0]->copy->bpow($_[1]);
},
'<<' => sub {
$_[2] ? ref($_[0])->new($_[1])->blsft($_[0]) : $_[0]->copy->blsft($_[1]);
},
'>>' => sub {
$_[2] ? ref($_[0])->new($_[1])->brsft($_[0]) : $_[0]->copy->brsft($_[1]);
},
'&' => sub {
$_[2] ? ref($_[0])->new($_[1])->band($_[0]) : $_[0]->copy->band($_[1]);
},
'|' => sub {
$_[2] ? ref($_[0])->new($_[1])->bior($_[0]) : $_[0]->copy->bior($_[1]);
},
'^' => sub {
$_[2] ? ref($_[0])->new($_[1])->bxor($_[0]) : $_[0]->copy->bxor($_[1]);
},
# can modify arg of ++ and --, so avoid a copy() for speed, but don't
# use $_[0]->bone(), it would modify $_[0] to be 1!
'++' => sub { $_[0]->binc() },
'--' => sub { $_[0]->bdec() },
# if overloaded, O(1) instead of O(N) and twice as fast for small numbers
'bool' => sub {
# this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
# v5.6.1 dumps on this: return !$_[0]->is_zero() || undef; :-(
my $t = undef;
$t = 1 if !$_[0]->is_zero();
$t;
},
# the original qw() does not work with the TIESCALAR below, why?
# Order of arguments unsignificant
'""' => sub { $_[0]->bstr(); },
'0+' => sub { $_[0]->numify(); }
;
##############################################################################
# global constants, flags and accessory
# These vars are public, but their direct usage is not recommended, use the
# accessor methods instead
$round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
$accuracy = undef;
$precision = undef;
$div_scale = 40;
$upgrade = undef; # default is no upgrade
$downgrade = undef; # default is no downgrade
# These are internally, and not to be used from the outside at all
$_trap_nan = 0; # are NaNs ok? set w/ config()
$_trap_inf = 0; # are infs ok? set w/ config()
my $nan = 'NaN'; # constants for easier life
my $CALC = 'Math::BigInt::FastCalc'; # module to do the low level math
# default is FastCalc.pm
my $IMPORT = 0; # was import() called yet?
# used to make require work
my %WARN; # warn only once for low-level libs
my %CAN; # cache for $CALC->can(...)
my %CALLBACKS; # callbacks to notify on lib loads
my $EMU_LIB = 'Math/BigInt/CalcEmu.pm'; # emulate low-level math
##############################################################################
# the old code had $rnd_mode, so we need to support it, too
$rnd_mode = 'even';
sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
sub FETCH { return $round_mode; }
sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
BEGIN
{
# tie to enable $rnd_mode to work transparently
tie $rnd_mode, 'Math::BigInt';
# set up some handy alias names
*as_int = \&as_number;
*is_pos = \&is_positive;
*is_neg = \&is_negative;
}
##############################################################################
sub round_mode
{
no strict 'refs';
# make Class->round_mode() work
my $self = shift;
my $class = ref($self) || $self || __PACKAGE__;
if (defined $_[0])
{
my $m = shift;
if ($m !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
{
require Carp; Carp::croak ("Unknown round mode '$m'");
}
return ${"${class}::round_mode"} = $m;
}
${"${class}::round_mode"};
}
sub upgrade
{
no strict 'refs';
# make Class->upgrade() work
my $self = shift;
my $class = ref($self) || $self || __PACKAGE__;
# need to set new value?
if (@_ > 0)
{
return ${"${class}::upgrade"} = $_[0];
}
${"${class}::upgrade"};
}
sub downgrade
{
no strict 'refs';
# make Class->downgrade() work
my $self = shift;
my $class = ref($self) || $self || __PACKAGE__;
# need to set new value?
if (@_ > 0)
{
return ${"${class}::downgrade"} = $_[0];
}
${"${class}::downgrade"};
}
sub div_scale
{
no strict 'refs';
# make Class->div_scale() work
my $self = shift;
my $class = ref($self) || $self || __PACKAGE__;
if (defined $_[0])
{
if ($_[0] < 0)
{
require Carp; Carp::croak ('div_scale must be greater than zero');
}
${"${class}::div_scale"} = $_[0];
}
${"${class}::div_scale"};
}
sub accuracy
{
# $x->accuracy($a); ref($x) $a
# $x->accuracy(); ref($x)
# Class->accuracy(); class
# Class->accuracy($a); class $a
my $x = shift;
my $class = ref($x) || $x || __PACKAGE__;
no strict 'refs';
# need to set new value?
if (@_ > 0)
{
my $a = shift;
# convert objects to scalars to avoid deep recursion. If object doesn't
# have numify(), then hopefully it will have overloading for int() and
# boolean test without wandering into a deep recursion path...
$a = $a->numify() if ref($a) && $a->can('numify');
if (defined $a)
{
# also croak on non-numerical
if (!$a || $a <= 0)
{
require Carp;
Carp::croak ('Argument to accuracy must be greater than zero');
}
if (int($a) != $a)
{
require Carp;
Carp::croak ('Argument to accuracy must be an integer');
}
}
if (ref($x))
{
# $object->accuracy() or fallback to global
$x->bround($a) if $a; # not for undef, 0
$x->{_a} = $a; # set/overwrite, even if not rounded
delete $x->{_p}; # clear P
$a = ${"${class}::accuracy"} unless defined $a; # proper return value
}
else
{
${"${class}::accuracy"} = $a; # set global A
${"${class}::precision"} = undef; # clear global P
}
return $a; # shortcut
}
my $a;
# $object->accuracy() or fallback to global
$a = $x->{_a} if ref($x);
# but don't return global undef, when $x's accuracy is 0!
$a = ${"${class}::accuracy"} if !defined $a;
$a;
}
sub precision
{
# $x->precision($p); ref($x) $p
# $x->precision(); ref($x)
# Class->precision(); class
# Class->precision($p); class $p
my $x = shift;
my $class = ref($x) || $x || __PACKAGE__;
no strict 'refs';
if (@_ > 0)
{
my $p = shift;
# convert objects to scalars to avoid deep recursion. If object doesn't
# have numify(), then hopefully it will have overloading for int() and
# boolean test without wandering into a deep recursion path...
$p = $p->numify() if ref($p) && $p->can('numify');
if ((defined $p) && (int($p) != $p))
{
require Carp; Carp::croak ('Argument to precision must be an integer');
}
if (ref($x))
{
# $object->precision() or fallback to global
$x->bfround($p) if $p; # not for undef, 0
$x->{_p} = $p; # set/overwrite, even if not rounded
delete $x->{_a}; # clear A
$p = ${"${class}::precision"} unless defined $p; # proper return value
}
else
{
${"${class}::precision"} = $p; # set global P
${"${class}::accuracy"} = undef; # clear global A
}
return $p; # shortcut
}
my $p;
# $object->precision() or fallback to global
$p = $x->{_p} if ref($x);
# but don't return global undef, when $x's precision is 0!
$p = ${"${class}::precision"} if !defined $p;
$p;
}
sub config
{
# return (or set) configuration data as hash ref
my $class = shift || 'Math::BigInt';
no strict 'refs';
if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH')))
{
# try to set given options as arguments from hash
my $args = $_[0];
if (ref($args) ne 'HASH')
{
$args = { @_ };
}
# these values can be "set"
my $set_args = {};
foreach my $key (
qw/trap_inf trap_nan
upgrade downgrade precision accuracy round_mode div_scale/
)
{
$set_args->{$key} = $args->{$key} if exists $args->{$key};
delete $args->{$key};
}
if (keys %$args > 0)
{
require Carp;
Carp::croak ("Illegal key(s) '",
join("','",keys %$args),"' passed to $class\->config()");
}
foreach my $key (keys %$set_args)
{
if ($key =~ /^trap_(inf|nan)\z/)
{
${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0);
next;
}
# use a call instead of just setting the $variable to check argument
$class->$key($set_args->{$key});
}
}
# now return actual configuration
my $cfg = {
lib => $CALC,
lib_version => ${"${CALC}::VERSION"},
class => $class,
trap_nan => ${"${class}::_trap_nan"},
trap_inf => ${"${class}::_trap_inf"},
version => ${"${class}::VERSION"},
};
foreach my $key (qw/
upgrade downgrade precision accuracy round_mode div_scale
/)
{
$cfg->{$key} = ${"${class}::$key"};
};
if (@_ == 1 && (ref($_[0]) ne 'HASH'))
{
# calls of the style config('lib') return just this value
return $cfg->{$_[0]};
}
$cfg;
}
sub _scale_a
{
# select accuracy parameter based on precedence,
# used by bround() and bfround(), may return undef for scale (means no op)
my ($x,$scale,$mode) = @_;
$scale = $x->{_a} unless defined $scale;
no strict 'refs';
my $class = ref($x);
$scale = ${ $class . '::accuracy' } unless defined $scale;
$mode = ${ $class . '::round_mode' } unless defined $mode;
if (defined $scale)
{
$scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale);
$scale = int($scale);
}
($scale,$mode);
}
sub _scale_p
{
# select precision parameter based on precedence,
# used by bround() and bfround(), may return undef for scale (means no op)
my ($x,$scale,$mode) = @_;
$scale = $x->{_p} unless defined $scale;
no strict 'refs';
my $class = ref($x);
$scale = ${ $class . '::precision' } unless defined $scale;
$mode = ${ $class . '::round_mode' } unless defined $mode;
if (defined $scale)
{
$scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale);
$scale = int($scale);
}
($scale,$mode);
}
##############################################################################
# constructors
sub copy
{
# if two arguments, the first one is the class to "swallow" subclasses
if (@_ > 1)
{
my $self = bless {
sign => $_[1]->{sign},
value => $CALC->_copy($_[1]->{value}),
}, $_[0] if @_ > 1;
$self->{_a} = $_[1]->{_a} if defined $_[1]->{_a};
$self->{_p} = $_[1]->{_p} if defined $_[1]->{_p};
return $self;
}
my $self = bless {
sign => $_[0]->{sign},
value => $CALC->_copy($_[0]->{value}),
}, ref($_[0]);
$self->{_a} = $_[0]->{_a} if defined $_[0]->{_a};
$self->{_p} = $_[0]->{_p} if defined $_[0]->{_p};
$self;
}
sub new
{
# create a new BigInt object from a string or another BigInt object.
# see hash keys documented at top
# the argument could be an object, so avoid ||, && etc on it, this would
# cause costly overloaded code to be called. The only allowed ops are
# ref() and defined.
my ($class,$wanted,$a,$p,$r) = @_;
# avoid numify-calls by not using || on $wanted!
return $class->bzero($a,$p) if !defined $wanted; # default to 0
return $class->copy($wanted,$a,$p,$r)
if ref($wanted) && $wanted->isa($class); # MBI or subclass
$class->import() if $IMPORT == 0; # make require work
my $self = bless {}, $class;
# shortcut for "normal" numbers
if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*\z/))
{
$self->{sign} = $1 || '+';
if ($wanted =~ /^[+-]/)
{
# remove sign without touching wanted to make it work with constants
my $t = $wanted; $t =~ s/^[+-]//;
$self->{value} = $CALC->_new($t);
}
else
{
$self->{value} = $CALC->_new($wanted);
}
no strict 'refs';
if ( (defined $a) || (defined $p)
|| (defined ${"${class}::precision"})
|| (defined ${"${class}::accuracy"})
)
{
$self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
}
return $self;
}
# handle '+inf', '-inf' first
if ($wanted =~ /^[+-]?inf\z/)
{
$self->{sign} = $wanted; # set a default sign for bstr()
return $self->binf($wanted);
}
# split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
my ($mis,$miv,$mfv,$es,$ev) = _split($wanted);
if (!ref $mis)
{
if ($_trap_nan)
{
require Carp; Carp::croak("$wanted is not a number in $class");
}
$self->{value} = $CALC->_zero();
$self->{sign} = $nan;
return $self;
}
if (!ref $miv)
{
# _from_hex or _from_bin
$self->{value} = $mis->{value};
$self->{sign} = $mis->{sign};
return $self; # throw away $mis
}
# make integer from mantissa by adjusting exp, then convert to bigint
$self->{sign} = $$mis; # store sign
$self->{value} = $CALC->_zero(); # for all the NaN cases
my $e = int("$$es$$ev"); # exponent (avoid recursion)
if ($e > 0)
{
my $diff = $e - CORE::length($$mfv);
if ($diff < 0) # Not integer
{
if ($_trap_nan)
{
require Carp; Carp::croak("$wanted not an integer in $class");
}
#print "NOI 1\n";
return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
$self->{sign} = $nan;
}
else # diff >= 0
{
# adjust fraction and add it to value
#print "diff > 0 $$miv\n";
$$miv = $$miv . ($$mfv . '0' x $diff);
}
}
else
{
if ($$mfv ne '') # e <= 0
{
# fraction and negative/zero E => NOI
if ($_trap_nan)
{
require Carp; Carp::croak("$wanted not an integer in $class");
}
#print "NOI 2 \$\$mfv '$$mfv'\n";
return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
$self->{sign} = $nan;
}
elsif ($e < 0)
{
# xE-y, and empty mfv
#print "xE-y\n";
$e = abs($e);
if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
{
if ($_trap_nan)
{
require Carp; Carp::croak("$wanted not an integer in $class");
}
#print "NOI 3\n";
return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
$self->{sign} = $nan;
}
}
}
$self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
$self->{value} = $CALC->_new($$miv) if $self->{sign} =~ /^[+-]$/;
# if any of the globals is set, use them to round and store them inside $self
# do not round for new($x,undef,undef) since that is used by MBF to signal
# no rounding
$self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
$self;
}
sub bnan
{
# create a bigint 'NaN', if given a BigInt, set it to 'NaN'
my $self = shift;
$self = $class if !defined $self;
if (!ref($self))
{
my $c = $self; $self = {}; bless $self, $c;
}
no strict 'refs';
if (${"${class}::_trap_nan"})
{
require Carp;
Carp::croak ("Tried to set $self to NaN in $class\::bnan()");
}
$self->import() if $IMPORT == 0; # make require work
return if $self->modify('bnan');
if ($self->can('_bnan'))
{
# use subclass to initialize
$self->_bnan();
}
else
{
# otherwise do our own thing
$self->{value} = $CALC->_zero();
}
$self->{sign} = $nan;
delete $self->{_a}; delete $self->{_p}; # rounding NaN is silly
$self;
}
sub binf
{
# create a bigint '+-inf', if given a BigInt, set it to '+-inf'
# the sign is either '+', or if given, used from there
my $self = shift;
my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
$self = $class if !defined $self;
if (!ref($self))
{
my $c = $self; $self = {}; bless $self, $c;
}
no strict 'refs';
if (${"${class}::_trap_inf"})
{
require Carp;
Carp::croak ("Tried to set $self to +-inf in $class\::binf()");
}
$self->import() if $IMPORT == 0; # make require work
return if $self->modify('binf');
if ($self->can('_binf'))
{
# use subclass to initialize
$self->_binf();
}
else
{
# otherwise do our own thing
$self->{value} = $CALC->_zero();
}
$sign = $sign . 'inf' if $sign !~ /inf$/; # - => -inf
$self->{sign} = $sign;
($self->{_a},$self->{_p}) = @_; # take over requested rounding
$self;
}
sub bzero
{
# create a bigint '+0', if given a BigInt, set it to 0
my $self = shift;
$self = __PACKAGE__ if !defined $self;
if (!ref($self))
{
my $c = $self; $self = {}; bless $self, $c;
}
$self->import() if $IMPORT == 0; # make require work
return if $self->modify('bzero');
if ($self->can('_bzero'))
{
# use subclass to initialize
$self->_bzero();
}
else
{
# otherwise do our own thing
$self->{value} = $CALC->_zero();
}
$self->{sign} = '+';
if (@_ > 0)
{
if (@_ > 3)
{
# call like: $x->bzero($a,$p,$r,$y);
($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
}
else
{
$self->{_a} = $_[0]
if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
$self->{_p} = $_[1]
if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
}
}
$self;
}
sub bone
{
# create a bigint '+1' (or -1 if given sign '-'),
# if given a BigInt, set it to +1 or -1, respectively
my $self = shift;
my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
$self = $class if !defined $self;
if (!ref($self))
{
my $c = $self; $self = {}; bless $self, $c;
}
$self->import() if $IMPORT == 0; # make require work
return if $self->modify('bone');
if ($self->can('_bone'))
{
# use subclass to initialize
$self->_bone();
}
else
{
# otherwise do our own thing
$self->{value} = $CALC->_one();
}
$self->{sign} = $sign;
if (@_ > 0)
{
if (@_ > 3)
{
# call like: $x->bone($sign,$a,$p,$r,$y);
($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
}
else
{
# call like: $x->bone($sign,$a,$p,$r);
$self->{_a} = $_[0]
if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
$self->{_p} = $_[1]
if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
}
}
$self;
}
##############################################################################
# string conversation
sub bsstr
{
# (ref to BFLOAT or num_str ) return num_str
# Convert number from internal format to scientific string format.
# internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
if ($x->{sign} !~ /^[+-]$/)
{
return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
return 'inf'; # +inf
}
my ($m,$e) = $x->parts();
#$m->bstr() . 'e+' . $e->bstr(); # e can only be positive in BigInt
# 'e+' because E can only be positive in BigInt
$m->bstr() . 'e+' . $CALC->_str($e->{value});
}
sub bstr
{
# make a string from bigint object
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
if ($x->{sign} !~ /^[+-]$/)
{
return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
return 'inf'; # +inf
}
my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
$es.$CALC->_str($x->{value});
}
sub numify
{
# Make a "normal" scalar from a BigInt object
my $x = shift; $x = $class->new($x) unless ref $x;
return $x->bstr() if $x->{sign} !~ /^[+-]$/;
my $num = $CALC->_num($x->{value});
return -$num if $x->{sign} eq '-';
$num;
}
##############################################################################
# public stuff (usually prefixed with "b")
sub sign
{
# return the sign of the number: +/-/-inf/+inf/NaN
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
$x->{sign};
}
sub _find_round_parameters
{
# After any operation or when calling round(), the result is rounded by
# regarding the A & P from arguments, local parameters, or globals.
# !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!!
# This procedure finds the round parameters, but it is for speed reasons
# duplicated in round. Otherwise, it is tested by the testsuite and used
# by fdiv().
# returns ($self) or ($self,$a,$p,$r) - sets $self to NaN of both A and P
# were requested/defined (locally or globally or both)
my ($self,$a,$p,$r,@args) = @_;
# $a accuracy, if given by caller
# $p precision, if given by caller
# $r round_mode, if given by caller
# @args all 'other' arguments (0 for unary, 1 for binary ops)
my $c = ref($self); # find out class of argument(s)
no strict 'refs';
# convert to normal scalar for speed and correctness in inner parts
$a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a);
$p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p);
# now pick $a or $p, but only if we have got "arguments"
if (!defined $a)
{
foreach ($self,@args)
{
# take the defined one, or if both defined, the one that is smaller
$a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
}
}
if (!defined $p)
{
# even if $a is defined, take $p, to signal error for both defined
foreach ($self,@args)
{
# take the defined one, or if both defined, the one that is bigger
# -2 > -3, and 3 > 2
$p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
}
}
# if still none defined, use globals (#2)
$a = ${"$c\::accuracy"} unless defined $a;
$p = ${"$c\::precision"} unless defined $p;
# A == 0 is useless, so undef it to signal no rounding
$a = undef if defined $a && $a == 0;
# no rounding today?
return ($self) unless defined $a || defined $p; # early out
# set A and set P is an fatal error
return ($self->bnan()) if defined $a && defined $p; # error
$r = ${"$c\::round_mode"} unless defined $r;
if ($r !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
{
require Carp; Carp::croak ("Unknown round mode '$r'");
}
$a = int($a) if defined $a;
$p = int($p) if defined $p;
($self,$a,$p,$r);
}
sub round
{
# Round $self according to given parameters, or given second argument's
# parameters or global defaults
# for speed reasons, _find_round_parameters is embeded here:
my ($self,$a,$p,$r,@args) = @_;
# $a accuracy, if given by caller
# $p precision, if given by caller
# $r round_mode, if given by caller
# @args all 'other' arguments (0 for unary, 1 for binary ops)
my $c = ref($self); # find out class of argument(s)
no strict 'refs';
# now pick $a or $p, but only if we have got "arguments"
if (!defined $a)
{
foreach ($self,@args)
{
# take the defined one, or if both defined, the one that is smaller
$a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
}
}
if (!defined $p)
{
# even if $a is defined, take $p, to signal error for both defined
foreach ($self,@args)
{
# take the defined one, or if both defined, the one that is bigger
# -2 > -3, and 3 > 2
$p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
}
}
# if still none defined, use globals (#2)
$a = ${"$c\::accuracy"} unless defined $a;
$p = ${"$c\::precision"} unless defined $p;
# A == 0 is useless, so undef it to signal no rounding
$a = undef if defined $a && $a == 0;
# no rounding today?
return $self unless defined $a || defined $p; # early out
# set A and set P is an fatal error
return $self->bnan() if defined $a && defined $p;
$r = ${"$c\::round_mode"} unless defined $r;
if ($r !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
{
require Carp; Carp::croak ("Unknown round mode '$r'");
}
# now round, by calling either fround or ffround:
if (defined $a)
{
$self->bround(int($a),$r) if !defined $self->{_a} || $self->{_a} >= $a;
}
else # both can't be undefined due to early out
{
$self->bfround(int($p),$r) if !defined $self->{_p} || $self->{_p} <= $p;
}
# bround() or bfround() already callled bnorm() if nec.
$self;
}
sub bnorm
{
# (numstr or BINT) return BINT
# Normalize number -- no-op here
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
$x;
}
sub babs
{
# (BINT or num_str) return BINT
# make number absolute, or return absolute BINT from string
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return $x if $x->modify('babs');
# post-normalized abs for internal use (does nothing for NaN)
$x->{sign} =~ s/^-/+/;
$x;
}
sub bneg
{
# (BINT or num_str) return BINT
# negate number or make a negated number from string
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return $x if $x->modify('bneg');
# for +0 dont negate (to have always normalized +0). Does nothing for 'NaN'
$x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $CALC->_is_zero($x->{value}));
$x;
}
sub bcmp
{
# Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
# (BINT or num_str, BINT or num_str) return cond_code
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y) = objectify(2,@_);
}
return $upgrade->bcmp($x,$y) if defined $upgrade &&
((!$x->isa($self)) || (!$y->isa($self)));
if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
{
# handle +-inf and NaN
return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
return +1 if $x->{sign} eq '+inf';
return -1 if $x->{sign} eq '-inf';
return -1 if $y->{sign} eq '+inf';
return +1;
}
# check sign for speed first
return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
# have same sign, so compare absolute values. Don't make tests for zero here
# because it's actually slower than testin in Calc (especially w/ Pari et al)
# post-normalized compare for internal use (honors signs)
if ($x->{sign} eq '+')
{
# $x and $y both > 0
return $CALC->_acmp($x->{value},$y->{value});
}
# $x && $y both < 0
$CALC->_acmp($y->{value},$x->{value}); # swaped acmp (lib returns 0,1,-1)
}
sub bacmp
{
# Compares 2 values, ignoring their signs.
# Returns one of undef, <0, =0, >0. (suitable for sort)
# (BINT, BINT) return cond_code
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y) = objectify(2,@_);
}
return $upgrade->bacmp($x,$y) if defined $upgrade &&
((!$x->isa($self)) || (!$y->isa($self)));
if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
{
# handle +-inf and NaN
return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/;
return -1;
}
$CALC->_acmp($x->{value},$y->{value}); # lib does only 0,1,-1
}
sub badd
{
# add second arg (BINT or string) to first (BINT) (modifies first)
# return result as BINT
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('badd');
return $upgrade->badd($upgrade->new($x),$upgrade->new($y),@r) if defined $upgrade &&
((!$x->isa($self)) || (!$y->isa($self)));
$r[3] = $y; # no push!
# inf and NaN handling
if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
{
# NaN first
return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
# inf handling
if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
{
# +inf++inf or -inf+-inf => same, rest is NaN
return $x if $x->{sign} eq $y->{sign};
return $x->bnan();
}
# +-inf + something => +inf
# something +-inf => +-inf
$x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
return $x;
}
my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
if ($sx eq $sy)
{
$x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
}
else
{
my $a = $CALC->_acmp ($y->{value},$x->{value}); # absolute compare
if ($a > 0)
{
$x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
$x->{sign} = $sy;
}
elsif ($a == 0)
{
# speedup, if equal, set result to 0
$x->{value} = $CALC->_zero();
$x->{sign} = '+';
}
else # a < 0
{
$x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
}
}
$x->round(@r);
}
sub bsub
{
# (BINT or num_str, BINT or num_str) return BINT
# subtract second arg from first, modify first
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bsub');
return $upgrade->new($x)->bsub($upgrade->new($y),@r) if defined $upgrade &&
((!$x->isa($self)) || (!$y->isa($self)));
return $x->round(@r) if $y->is_zero();
# To correctly handle the lone special case $x->bsub($x), we note the sign
# of $x, then flip the sign from $y, and if the sign of $x did change, too,
# then we caught the special case:
my $xsign = $x->{sign};
$y->{sign} =~ tr/+\-/-+/; # does nothing for NaN
if ($xsign ne $x->{sign})
{
# special case of $x->bsub($x) results in 0
return $x->bzero(@r) if $xsign =~ /^[+-]$/;
return $x->bnan(); # NaN, -inf, +inf
}
$x->badd($y,@r); # badd does not leave internal zeros
$y->{sign} =~ tr/+\-/-+/; # refix $y (does nothing for NaN)
$x; # already rounded by badd() or no round nec.
}
sub binc
{
# increment arg by one
my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
return $x if $x->modify('binc');
if ($x->{sign} eq '+')
{
$x->{value} = $CALC->_inc($x->{value});
return $x->round($a,$p,$r);
}
elsif ($x->{sign} eq '-')
{
$x->{value} = $CALC->_dec($x->{value});
$x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
return $x->round($a,$p,$r);
}
# inf, nan handling etc
$x->badd($self->bone(),$a,$p,$r); # badd does round
}
sub bdec
{
# decrement arg by one
my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
return $x if $x->modify('bdec');
if ($x->{sign} eq '-')
{
# x already < 0
$x->{value} = $CALC->_inc($x->{value});
}
else
{
return $x->badd($self->bone('-'),@r) unless $x->{sign} eq '+'; # inf or NaN
# >= 0
if ($CALC->_is_zero($x->{value}))
{
# == 0
$x->{value} = $CALC->_one(); $x->{sign} = '-'; # 0 => -1
}
else
{
# > 0
$x->{value} = $CALC->_dec($x->{value});
}
}
$x->round(@r);
}
sub blog
{
# calculate $x = $a ** $base + $b and return $a (e.g. the log() to base
# $base of $x)
# set up parameters
my ($self,$x,$base,@r) = (undef,@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$base,@r) = objectify(1,ref($x),@_);
}
return $x if $x->modify('blog');
$base = $self->new($base) if defined $base && !ref $base;
# inf, -inf, NaN, <0 => NaN
return $x->bnan()
if $x->{sign} ne '+' || (defined $base && $base->{sign} ne '+');
return $upgrade->blog($upgrade->new($x),$base,@r) if
defined $upgrade;
# fix for bug #24969:
# the default base is e (Euler's number) which is not an integer
if (!defined $base)
{
require Math::BigFloat;
my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int();
# modify $x in place
$x->{value} = $u->{value};
$x->{sign} = $u->{sign};
return $x;
}
my ($rc,$exact) = $CALC->_log_int($x->{value},$base->{value});
return $x->bnan() unless defined $rc; # not possible to take log?
$x->{value} = $rc;
$x->round(@r);
}
sub bnok
{
# Calculate n over k (binomial coefficient or "choose" function) as integer.
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bnok');
return $x->bnan() if $x->{sign} eq 'NaN' || $y->{sign} eq 'NaN';
return $x->binf() if $x->{sign} eq '+inf';
# k > n or k < 0 => 0
my $cmp = $x->bacmp($y);
return $x->bzero() if $cmp < 0 || $y->{sign} =~ /^-/;
# k == n => 1
return $x->bone(@r) if $cmp == 0;
if ($CALC->can('_nok'))
{
$x->{value} = $CALC->_nok($x->{value},$y->{value});
}
else
{
# ( 7 ) 7! 7*6*5 * 4*3*2*1 7 * 6 * 5
# ( - ) = --------- = --------------- = ---------
# ( 3 ) 3! (7-3)! 3*2*1 * 4*3*2*1 3 * 2 * 1
# compute n - k + 2 (so we start with 5 in the example above)
my $z = $x - $y;
if (!$z->is_one())
{
$z->binc();
my $r = $z->copy(); $z->binc();
my $d = $self->new(2);
while ($z->bacmp($x) <= 0) # f < x ?
{
$r->bmul($z); $r->bdiv($d);
$z->binc(); $d->binc();
}
$x->{value} = $r->{value}; $x->{sign} = '+';
}
else { $x->bone(); }
}
$x->round(@r);
}
sub bexp
{
# Calculate e ** $x (Euler's number to the power of X), truncated to
# an integer value.
my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
return $x if $x->modify('bexp');
# inf, -inf, NaN, <0 => NaN
return $x->bnan() if $x->{sign} eq 'NaN';
return $x->bone() if $x->is_zero();
return $x if $x->{sign} eq '+inf';
return $x->bzero() if $x->{sign} eq '-inf';
my $u;
{
# run through Math::BigFloat unless told otherwise
require Math::BigFloat unless defined $upgrade;
local $upgrade = 'Math::BigFloat' unless defined $upgrade;
# calculate result, truncate it to integer
$u = $upgrade->bexp($upgrade->new($x),@r);
}
if (!defined $upgrade)
{
$u = $u->as_int();
# modify $x in place
$x->{value} = $u->{value};
$x->round(@r);
}
else { $x = $u; }
}
sub blcm
{
# (BINT or num_str, BINT or num_str) return BINT
# does not modify arguments, but returns new object
# Lowest Common Multiplicator
my $y = shift; my ($x);
if (ref($y))
{
$x = $y->copy();
}
else
{
$x = $class->new($y);
}
my $self = ref($x);
while (@_)
{
my $y = shift; $y = $self->new($y) if !ref ($y);
$x = __lcm($x,$y);
}
$x;
}
sub bgcd
{
# (BINT or num_str, BINT or num_str) return BINT
# does not modify arguments, but returns new object
# GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
my $y = shift;
$y = $class->new($y) if !ref($y);
my $self = ref($y);
my $x = $y->copy()->babs(); # keep arguments
return $x->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN?
while (@_)
{
$y = shift; $y = $self->new($y) if !ref($y);
return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
$x->{value} = $CALC->_gcd($x->{value},$y->{value});
last if $CALC->_is_one($x->{value});
}
$x;
}
sub bnot
{
# (num_str or BINT) return BINT
# represent ~x as twos-complement number
# we don't need $self, so undef instead of ref($_[0]) make it slightly faster
my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('bnot');
$x->binc()->bneg(); # binc already does round
}
##############################################################################
# is_foo test routines
# we don't need $self, so undef instead of ref($_[0]) make it slightly faster
sub is_zero
{
# return true if arg (BINT or num_str) is zero (array '+', '0')
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
$CALC->_is_zero($x->{value});
}
sub is_nan
{
# return true if arg (BINT or num_str) is NaN
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
$x->{sign} eq $nan ? 1 : 0;
}
sub is_inf
{
# return true if arg (BINT or num_str) is +-inf
my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
if (defined $sign)
{
$sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf
$sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-'
return $x->{sign} =~ /^$sign$/ ? 1 : 0;
}
$x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity
}
sub is_one
{
# return true if arg (BINT or num_str) is +1, or -1 if sign is given
my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
$sign = '+' if !defined $sign || $sign ne '-';
return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
$CALC->_is_one($x->{value});
}
sub is_odd
{
# return true when arg (BINT or num_str) is odd, false for even
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
$CALC->_is_odd($x->{value});
}
sub is_even
{
# return true when arg (BINT or num_str) is even, false for odd
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
$CALC->_is_even($x->{value});
}
sub is_positive
{
# return true when arg (BINT or num_str) is positive (>= 0)
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
return 1 if $x->{sign} eq '+inf'; # +inf is positive
# 0+ is neither positive nor negative
($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0;
}
sub is_negative
{
# return true when arg (BINT or num_str) is negative (< 0)
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
$x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not
}
sub is_int
{
# return true when arg (BINT or num_str) is an integer
# always true for BigInt, but different for BigFloats
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
$x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
}
###############################################################################
sub bmul
{
# multiply the first number by the second number
# (BINT or num_str, BINT or num_str) return BINT
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bmul');
return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
# inf handling
if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
{
return $x->bnan() if $x->is_zero() || $y->is_zero();
# result will always be +-inf:
# +inf * +/+inf => +inf, -inf * -/-inf => +inf
# +inf * -/-inf => -inf, -inf * +/+inf => -inf
return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
return $x->binf('-');
}
return $upgrade->bmul($x,$upgrade->new($y),@r)
if defined $upgrade && !$y->isa($self);
$r[3] = $y; # no push here
$x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
$x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
$x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
$x->round(@r);
}
sub bmuladd
{
# multiply two numbers and then add the third to the result
# (BINT or num_str, BINT or num_str, BINT or num_str) return BINT
# set up parameters
my ($self,$x,$y,$z,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,$z,@r) = objectify(3,@_);
}
return $x if $x->modify('bmuladd');
return $x->bnan() if ($x->{sign} eq $nan) ||
($y->{sign} eq $nan) ||
($z->{sign} eq $nan);
# inf handling of x and y
if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
{
return $x->bnan() if $x->is_zero() || $y->is_zero();
# result will always be +-inf:
# +inf * +/+inf => +inf, -inf * -/-inf => +inf
# +inf * -/-inf => -inf, -inf * +/+inf => -inf
return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
return $x->binf('-');
}
# inf handling x*y and z
if (($z->{sign} =~ /^[+-]inf$/))
{
# something +-inf => +-inf
$x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/;
}
return $upgrade->bmuladd($x,$upgrade->new($y),$upgrade->new($z),@r)
if defined $upgrade && (!$y->isa($self) || !$z->isa($self) || !$x->isa($self));
# TODO: what if $y and $z have A or P set?
$r[3] = $z; # no push here
$x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
$x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
$x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs
if ($sx eq $sz)
{
$x->{value} = $CALC->_add($x->{value},$z->{value}); # same sign, abs add
}
else
{
my $a = $CALC->_acmp ($z->{value},$x->{value}); # absolute compare
if ($a > 0)
{
$x->{value} = $CALC->_sub($z->{value},$x->{value},1); # abs sub w/ swap
$x->{sign} = $sz;
}
elsif ($a == 0)
{
# speedup, if equal, set result to 0
$x->{value} = $CALC->_zero();
$x->{sign} = '+';
}
else # a < 0
{
$x->{value} = $CALC->_sub($x->{value}, $z->{value}); # abs sub
}
}
$x->round(@r);
}
sub _div_inf
{
# helper function that handles +-inf cases for bdiv()/bmod() to reuse code
my ($self,$x,$y) = @_;
# NaN if x == NaN or y == NaN or x==y==0
return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
if (($x->is_nan() || $y->is_nan()) ||
($x->is_zero() && $y->is_zero()));
# +-inf / +-inf == NaN, reminder also NaN
if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
{
return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
}
# x / +-inf => 0, remainder x (works even if x == 0)
if ($y->{sign} =~ /^[+-]inf$/)
{
my $t = $x->copy(); # bzero clobbers up $x
return wantarray ? ($x->bzero(),$t) : $x->bzero()
}
# 5 / 0 => +inf, -6 / 0 => -inf
# +inf / 0 = inf, inf, and -inf / 0 => -inf, -inf
# exception: -8 / 0 has remainder -8, not 8
# exception: -inf / 0 has remainder -inf, not inf
if ($y->is_zero())
{
# +-inf / 0 => special case for -inf
return wantarray ? ($x,$x->copy()) : $x if $x->is_inf();
if (!$x->is_zero() && !$x->is_inf())
{
my $t = $x->copy(); # binf clobbers up $x
return wantarray ?
($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
}
}
# last case: +-inf / ordinary number
my $sign = '+inf';
$sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
$x->{sign} = $sign;
return wantarray ? ($x,$self->bzero()) : $x;
}
sub bdiv
{
# (dividend: BINT or num_str, divisor: BINT or num_str) return
# (BINT,BINT) (quo,rem) or BINT (only rem)
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bdiv');
return $self->_div_inf($x,$y)
if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
if defined $upgrade;
$r[3] = $y; # no push!
# calc new sign and in case $y == +/- 1, return $x
my $xsign = $x->{sign}; # keep
$x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
if (wantarray)
{
my $rem = $self->bzero();
($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
$x->{sign} = '+' if $CALC->_is_zero($x->{value});
$rem->{_a} = $x->{_a};
$rem->{_p} = $x->{_p};
$x->round(@r);
if (! $CALC->_is_zero($rem->{value}))
{
$rem->{sign} = $y->{sign};
$rem = $y->copy()->bsub($rem) if $xsign ne $y->{sign}; # one of them '-'
}
else
{
$rem->{sign} = '+'; # dont leave -0
}
$rem->round(@r);
return ($x,$rem);
}
$x->{value} = $CALC->_div($x->{value},$y->{value});
$x->{sign} = '+' if $CALC->_is_zero($x->{value});
$x->round(@r);
}
###############################################################################
# modulus functions
sub bmod
{
# modulus (or remainder)
# (BINT or num_str, BINT or num_str) return BINT
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bmod');
$r[3] = $y; # no push!
if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
{
my ($d,$r) = $self->_div_inf($x,$y);
$x->{sign} = $r->{sign};
$x->{value} = $r->{value};
return $x->round(@r);
}
# calc new sign and in case $y == +/- 1, return $x
$x->{value} = $CALC->_mod($x->{value},$y->{value});
if (!$CALC->_is_zero($x->{value}))
{
$x->{value} = $CALC->_sub($y->{value},$x->{value},1) # $y-$x
if ($x->{sign} ne $y->{sign});
$x->{sign} = $y->{sign};
}
else
{
$x->{sign} = '+'; # dont leave -0
}
$x->round(@r);
}
sub bmodinv
{
# Modular inverse. given a number which is (hopefully) relatively
# prime to the modulus, calculate its inverse using Euclid's
# alogrithm. If the number is not relatively prime to the modulus
# (i.e. their gcd is not one) then NaN is returned.
# set up parameters
my ($self,$x,$y,@r) = (undef,@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bmodinv');
return $x->bnan()
if ($y->{sign} ne '+' # -, NaN, +inf, -inf
|| $x->is_zero() # or num == 0
|| $x->{sign} !~ /^[+-]$/ # or num NaN, inf, -inf
);
# put least residue into $x if $x was negative, and thus make it positive
$x->bmod($y) if $x->{sign} eq '-';
my $sign;
($x->{value},$sign) = $CALC->_modinv($x->{value},$y->{value});
return $x->bnan() if !defined $x->{value}; # in case no GCD found
return $x if !defined $sign; # already real result
$x->{sign} = $sign; # flip/flop see below
$x->bmod($y); # calc real result
$x;
}
sub bmodpow
{
# takes a very large number to a very large exponent in a given very
# large modulus, quickly, thanks to binary exponentation. Supports
# negative exponents.
my ($self,$num,$exp,$mod,@r) = objectify(3,@_);
return $num if $num->modify('bmodpow');
# check modulus for valid values
return $num->bnan() if ($mod->{sign} ne '+' # NaN, - , -inf, +inf
|| $mod->is_zero());
# check exponent for valid values
if ($exp->{sign} =~ /\w/)
{
# i.e., if it's NaN, +inf, or -inf...
return $num->bnan();
}
$num->bmodinv ($mod) if ($exp->{sign} eq '-');
# check num for valid values (also NaN if there was no inverse but $exp < 0)
return $num->bnan() if $num->{sign} !~ /^[+-]$/;
# $mod is positive, sign on $exp is ignored, result also positive
$num->{value} = $CALC->_modpow($num->{value},$exp->{value},$mod->{value});
$num;
}
###############################################################################
sub bfac
{
# (BINT or num_str, BINT or num_str) return BINT
# compute factorial number from $x, modify $x in place
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf
return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN
$x->{value} = $CALC->_fac($x->{value});
$x->round(@r);
}
sub bpow
{
# (BINT or num_str, BINT or num_str) return BINT
# compute power of two numbers -- stolen from Knuth Vol 2 pg 233
# modifies first argument
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bpow');
return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
# inf handling
if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
{
if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
{
# +-inf ** +-inf
return $x->bnan();
}
# +-inf ** Y
if ($x->{sign} =~ /^[+-]inf/)
{
# +inf ** 0 => NaN
return $x->bnan() if $y->is_zero();
# -inf ** -1 => 1/inf => 0
return $x->bzero() if $y->is_one('-') && $x->is_negative();
# +inf ** Y => inf
return $x if $x->{sign} eq '+inf';
# -inf ** Y => -inf if Y is odd
return $x if $y->is_odd();
return $x->babs();
}
# X ** +-inf
# 1 ** +inf => 1
return $x if $x->is_one();
# 0 ** inf => 0
return $x if $x->is_zero() && $y->{sign} =~ /^[+]/;
# 0 ** -inf => inf
return $x->binf() if $x->is_zero();
# -1 ** -inf => NaN
return $x->bnan() if $x->is_one('-') && $y->{sign} =~ /^[-]/;
# -X ** -inf => 0
return $x->bzero() if $x->{sign} eq '-' && $y->{sign} =~ /^[-]/;
# -1 ** inf => NaN
return $x->bnan() if $x->{sign} eq '-';
# X ** inf => inf
return $x->binf() if $y->{sign} =~ /^[+]/;
# X ** -inf => 0
return $x->bzero();
}
return $upgrade->bpow($upgrade->new($x),$y,@r)
if defined $upgrade && (!$y->isa($self) || $y->{sign} eq '-');
$r[3] = $y; # no push!
# cases 0 ** Y, X ** 0, X ** 1, 1 ** Y are handled by Calc or Emu
my $new_sign = '+';
$new_sign = $y->is_odd() ? '-' : '+' if ($x->{sign} ne '+');
# 0 ** -7 => ( 1 / (0 ** 7)) => 1 / 0 => +inf
return $x->binf()
if $y->{sign} eq '-' && $x->{sign} eq '+' && $CALC->_is_zero($x->{value});
# 1 ** -y => 1 / (1 ** |y|)
# so do test for negative $y after above's clause
return $x->bnan() if $y->{sign} eq '-' && !$CALC->_is_one($x->{value});
$x->{value} = $CALC->_pow($x->{value},$y->{value});
$x->{sign} = $new_sign;
$x->{sign} = '+' if $CALC->_is_zero($y->{value});
$x->round(@r);
}
sub blsft
{
# (BINT or num_str, BINT or num_str) return BINT
# compute x << y, base n, y >= 0
# set up parameters
my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,$n,@r) = objectify(2,@_);
}
return $x if $x->modify('blsft');
return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
return $x->round(@r) if $y->is_zero();
$n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
$x->{value} = $CALC->_lsft($x->{value},$y->{value},$n);
$x->round(@r);
}
sub brsft
{
# (BINT or num_str, BINT or num_str) return BINT
# compute x >> y, base n, y >= 0
# set up parameters
my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,$n,@r) = objectify(2,@_);
}
return $x if $x->modify('brsft');
return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
return $x->round(@r) if $y->is_zero();
return $x->bzero(@r) if $x->is_zero(); # 0 => 0
$n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
# this only works for negative numbers when shifting in base 2
if (($x->{sign} eq '-') && ($n == 2))
{
return $x->round(@r) if $x->is_one('-'); # -1 => -1
if (!$y->is_one())
{
# although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
# but perhaps there is a better emulation for two's complement shift...
# if $y != 1, we must simulate it by doing:
# convert to bin, flip all bits, shift, and be done
$x->binc(); # -3 => -2
my $bin = $x->as_bin();
$bin =~ s/^-0b//; # strip '-0b' prefix
$bin =~ tr/10/01/; # flip bits
# now shift
if ($y >= CORE::length($bin))
{
$bin = '0'; # shifting to far right creates -1
# 0, because later increment makes
# that 1, attached '-' makes it '-1'
# because -1 >> x == -1 !
}
else
{
$bin =~ s/.{$y}$//; # cut off at the right side
$bin = '1' . $bin; # extend left side by one dummy '1'
$bin =~ tr/10/01/; # flip bits back
}
my $res = $self->new('0b'.$bin); # add prefix and convert back
$res->binc(); # remember to increment
$x->{value} = $res->{value}; # take over value
return $x->round(@r); # we are done now, magic, isn't?
}
# x < 0, n == 2, y == 1
$x->bdec(); # n == 2, but $y == 1: this fixes it
}
$x->{value} = $CALC->_rsft($x->{value},$y->{value},$n);
$x->round(@r);
}
sub band
{
#(BINT or num_str, BINT or num_str) return BINT
# compute x & y
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('band');
$r[3] = $y; # no push!
return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
my $sx = $x->{sign} eq '+' ? 1 : -1;
my $sy = $y->{sign} eq '+' ? 1 : -1;
if ($sx == 1 && $sy == 1)
{
$x->{value} = $CALC->_and($x->{value},$y->{value});
return $x->round(@r);
}
if ($CAN{signed_and})
{
$x->{value} = $CALC->_signed_and($x->{value},$y->{value},$sx,$sy);
return $x->round(@r);
}
require $EMU_LIB;
__emu_band($self,$x,$y,$sx,$sy,@r);
}
sub bior
{
#(BINT or num_str, BINT or num_str) return BINT
# compute x | y
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bior');
$r[3] = $y; # no push!
return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
my $sx = $x->{sign} eq '+' ? 1 : -1;
my $sy = $y->{sign} eq '+' ? 1 : -1;
# the sign of X follows the sign of X, e.g. sign of Y irrelevant for bior()
# don't use lib for negative values
if ($sx == 1 && $sy == 1)
{
$x->{value} = $CALC->_or($x->{value},$y->{value});
return $x->round(@r);
}
# if lib can do negative values, let it handle this
if ($CAN{signed_or})
{
$x->{value} = $CALC->_signed_or($x->{value},$y->{value},$sx,$sy);
return $x->round(@r);
}
require $EMU_LIB;
__emu_bior($self,$x,$y,$sx,$sy,@r);
}
sub bxor
{
#(BINT or num_str, BINT or num_str) return BINT
# compute x ^ y
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$x,$y,@r) = objectify(2,@_);
}
return $x if $x->modify('bxor');
$r[3] = $y; # no push!
return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
my $sx = $x->{sign} eq '+' ? 1 : -1;
my $sy = $y->{sign} eq '+' ? 1 : -1;
# don't use lib for negative values
if ($sx == 1 && $sy == 1)
{
$x->{value} = $CALC->_xor($x->{value},$y->{value});
return $x->round(@r);
}
# if lib can do negative values, let it handle this
if ($CAN{signed_xor})
{
$x->{value} = $CALC->_signed_xor($x->{value},$y->{value},$sx,$sy);
return $x->round(@r);
}
require $EMU_LIB;
__emu_bxor($self,$x,$y,$sx,$sy,@r);
}
sub length
{
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
my $e = $CALC->_len($x->{value});
wantarray ? ($e,0) : $e;
}
sub digit
{
# return the nth decimal digit, negative values count backward, 0 is right
my ($self,$x,$n) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
$n = $n->numify() if ref($n);
$CALC->_digit($x->{value},$n||0);
}
sub _trailing_zeros
{
# return the amount of trailing zeros in $x (as scalar)
my $x = shift;
$x = $class->new($x) unless ref $x;
return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc
$CALC->_zeros($x->{value}); # must handle odd values, 0 etc
}
sub bsqrt
{
# calculate square root of $x
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('bsqrt');
return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN
return $x if $x->{sign} eq '+inf'; # sqrt(+inf) == inf
return $upgrade->bsqrt($x,@r) if defined $upgrade;
$x->{value} = $CALC->_sqrt($x->{value});
$x->round(@r);
}
sub broot
{
# calculate $y'th root of $x
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
$y = $self->new(2) unless defined $y;
# objectify is costly, so avoid it
if ((!ref($x)) || (ref($x) ne ref($y)))
{
($self,$x,$y,@r) = objectify(2,$self || $class,@_);
}
return $x if $x->modify('broot');
# NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
$y->{sign} !~ /^\+$/;
return $x->round(@r)
if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();
return $upgrade->new($x)->broot($upgrade->new($y),@r) if defined $upgrade;
$x->{value} = $CALC->_root($x->{value},$y->{value});
$x->round(@r);
}
sub exponent
{
# return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
if ($x->{sign} !~ /^[+-]$/)
{
my $s = $x->{sign}; $s =~ s/^[+-]//; # NaN, -inf,+inf => NaN or inf
return $self->new($s);
}
return $self->bone() if $x->is_zero();
# 12300 => 2 trailing zeros => exponent is 2
$self->new( $CALC->_zeros($x->{value}) );
}
sub mantissa
{
# return the mantissa (compatible to Math::BigFloat, e.g. reduced)
my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
if ($x->{sign} !~ /^[+-]$/)
{
# for NaN, +inf, -inf: keep the sign
return $self->new($x->{sign});
}
my $m = $x->copy(); delete $m->{_p}; delete $m->{_a};
# that's a bit inefficient:
my $zeros = $CALC->_zeros($m->{value});
$m->brsft($zeros,10) if $zeros != 0;
$m;
}
sub parts
{
# return a copy of both the exponent and the mantissa
my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
($x->mantissa(),$x->exponent());
}
##############################################################################
# rounding functions
sub bfround
{
# precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
# $n == 0 || $n == 1 => round to integer
my $x = shift; my $self = ref($x) || $x; $x = $self->new($x) unless ref $x;
my ($scale,$mode) = $x->_scale_p(@_);
return $x if !defined $scale || $x->modify('bfround'); # no-op
# no-op for BigInts if $n <= 0
$x->bround( $x->length()-$scale, $mode) if $scale > 0;
delete $x->{_a}; # delete to save memory
$x->{_p} = $scale; # store new _p
$x;
}
sub _scan_for_nonzero
{
# internal, used by bround() to scan for non-zeros after a '5'
my ($x,$pad,$xs,$len) = @_;
return 0 if $len == 1; # "5" is trailed by invisible zeros
my $follow = $pad - 1;
return 0 if $follow > $len || $follow < 1;
# use the string form to check whether only '0's follow or not
substr ($xs,-$follow) =~ /[^0]/ ? 1 : 0;
}
sub fround
{
# Exists to make life easier for switch between MBF and MBI (should we
# autoload fxxx() like MBF does for bxxx()?)
my $x = shift; $x = $class->new($x) unless ref $x;
$x->bround(@_);
}
sub bround
{
# accuracy: +$n preserve $n digits from left,
# -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
# no-op for $n == 0
# and overwrite the rest with 0's, return normalized number
# do not return $x->bnorm(), but $x
my $x = shift; $x = $class->new($x) unless ref $x;
my ($scale,$mode) = $x->_scale_a(@_);
return $x if !defined $scale || $x->modify('bround'); # no-op
if ($x->is_zero() || $scale == 0)
{
$x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
return $x;
}
return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
# we have fewer digits than we want to scale to
my $len = $x->length();
# convert $scale to a scalar in case it is an object (put's a limit on the
# number length, but this would already limited by memory constraints), makes
# it faster
$scale = $scale->numify() if ref ($scale);
# scale < 0, but > -len (not >=!)
if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
{
$x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
return $x;
}
# count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
my ($pad,$digit_round,$digit_after);
$pad = $len - $scale;
$pad = abs($scale-1) if $scale < 0;
# do not use digit(), it is very costly for binary => decimal
# getting the entire string is also costly, but we need to do it only once
my $xs = $CALC->_str($x->{value});
my $pl = -$pad-1;
# pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
# pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
$digit_round = '0'; $digit_round = substr($xs,$pl,1) if $pad <= $len;
$pl++; $pl ++ if $pad >= $len;
$digit_after = '0'; $digit_after = substr($xs,$pl,1) if $pad > 0;
# in case of 01234 we round down, for 6789 up, and only in case 5 we look
# closer at the remaining digits of the original $x, remember decision
my $round_up = 1; # default round up
$round_up -- if
($mode eq 'trunc') || # trunc by round down
($digit_after =~ /[01234]/) || # round down anyway,
# 6789 => round up
($digit_after eq '5') && # not 5000...0000
($x->_scan_for_nonzero($pad,$xs,$len) == 0) &&
(
($mode eq 'even') && ($digit_round =~ /[24680]/) ||
($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
($mode eq '+inf') && ($x->{sign} eq '-') ||
($mode eq '-inf') && ($x->{sign} eq '+') ||
($mode eq 'zero') # round down if zero, sign adjusted below
);
my $put_back = 0; # not yet modified
if (($pad > 0) && ($pad <= $len))
{
substr($xs,-$pad,$pad) = '0' x $pad; # replace with '00...'
$put_back = 1; # need to put back
}
elsif ($pad > $len)
{
$x->bzero(); # round to '0'
}
if ($round_up) # what gave test above?
{
$put_back = 1; # need to put back
$pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0
# we modify directly the string variant instead of creating a number and
# adding it, since that is faster (we already have the string)
my $c = 0; $pad ++; # for $pad == $len case
while ($pad <= $len)
{
$c = substr($xs,-$pad,1) + 1; $c = '0' if $c eq '10';
substr($xs,-$pad,1) = $c; $pad++;
last if $c != 0; # no overflow => early out
}
$xs = '1'.$xs if $c == 0;
}
$x->{value} = $CALC->_new($xs) if $put_back == 1; # put back, if needed
$x->{_a} = $scale if $scale >= 0;
if ($scale < 0)
{
$x->{_a} = $len+$scale;
$x->{_a} = 0 if $scale < -$len;
}
$x;
}
sub bfloor
{
# return integer less or equal then number; no-op since it's already integer
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
$x->round(@r);
}
sub bceil
{
# return integer greater or equal then number; no-op since it's already int
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
$x->round(@r);
}
sub as_number
{
# An object might be asked to return itself as bigint on certain overloaded
# operations. This does exactly this, so that sub classes can simple inherit
# it or override with their own integer conversion routine.
$_[0]->copy();
}
sub as_hex
{
# return as hex string, with prefixed 0x
my $x = shift; $x = $class->new($x) if !ref($x);
return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
my $s = '';
$s = $x->{sign} if $x->{sign} eq '-';
$s . $CALC->_as_hex($x->{value});
}
sub as_bin
{
# return as binary string, with prefixed 0b
my $x = shift; $x = $class->new($x) if !ref($x);
return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
my $s = ''; $s = $x->{sign} if $x->{sign} eq '-';
return $s . $CALC->_as_bin($x->{value});
}
sub as_oct
{
# return as octal string, with prefixed 0
my $x = shift; $x = $class->new($x) if !ref($x);
return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
my $s = ''; $s = $x->{sign} if $x->{sign} eq '-';
return $s . $CALC->_as_oct($x->{value});
}
##############################################################################
# private stuff (internal use only)
sub objectify
{
# check for strings, if yes, return objects instead
# the first argument is number of args objectify() should look at it will
# return $count+1 elements, the first will be a classname. This is because
# overloaded '""' calls bstr($object,undef,undef) and this would result in
# useless objects being created and thrown away. So we cannot simple loop
# over @_. If the given count is 0, all arguments will be used.
# If the second arg is a ref, use it as class.
# If not, try to use it as classname, unless undef, then use $class
# (aka Math::BigInt). The latter shouldn't happen,though.
# caller: gives us:
# $x->badd(1); => ref x, scalar y
# Class->badd(1,2); => classname x (scalar), scalar x, scalar y
# Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
# Math::BigInt::badd(1,2); => scalar x, scalar y
# In the last case we check number of arguments to turn it silently into
# $class,1,2. (We can not take '1' as class ;o)
# badd($class,1) is not supported (it should, eventually, try to add undef)
# currently it tries 'Math::BigInt' + 1, which will not work.
# some shortcut for the common cases
# $x->unary_op();
return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
my $count = abs(shift || 0);
my (@a,$k,$d); # resulting array, temp, and downgrade
if (ref $_[0])
{
# okay, got object as first
$a[0] = ref $_[0];
}
else
{
# nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
$a[0] = $class;
$a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
}
no strict 'refs';
# disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
if (defined ${"$a[0]::downgrade"})
{
$d = ${"$a[0]::downgrade"};
${"$a[0]::downgrade"} = undef;
}
my $up = ${"$a[0]::upgrade"};
# print STDERR "# Now in objectify, my class is today $a[0], count = $count\n";
if ($count == 0)
{
while (@_)
{
$k = shift;
if (!ref($k))
{
$k = $a[0]->new($k);
}
elsif (!defined $up && ref($k) ne $a[0])
{
# foreign object, try to convert to integer
$k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
}
push @a,$k;
}
}
else
{
while ($count > 0)
{
$count--;
$k = shift;
if (!ref($k))
{
$k = $a[0]->new($k);
}
elsif (!defined $up && ref($k) ne $a[0])
{
# foreign object, try to convert to integer
$k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
}
push @a,$k;
}
push @a,@_; # return other params, too
}
if (! wantarray)
{
require Carp; Carp::croak ("$class objectify needs list context");
}
${"$a[0]::downgrade"} = $d;
@a;
}
sub _register_callback
{
my ($class,$callback) = @_;
if (ref($callback) ne 'CODE')
{
require Carp;
Carp::croak ("$callback is not a coderef");
}
$CALLBACKS{$class} = $callback;
}
sub import
{
my $self = shift;
$IMPORT++; # remember we did import()
my @a; my $l = scalar @_;
my $warn_or_die = 0; # 0 - no warn, 1 - warn, 2 - die
for ( my $i = 0; $i < $l ; $i++ )
{
if ($_[$i] eq ':constant')
{
# this causes overlord er load to step in
overload::constant
integer => sub { $self->new(shift) },
binary => sub { $self->new(shift) };
}
elsif ($_[$i] eq 'upgrade')
{
# this causes upgrading
$upgrade = $_[$i+1]; # or undef to disable
$i++;
}
elsif ($_[$i] =~ /^(lib|try|only)\z/)
{
# this causes a different low lib to take care...
$CALC = $_[$i+1] || '';
# lib => 1 (warn on fallback), try => 0 (no warn), only => 2 (die on fallback)
$warn_or_die = 1 if $_[$i] eq 'lib';
$warn_or_die = 2 if $_[$i] eq 'only';
$i++;
}
else
{
push @a, $_[$i];
}
}
# any non :constant stuff is handled by our parent, Exporter
if (@a > 0)
{
require Exporter;
$self->SUPER::import(@a); # need it for subclasses
$self->export_to_level(1,$self,@a); # need it for MBF
}
# try to load core math lib
my @c = split /\s*,\s*/,$CALC;
foreach (@c)
{
$_ =~ tr/a-zA-Z0-9://cd; # limit to sane characters
}
push @c, \'FastCalc', \'Calc' # if all fail, try these
if $warn_or_die < 2; # but not for "only"
$CALC = ''; # signal error
foreach my $l (@c)
{
# fallback libraries are "marked" as \'string', extract string if nec.
my $lib = $l; $lib = $$l if ref($l);
next if ($lib || '') eq '';
$lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
$lib =~ s/\.pm$//;
if ($] < 5.006)
{
# Perl < 5.6.0 dies with "out of memory!" when eval("") and ':constant' is
# used in the same script, or eval("") inside import().
my @parts = split /::/, $lib; # Math::BigInt => Math BigInt
my $file = pop @parts; $file .= '.pm'; # BigInt => BigInt.pm
require File::Spec;
$file = File::Spec->catfile (@parts, $file);
eval { require "$file"; $lib->import( @c ); }
}
else
{
eval "use $lib qw/@c/;";
}
if ($@ eq '')
{
my $ok = 1;
# loaded it ok, see if the api_version() is high enough
if ($lib->can('api_version') && $lib->api_version() >= 1.0)
{
$ok = 0;
# api_version matches, check if it really provides anything we need
for my $method (qw/
one two ten
str num
add mul div sub dec inc
acmp len digit is_one is_zero is_even is_odd
is_two is_ten
zeros new copy check
from_hex from_oct from_bin as_hex as_bin as_oct
rsft lsft xor and or
mod sqrt root fac pow modinv modpow log_int gcd
/)
{
if (!$lib->can("_$method"))
{
if (($WARN{$lib}||0) < 2)
{
require Carp;
Carp::carp ("$lib is missing method '_$method'");
$WARN{$lib} = 1; # still warn about the lib
}
$ok++; last;
}
}
}
if ($ok == 0)
{
$CALC = $lib;
if ($warn_or_die > 0 && ref($l))
{
require Carp;
my $msg = "Math::BigInt: couldn't load specified math lib(s), fallback to $lib";
Carp::carp ($msg) if $warn_or_die == 1;
Carp::croak ($msg) if $warn_or_die == 2;
}
last; # found a usable one, break
}
else
{
if (($WARN{$lib}||0) < 2)
{
my $ver = eval "\$$lib\::VERSION" || 'unknown';
require Carp;
Carp::carp ("Cannot load outdated $lib v$ver, please upgrade");
$WARN{$lib} = 2; # never warn again
}
}
}
}
if ($CALC eq '')
{
require Carp;
if ($warn_or_die == 2)
{
Carp::croak ("Couldn't load specified math lib(s) and fallback disallowed");
}
else
{
Carp::croak ("Couldn't load any math lib(s), not even fallback to Calc.pm");
}
}
# notify callbacks
foreach my $class (keys %CALLBACKS)
{
&{$CALLBACKS{$class}}($CALC);
}
# Fill $CAN with the results of $CALC->can(...) for emulating lower math lib
# functions
%CAN = ();
for my $method (qw/ signed_and signed_or signed_xor /)
{
$CAN{$method} = $CALC->can("_$method") ? 1 : 0;
}
# import done
}
sub from_hex
{
# create a bigint from a hexadecimal string
my ($self, $hs) = @_;
my $rc = __from_hex($hs);
return $self->bnan() unless defined $rc;
$rc;
}
sub from_bin
{
# create a bigint from a hexadecimal string
my ($self, $bs) = @_;
my $rc = __from_bin($bs);
return $self->bnan() unless defined $rc;
$rc;
}
sub from_oct
{
# create a bigint from a hexadecimal string
my ($self, $os) = @_;
my $x = $self->bzero();
# strip underscores
$os =~ s/([0-7])_([0-7])/$1$2/g;
$os =~ s/([0-7])_([0-7])/$1$2/g;
return $x->bnan() if $os !~ /^[\-\+]?0[0-7]+\z/;
my $sign = '+'; $sign = '-' if $os =~ /^-/;
$os =~ s/^[+-]//; # strip sign
$x->{value} = $CALC->_from_oct($os);
$x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
$x;
}
sub __from_hex
{
# internal
# convert a (ref to) big hex string to BigInt, return undef for error
my $hs = shift;
my $x = Math::BigInt->bzero();
# strip underscores
$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g;
return $x->bnan() if $hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
my $sign = '+'; $sign = '-' if $hs =~ /^-/;
$hs =~ s/^[+-]//; # strip sign
$x->{value} = $CALC->_from_hex($hs);
$x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
$x;
}
sub __from_bin
{
# internal
# convert a (ref to) big binary string to BigInt, return undef for error
my $bs = shift;
my $x = Math::BigInt->bzero();
# strip underscores
$bs =~ s/([01])_([01])/$1$2/g;
$bs =~ s/([01])_([01])/$1$2/g;
return $x->bnan() if $bs !~ /^[+-]?0b[01]+$/;
my $sign = '+'; $sign = '-' if $bs =~ /^\-/;
$bs =~ s/^[+-]//; # strip sign
$x->{value} = $CALC->_from_bin($bs);
$x->{sign} = $sign unless $CALC->_is_zero($x->{value}); # no '-0'
$x;
}
sub _split
{
# input: num_str; output: undef for invalid or
# (\$mantissa_sign,\$mantissa_value,\$mantissa_fraction,\$exp_sign,\$exp_value)
# Internal, take apart a string and return the pieces.
# Strip leading/trailing whitespace, leading zeros, underscore and reject
# invalid input.
my $x = shift;
# strip white space at front, also extranous leading zeros
$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2'
$x =~ s/^\s+//; # but this will
$x =~ s/\s+$//g; # strip white space at end
# shortcut, if nothing to split, return early
if ($x =~ /^[+-]?[0-9]+\z/)
{
$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
return (\$sign, \$x, \'', \'', \0);
}
# invalid starting char?
return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
return __from_hex($x) if $x =~ /^[\-\+]?0x/; # hex string
return __from_bin($x) if $x =~ /^[\-\+]?0b/; # binary string
# strip underscores between digits
$x =~ s/([0-9])_([0-9])/$1$2/g;
$x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3
# some possible inputs:
# 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
# .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2 # 0e999
my ($m,$e,$last) = split /[Ee]/,$x;
return if defined $last; # last defined => 1e2E3 or others
$e = '0' if !defined $e || $e eq "";
# sign,value for exponent,mantint,mantfrac
my ($es,$ev,$mis,$miv,$mfv);
# valid exponent?
if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
{
$es = $1; $ev = $2;
# valid mantissa?
return if $m eq '.' || $m eq '';
my ($mi,$mf,$lastf) = split /\./,$m;
return if defined $lastf; # lastf defined => 1.2.3 or others
$mi = '0' if !defined $mi;
$mi .= '0' if $mi =~ /^[\-\+]?$/;
$mf = '0' if !defined $mf || $mf eq '';
if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
{
$mis = $1||'+'; $miv = $2;
return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros
$mfv = $1;
# handle the 0e999 case here
$ev = 0 if $miv eq '0' && $mfv eq '';
return (\$mis,\$miv,\$mfv,\$es,\$ev);
}
}
return; # NaN, not a number
}
##############################################################################
# internal calculation routines (others are in Math::BigInt::Calc etc)
sub __lcm
{
# (BINT or num_str, BINT or num_str) return BINT
# does modify first argument
# LCM
my ($x,$ty) = @_;
return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
my $method = ref($x) . '::bgcd';
no strict 'refs';
$x * $ty / &$method($x,$ty);
}
###############################################################################
# trigonometric functions
sub bpi
{
# Calculate PI to N digits. Unless upgrading is in effect, returns the
# result truncated to an integer, that is, always returns '3'.
my ($self,$n) = @_;
if (@_ == 1)
{
# called like Math::BigInt::bpi(10);
$n = $self; $self = $class;
}
$self = ref($self) if ref($self);
return $upgrade->new($n) if defined $upgrade;
# hard-wired to "3"
$self->new(3);
}
sub bcos
{
# Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the
# result truncated to an integer.
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('bcos');
return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
return $upgrade->new($x)->bcos(@r) if defined $upgrade;
require Math::BigFloat;
# calculate the result and truncate it to integer
my $t = Math::BigFloat->new($x)->bcos(@r)->as_int();
$x->bone() if $t->is_one();
$x->bzero() if $t->is_zero();
$x->round(@r);
}
sub bsin
{
# Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the
# result truncated to an integer.
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('bsin');
return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
return $upgrade->new($x)->bsin(@r) if defined $upgrade;
require Math::BigFloat;
# calculate the result and truncate it to integer
my $t = Math::BigFloat->new($x)->bsin(@r)->as_int();
$x->bone() if $t->is_one();
$x->bzero() if $t->is_zero();
$x->round(@r);
}
sub batan2
{
# calculate arcus tangens of ($y/$x)
# set up parameters
my ($self,$y,$x,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
($self,$y,$x,@r) = objectify(2,@_);
}
return $y if $y->modify('batan2');
return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan);
# Y X
# != 0 -inf result is +- pi
if ($x->is_inf() || $y->is_inf())
{
# upgrade to BigFloat etc.
return $upgrade->new($y)->batan2($upgrade->new($x),@r) if defined $upgrade;
if ($y->is_inf())
{
if ($x->{sign} eq '-inf')
{
# calculate 3 pi/4 => 2.3.. => 2
$y->bone( substr($y->{sign},0,1) );
$y->bmul($self->new(2));
}
elsif ($x->{sign} eq '+inf')
{
# calculate pi/4 => 0.7 => 0
$y->bzero();
}
else
{
# calculate pi/2 => 1.5 => 1
$y->bone( substr($y->{sign},0,1) );
}
}
else
{
if ($x->{sign} eq '+inf')
{
# calculate pi/4 => 0.7 => 0
$y->bzero();
}
else
{
# PI => 3.1415.. => 3
$y->bone( substr($y->{sign},0,1) );
$y->bmul($self->new(3));
}
}
return $y;
}
return $upgrade->new($y)->batan2($upgrade->new($x),@r) if defined $upgrade;
require Math::BigFloat;
my $r = Math::BigFloat->new($y)->batan2(Math::BigFloat->new($x),@r)->as_int();
$x->{value} = $r->{value};
$x->{sign} = $r->{sign};
$x;
}
sub batan
{
# Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the
# result truncated to an integer.
my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
return $x if $x->modify('batan');
return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
return $upgrade->new($x)->batan(@r) if defined $upgrade;
# calculate the result and truncate it to integer
my $t = Math::BigFloat->new($x)->batan(@r);
$x->{value} = $CALC->_new( $x->as_int()->bstr() );
$x->round(@r);
}
###############################################################################
# this method returns 0 if the object can be modified, or 1 if not.
# We use a fast constant sub() here, to avoid costly calls. Subclasses
# may override it with special code (f.i. Math::BigInt::Constant does so)
sub modify () { 0; }
1;
__END__
=pod
=head1 NAME
Math::BigInt - Arbitrary size integer/float math package
=head1 SYNOPSIS
use Math::BigInt;
# or make it faster with huge numbers: install (optional)
# Math::BigInt::GMP and always use (it will fall back to
# pure Perl if the GMP library is not installed):
# (See also the L<MATH LIBRARY> section!)
# will warn if Math::BigInt::GMP cannot be found
use Math::BigInt lib => 'GMP';
# to supress the warning use this:
# use Math::BigInt try => 'GMP';
# dies if GMP cannot be loaded:
# use Math::BigInt only => 'GMP';
my $str = '1234567890';
my @values = (64,74,18);
my $n = 1; my $sign = '-';
# Number creation
my $x = Math::BigInt->new($str); # defaults to 0
my $y = $x->copy(); # make a true copy
my $nan = Math::BigInt->bnan(); # create a NotANumber
my $zero = Math::BigInt->bzero(); # create a +0
my $inf = Math::BigInt->binf(); # create a +inf
my $inf = Math::BigInt->binf('-'); # create a -inf
my $one = Math::BigInt->bone(); # create a +1
my $mone = Math::BigInt->bone('-'); # create a -1
my $pi = Math::BigInt->bpi(); # returns '3'
# see Math::BigFloat::bpi()
$h = Math::BigInt->new('0x123'); # from hexadecimal
$b = Math::BigInt->new('0b101'); # from binary
$o = Math::BigInt->from_oct('0101'); # from octal
# Testing (don't modify their arguments)
# (return true if the condition is met, otherwise false)
$x->is_zero(); # if $x is +0
$x->is_nan(); # if $x is NaN
$x->is_one(); # if $x is +1
$x->is_one('-'); # if $x is -1
$x->is_odd(); # if $x is odd
$x->is_even(); # if $x is even
$x->is_pos(); # if $x >= 0
$x->is_neg(); # if $x < 0
$x->is_inf($sign); # if $x is +inf, or -inf (sign is default '+')
$x->is_int(); # if $x is an integer (not a float)
# comparing and digit/sign extraction
$x->bcmp($y); # compare numbers (undef,<0,=0,>0)
$x->bacmp($y); # compare absolutely (undef,<0,=0,>0)
$x->sign(); # return the sign, either +,- or NaN
$x->digit($n); # return the nth digit, counting from right
$x->digit(-$n); # return the nth digit, counting from left
# The following all modify their first argument. If you want to preserve
# $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
# necessary when mixing $a = $b assignments with non-overloaded math.
$x->bzero(); # set $x to 0
$x->bnan(); # set $x to NaN
$x->bone(); # set $x to +1
$x->bone('-'); # set $x to -1
$x->binf(); # set $x to inf
$x->binf('-'); # set $x to -inf
$x->bneg(); # negation
$x->babs(); # absolute value
$x->bnorm(); # normalize (no-op in BigInt)
$x->bnot(); # two's complement (bit wise not)
$x->binc(); # increment $x by 1
$x->bdec(); # decrement $x by 1
$x->badd($y); # addition (add $y to $x)
$x->bsub($y); # subtraction (subtract $y from $x)
$x->bmul($y); # multiplication (multiply $x by $y)
$x->bdiv($y); # divide, set $x to quotient
# return (quo,rem) or quo if scalar
$x->bmuladd($y,$z); # $x = $x * $y + $z
$x->bmod($y); # modulus (x % y)
$x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod))
$x->bmodinv($mod); # the inverse of $x in the given modulus $mod
$x->bpow($y); # power of arguments (x ** y)
$x->blsft($y); # left shift in base 2
$x->brsft($y); # right shift in base 2
# returns (quo,rem) or quo if in scalar context
$x->blsft($y,$n); # left shift by $y places in base $n
$x->brsft($y,$n); # right shift by $y places in base $n
# returns (quo,rem) or quo if in scalar context
$x->band($y); # bitwise and
$x->bior($y); # bitwise inclusive or
$x->bxor($y); # bitwise exclusive or
$x->bnot(); # bitwise not (two's complement)
$x->bsqrt(); # calculate square-root
$x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root)
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
$x->bnok($y); # x over y (binomial coefficient n over k)
$x->blog(); # logarithm of $x to base e (Euler's number)
$x->blog($base); # logarithm of $x to base $base (f.i. 2)
$x->bexp(); # calculate e ** $x where e is Euler's number
$x->round($A,$P,$mode); # round to accuracy or precision using mode $mode
$x->bround($n); # accuracy: preserve $n digits
$x->bfround($n); # $n > 0: round $nth digits,
# $n < 0: round to the $nth digit after the
# dot, no-op for BigInts
# The following do not modify their arguments in BigInt (are no-ops),
# but do so in BigFloat:
$x->bfloor(); # return integer less or equal than $x
$x->bceil(); # return integer greater or equal than $x
# The following do not modify their arguments:
# greatest common divisor (no OO style)
my $gcd = Math::BigInt::bgcd(@values);
# lowest common multiplicator (no OO style)
my $lcm = Math::BigInt::blcm(@values);
$x->length(); # return number of digits in number
($xl,$f) = $x->length(); # length of number and length of fraction part,
# latter is always 0 digits long for BigInts
$x->exponent(); # return exponent as BigInt
$x->mantissa(); # return (signed) mantissa as BigInt
$x->parts(); # return (mantissa,exponent) as BigInt
$x->copy(); # make a true copy of $x (unlike $y = $x;)
$x->as_int(); # return as BigInt (in BigInt: same as copy())
$x->numify(); # return as scalar (might overflow!)
# conversation to string (do not modify their argument)
$x->bstr(); # normalized string (e.g. '3')
$x->bsstr(); # norm. string in scientific notation (e.g. '3E0')
$x->as_hex(); # as signed hexadecimal string with prefixed 0x
$x->as_bin(); # as signed binary string with prefixed 0b
$x->as_oct(); # as signed octal string with prefixed 0
# precision and accuracy (see section about rounding for more)
$x->precision(); # return P of $x (or global, if P of $x undef)
$x->precision($n); # set P of $x to $n
$x->accuracy(); # return A of $x (or global, if A of $x undef)
$x->accuracy($n); # set A $x to $n
# Global methods
Math::BigInt->precision(); # get/set global P for all BigInt objects
Math::BigInt->accuracy(); # get/set global A for all BigInt objects
Math::BigInt->round_mode(); # get/set global round mode, one of
# 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
Math::BigInt->config(); # return hash containing configuration
=head1 DESCRIPTION
All operators (including basic math operations) are overloaded if you
declare your big integers as
$i = new Math::BigInt '123_456_789_123_456_789';
Operations with overloaded operators preserve the arguments which is
exactly what you expect.
=over 2
=item Input
Input values to these routines may be any string, that looks like a number
and results in an integer, including hexadecimal and binary numbers.
Scalars holding numbers may also be passed, but note that non-integer numbers
may already have lost precision due to the conversation to float. Quote
your input if you want BigInt to see all the digits:
$x = Math::BigInt->new(12345678890123456789); # bad
$x = Math::BigInt->new('12345678901234567890'); # good
You can include one underscore between any two digits.
This means integer values like 1.01E2 or even 1000E-2 are also accepted.
Non-integer values result in NaN.
Hexadecimal (prefixed with "0x") and binary numbers (prefixed with "0b")
are accepted, too. Please note that octal numbers are not recognized
by new(), so the following will print "123":
perl -MMath::BigInt -le 'print Math::BigInt->new("0123")'
To convert an octal number, use from_oct();
perl -MMath::BigInt -le 'print Math::BigInt->from_oct("0123")'
Currently, Math::BigInt::new() defaults to 0, while Math::BigInt::new('')
results in 'NaN'. This might change in the future, so use always the following
explicit forms to get a zero or NaN:
$zero = Math::BigInt->bzero();
$nan = Math::BigInt->bnan();
C<bnorm()> on a BigInt object is now effectively a no-op, since the numbers
are always stored in normalized form. If passed a string, creates a BigInt
object from the input.
=item Output
Output values are BigInt objects (normalized), except for the methods which
return a string (see L<SYNOPSIS>).
Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
C<is_nan()>, etc.) return true or false, while others (C<bcmp()>, C<bacmp()>)
return either undef (if NaN is involved), <0, 0 or >0 and are suited for sort.
=back
=head1 METHODS
Each of the methods below (except config(), accuracy() and precision())
accepts three additional parameters. These arguments C<$A>, C<$P> and C<$R>
are C<accuracy>, C<precision> and C<round_mode>. Please see the section about
L<ACCURACY and PRECISION> for more information.
=head2 config()
use Data::Dumper;
print Dumper ( Math::BigInt->config() );
print Math::BigInt->config()->{lib},"\n";
Returns a hash containing the configuration, e.g. the version number, lib
loaded etc. The following hash keys are currently filled in with the
appropriate information.
key Description
Example
============================================================
lib Name of the low-level math library
Math::BigInt::Calc
lib_version Version of low-level math library (see 'lib')
0.30
class The class name of config() you just called
Math::BigInt
upgrade To which class math operations might be upgraded
Math::BigFloat
downgrade To which class math operations might be downgraded
undef
precision Global precision
undef
accuracy Global accuracy
undef
round_mode Global round mode
even
version version number of the class you used
1.61
div_scale Fallback accuracy for div
40
trap_nan If true, traps creation of NaN via croak()
1
trap_inf If true, traps creation of +inf/-inf via croak()
1
The following values can be set by passing C<config()> a reference to a hash:
trap_inf trap_nan
upgrade downgrade precision accuracy round_mode div_scale
Example:
$new_cfg = Math::BigInt->config( { trap_inf => 1, precision => 5 } );
=head2 accuracy()
$x->accuracy(5); # local for $x
CLASS->accuracy(5); # global for all members of CLASS
# Note: This also applies to new()!
$A = $x->accuracy(); # read out accuracy that affects $x
$A = CLASS->accuracy(); # read out global accuracy
Set or get the global or local accuracy, aka how many significant digits the
results have. If you set a global accuracy, then this also applies to new()!
Warning! The accuracy I<sticks>, e.g. once you created a number under the
influence of C<< CLASS->accuracy($A) >>, all results from math operations with
that number will also be rounded.
In most cases, you should probably round the results explicitly using one of
L<round()>, L<bround()> or L<bfround()> or by passing the desired accuracy
to the math operation as additional parameter:
my $x = Math::BigInt->new(30000);
my $y = Math::BigInt->new(7);
print scalar $x->copy()->bdiv($y, 2); # print 4300
print scalar $x->copy()->bdiv($y)->bround(2); # print 4300
Please see the section about L<ACCURACY AND PRECISION> for further details.
Value must be greater than zero. Pass an undef value to disable it:
$x->accuracy(undef);
Math::BigInt->accuracy(undef);
Returns the current accuracy. For C<$x->accuracy()> it will return either the
local accuracy, or if not defined, the global. This means the return value
represents the accuracy that will be in effect for $x:
$y = Math::BigInt->new(1234567); # unrounded
print Math::BigInt->accuracy(4),"\n"; # set 4, print 4
$x = Math::BigInt->new(123456); # $x will be automatically rounded!
print "$x $y\n"; # '123500 1234567'
print $x->accuracy(),"\n"; # will be 4
print $y->accuracy(),"\n"; # also 4, since global is 4
print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5
print $x->accuracy(),"\n"; # still 4
print $y->accuracy(),"\n"; # 5, since global is 5
Note: Works also for subclasses like Math::BigFloat. Each class has it's own
globals separated from Math::BigInt, but it is possible to subclass
Math::BigInt and make the globals of the subclass aliases to the ones from
Math::BigInt.
=head2 precision()
$x->precision(-2); # local for $x, round at the second digit right of the dot
$x->precision(2); # ditto, round at the second digit left of the dot
CLASS->precision(5); # Global for all members of CLASS
# This also applies to new()!
CLASS->precision(-5); # ditto
$P = CLASS->precision(); # read out global precision
$P = $x->precision(); # read out precision that affects $x
Note: You probably want to use L<accuracy()> instead. With L<accuracy> you
set the number of digits each result should have, with L<precision> you
set the place where to round!
C<precision()> sets or gets the global or local precision, aka at which digit
before or after the dot to round all results. A set global precision also
applies to all newly created numbers!
In Math::BigInt, passing a negative number precision has no effect since no
numbers have digits after the dot. In L<Math::BigFloat>, it will round all
results to P digits after the dot.
Please see the section about L<ACCURACY AND PRECISION> for further details.
Pass an undef value to disable it:
$x->precision(undef);
Math::BigInt->precision(undef);
Returns the current precision. For C<$x->precision()> it will return either the
local precision of $x, or if not defined, the global. This means the return
value represents the prevision that will be in effect for $x:
$y = Math::BigInt->new(1234567); # unrounded
print Math::BigInt->precision(4),"\n"; # set 4, print 4
$x = Math::BigInt->new(123456); # will be automatically rounded
print $x; # print "120000"!
Note: Works also for subclasses like L<Math::BigFloat>. Each class has its
own globals separated from Math::BigInt, but it is possible to subclass
Math::BigInt and make the globals of the subclass aliases to the ones from
Math::BigInt.
=head2 brsft()
$x->brsft($y,$n);
Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2, but others work, too.
Right shifting usually amounts to dividing $x by $n ** $y and truncating the
result:
$x = Math::BigInt->new(10);
$x->brsft(1); # same as $x >> 1: 5
$x = Math::BigInt->new(1234);
$x->brsft(2,10); # result 12
There is one exception, and that is base 2 with negative $x:
$x = Math::BigInt->new(-5);
print $x->brsft(1);
This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
result).
=head2 new()
$x = Math::BigInt->new($str,$A,$P,$R);
Creates a new BigInt object from a scalar or another BigInt object. The
input is accepted as decimal, hex (with leading '0x') or binary (with leading
'0b').
See L<Input> for more info on accepted input formats.
=head2 from_oct()
$x = Math::BigInt->from_oct("0775"); # input is octal
=head2 from_hex()
$x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal
=head2 from_bin()
$x = Math::BigInt->from_oct("0x10011"); # input is binary
=head2 bnan()
$x = Math::BigInt->bnan();
Creates a new BigInt object representing NaN (Not A Number).
If used on an object, it will set it to NaN:
$x->bnan();
=head2 bzero()
$x = Math::BigInt->bzero();
Creates a new BigInt object representing zero.
If used on an object, it will set it to zero:
$x->bzero();
=head2 binf()
$x = Math::BigInt->binf($sign);
Creates a new BigInt object representing infinity. The optional argument is
either '-' or '+', indicating whether you want infinity or minus infinity.
If used on an object, it will set it to infinity:
$x->binf();
$x->binf('-');
=head2 bone()
$x = Math::BigInt->binf($sign);
Creates a new BigInt object representing one. The optional argument is
either '-' or '+', indicating whether you want one or minus one.
If used on an object, it will set it to one:
$x->bone(); # +1
$x->bone('-'); # -1
=head2 is_one()/is_zero()/is_nan()/is_inf()
$x->is_zero(); # true if arg is +0
$x->is_nan(); # true if arg is NaN
$x->is_one(); # true if arg is +1
$x->is_one('-'); # true if arg is -1
$x->is_inf(); # true if +inf
$x->is_inf('-'); # true if -inf (sign is default '+')
These methods all test the BigInt for being one specific value and return
true or false depending on the input. These are faster than doing something
like:
if ($x == 0)
=head2 is_pos()/is_neg()/is_positive()/is_negative()
$x->is_pos(); # true if > 0
$x->is_neg(); # true if < 0
The methods return true if the argument is positive or negative, respectively.
C<NaN> is neither positive nor negative, while C<+inf> counts as positive, and
C<-inf> is negative. A C<zero> is neither positive nor negative.
These methods are only testing the sign, and not the value.
C<is_positive()> and C<is_negative()> are aliases to C<is_pos()> and
C<is_neg()>, respectively. C<is_positive()> and C<is_negative()> were
introduced in v1.36, while C<is_pos()> and C<is_neg()> were only introduced
in v1.68.
=head2 is_odd()/is_even()/is_int()
$x->is_odd(); # true if odd, false for even
$x->is_even(); # true if even, false for odd
$x->is_int(); # true if $x is an integer
The return true when the argument satisfies the condition. C<NaN>, C<+inf>,
C<-inf> are not integers and are neither odd nor even.
In BigInt, all numbers except C<NaN>, C<+inf> and C<-inf> are integers.
=head2 bcmp()
$x->bcmp($y);
Compares $x with $y and takes the sign into account.
Returns -1, 0, 1 or undef.
=head2 bacmp()
$x->bacmp($y);
Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
=head2 sign()
$x->sign();
Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
If you want $x to have a certain sign, use one of the following methods:
$x->babs(); # '+'
$x->babs()->bneg(); # '-'
$x->bnan(); # 'NaN'
$x->binf(); # '+inf'
$x->binf('-'); # '-inf'
=head2 digit()
$x->digit($n); # return the nth digit, counting from right
If C<$n> is negative, returns the digit counting from left.
=head2 bneg()
$x->bneg();
Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
and '-inf', respectively. Does nothing for NaN or zero.
=head2 babs()
$x->babs();
Set the number to its absolute value, e.g. change the sign from '-' to '+'
and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
numbers.
=head2 bnorm()
$x->bnorm(); # normalize (no-op)
=head2 bnot()
$x->bnot();
Two's complement (bitwise not). This is equivalent to
$x->binc()->bneg();
but faster.
=head2 binc()
$x->binc(); # increment x by 1
=head2 bdec()
$x->bdec(); # decrement x by 1
=head2 badd()
$x->badd($y); # addition (add $y to $x)
=head2 bsub()
$x->bsub($y); # subtraction (subtract $y from $x)
=head2 bmul()
$x->bmul($y); # multiplication (multiply $x by $y)
=head2 bmuladd()
$x->bmuladd($y,$z);
Multiply $x by $y, and then add $z to the result,
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 bdiv()
$x->bdiv($y); # divide, set $x to quotient
# return (quo,rem) or quo if scalar
=head2 bmod()
$x->bmod($y); # modulus (x % y)
=head2 bmodinv()
num->bmodinv($mod); # modular inverse
Returns the inverse of C<$num> in the given modulus C<$mod>. 'C<NaN>' is
returned unless C<$num> is relatively prime to C<$mod>, i.e. unless
C<bgcd($num, $mod)==1>.
=head2 bmodpow()
$num->bmodpow($exp,$mod); # modular exponentation
# ($num**$exp % $mod)
Returns the value of C<$num> taken to the power C<$exp> in the modulus
C<$mod> using binary exponentation. C<bmodpow> is far superior to
writing
$num ** $exp % $mod
because it is much faster - it reduces internal variables into
the modulus whenever possible, so it operates on smaller numbers.
C<bmodpow> also supports negative exponents.
bmodpow($num, -1, $mod)
is exactly equivalent to
bmodinv($num, $mod)
=head2 bpow()
$x->bpow($y); # power of arguments (x ** y)
=head2 blog()
$x->blog($base, $accuracy); # logarithm of x to the base $base
If C<$base> is not defined, Euler's number (e) is used:
print $x->blog(undef, 100); # log(x) to 100 digits
=head2 bexp()
$x->bexp($accuracy); # calculate e ** X
Calculates the expression C<e ** $x> where C<e> is Euler's number.
This method was added in v1.82 of Math::BigInt (April 2007).
See also L<blog()>.
=head2 bnok()
$x->bnok($y); # x over y (binomial coefficient n over k)
Calculates the binomial coefficient n over k, also called the "choose"
function. The result is equivalent to:
( n ) n!
| - | = -------
( k ) k!(n-k)!
This method was added in v1.84 of Math::BigInt (April 2007).
=head2 bpi()
print Math::BigInt->bpi(100), "\n"; # 3
Returns PI truncated to an integer, with the argument being ignored. This means
under BigInt this always returns C<3>.
If upgrading is in effect, returns PI, rounded to N digits with the
current rounding mode:
use Math::BigFloat;
use Math::BigInt upgrade => Math::BigFloat;
print Math::BigInt->bpi(3), "\n"; # 3.14
print Math::BigInt->bpi(100), "\n"; # 3.1415....
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 bcos()
my $x = Math::BigInt->new(1);
print $x->bcos(100), "\n";
Calculate the cosinus of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an
integer.
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 bsin()
my $x = Math::BigInt->new(1);
print $x->bsin(100), "\n";
Calculate the sinus of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an
integer.
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 batan2()
my $x = Math::BigInt->new(1);
my $y = Math::BigInt->new(1);
print $y->batan2($x), "\n";
Calculate the arcus tangens of C<$y> divided by C<$x>, modifying $y in place.
In BigInt, unless upgrading is in effect, the result is truncated to an
integer.
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 batan()
my $x = Math::BigFloat->new(0.5);
print $x->batan(100), "\n";
Calculate the arcus tangens of $x, modifying $x in place.
In BigInt, unless upgrading is in effect, the result is truncated to an
integer.
This method was added in v1.87 of Math::BigInt (June 2007).
=head2 blsft()
$x->blsft($y); # left shift in base 2
$x->blsft($y,$n); # left shift, in base $n (like 10)
=head2 brsft()
$x->brsft($y); # right shift in base 2
$x->brsft($y,$n); # right shift, in base $n (like 10)
=head2 band()
$x->band($y); # bitwise and
=head2 bior()
$x->bior($y); # bitwise inclusive or
=head2 bxor()
$x->bxor($y); # bitwise exclusive or
=head2 bnot()
$x->bnot(); # bitwise not (two's complement)
=head2 bsqrt()
$x->bsqrt(); # calculate square-root
=head2 broot()
$x->broot($N);
Calculates the N'th root of C<$x>.
=head2 bfac()
$x->bfac(); # factorial of $x (1*2*3*4*..$x)
=head2 round()
$x->round($A,$P,$round_mode);
Round $x to accuracy C<$A> or precision C<$P> using the round mode
C<$round_mode>.
=head2 bround()
$x->bround($N); # accuracy: preserve $N digits
=head2 bfround()
$x->bfround($N);
If N is > 0, rounds to the Nth digit from the left. If N < 0, rounds to
the Nth digit after the dot. Since BigInts are integers, the case N < 0
is a no-op for them.
Examples:
Input N Result
===================================================
123456.123456 3 123500
123456.123456 2 123450
123456.123456 -2 123456.12
123456.123456 -3 123456.123
=head2 bfloor()
$x->bfloor();
Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
does change $x in BigFloat.
=head2 bceil()
$x->bceil();
Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
does change $x in BigFloat.
=head2 bgcd()
bgcd(@values); # greatest common divisor (no OO style)
=head2 blcm()
blcm(@values); # lowest common multiplicator (no OO style)
head2 length()
$x->length();
($xl,$fl) = $x->length();
Returns the number of digits in the decimal representation of the number.
In list context, returns the length of the integer and fraction part. For
BigInt's, the length of the fraction part will always be 0.
=head2 exponent()
$x->exponent();
Return the exponent of $x as BigInt.
=head2 mantissa()
$x->mantissa();
Return the signed mantissa of $x as BigInt.
=head2 parts()
$x->parts(); # return (mantissa,exponent) as BigInt
=head2 copy()
$x->copy(); # make a true copy of $x (unlike $y = $x;)
=head2 as_int()/as_number()
$x->as_int();
Returns $x as a BigInt (truncated towards zero). In BigInt this is the same as
C<copy()>.
C<as_number()> is an alias to this method. C<as_number> was introduced in
v1.22, while C<as_int()> was only introduced in v1.68.
=head2 bstr()
$x->bstr();
Returns a normalized string representation of C<$x>.
=head2 bsstr()
$x->bsstr(); # normalized string in scientific notation
=head2 as_hex()
$x->as_hex(); # as signed hexadecimal string with prefixed 0x
=head2 as_bin()
$x->as_bin(); # as signed binary string with prefixed 0b
=head2 as_oct()
$x->as_oct(); # as signed octal string with prefixed 0
=head2 numify()
print $x->numify();
This returns a normal Perl scalar from $x. It is used automatically
whenever a scalar is needed, for instance in array index operations.
This loses precision, to avoid this use L<as_int()> instead.
=head2 modify()
$x->modify('bpowd');
This method returns 0 if the object can be modified with the given
peration, or 1 if not.
This is used for instance by L<Math::BigInt::Constant>.
=head2 upgrade()/downgrade()
Set/get the class for downgrade/upgrade operations. Thuis is used
for instance by L<bignum>. The defaults are '', thus the following
operation will create a BigInt, not a BigFloat:
my $i = Math::BigInt->new(123);
my $f = Math::BigFloat->new('123.1');
print $i + $f,"\n"; # print 246
=head2 div_scale()
Set/get the number of digits for the default precision in divide
operations.
=head2 round_mode()
Set/get the current round mode.
=head1 ACCURACY and PRECISION
Since version v1.33, Math::BigInt and Math::BigFloat have full support for
accuracy and precision based rounding, both automatically after every
operation, as well as manually.
This section describes the accuracy/precision handling in Math::Big* as it
used to be and as it is now, complete with an explanation of all terms and
abbreviations.
Not yet implemented things (but with correct description) are marked with '!',
things that need to be answered are marked with '?'.
In the next paragraph follows a short description of terms used here (because
these may differ from terms used by others people or documentation).
During the rest of this document, the shortcuts A (for accuracy), P (for
precision), F (fallback) and R (rounding mode) will be used.
=head2 Precision P
A fixed number of digits before (positive) or after (negative)
the decimal point. For example, 123.45 has a precision of -2. 0 means an
integer like 123 (or 120). A precision of 2 means two digits to the left
of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
numbers with zeros before the decimal point may have different precisions,
because 1200 can have p = 0, 1 or 2 (depending on what the inital value
was). It could also have p < 0, when the digits after the decimal point
are zero.
The string output (of floating point numbers) will be padded with zeros:
Initial value P A Result String
------------------------------------------------------------
1234.01 -3 1000 1000
1234 -2 1200 1200
1234.5 -1 1230 1230
1234.001 1 1234 1234.0
1234.01 0 1234 1234
1234.01 2 1234.01 1234.01
1234.01 5 1234.01 1234.01000
For BigInts, no padding occurs.
=head2 Accuracy A
Number of significant digits. Leading zeros are not counted. A
number may have an accuracy greater than the non-zero digits
when there are zeros in it or trailing zeros. For example, 123.456 has
A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
The string output (of floating point numbers) will be padded with zeros:
Initial value P A Result String
------------------------------------------------------------
1234.01 3 1230 1230
1234.01 6 1234.01 1234.01
1234.1 8 1234.1 1234.1000
For BigInts, no padding occurs.
=head2 Fallback F
When both A and P are undefined, this is used as a fallback accuracy when
dividing numbers.
=head2 Rounding mode R
When rounding a number, different 'styles' or 'kinds'
of rounding are possible. (Note that random rounding, as in
Math::Round, is not implemented.)
=over 2
=item 'trunc'
truncation invariably removes all digits following the
rounding place, replacing them with zeros. Thus, 987.65 rounded
to tens (P=1) becomes 980, and rounded to the fourth sigdig
becomes 987.6 (A=4). 123.456 rounded to the second place after the
decimal point (P=-2) becomes 123.46.
All other implemented styles of rounding attempt to round to the
"nearest digit." If the digit D immediately to the right of the
rounding place (skipping the decimal point) is greater than 5, the
number is incremented at the rounding place (possibly causing a
cascade of incrementation): e.g. when rounding to units, 0.9 rounds
to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
truncated at the rounding place: e.g. when rounding to units, 0.4
rounds to 0, and -19.4 rounds to -19.
However the results of other styles of rounding differ if the
digit immediately to the right of the rounding place (skipping the
decimal point) is 5 and if there are no digits, or no digits other
than 0, after that 5. In such cases:
=item 'even'
rounds the digit at the rounding place to 0, 2, 4, 6, or 8
if it is not already. E.g., when rounding to the first sigdig, 0.45
becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
=item 'odd'
rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
it is not already. E.g., when rounding to the first sigdig, 0.45
becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
=item '+inf'
round to plus infinity, i.e. always round up. E.g., when
rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
and 0.4501 also becomes 0.5.
=item '-inf'
round to minus infinity, i.e. always round down. E.g., when
rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
but 0.4501 becomes 0.5.
=item 'zero'
round to zero, i.e. positive numbers down, negative ones up.
E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
becomes -0.5, but 0.4501 becomes 0.5.
=item 'common'
round up if the digit immediately to the right of the rounding place
is 5 or greater, otherwise round down. E.g., 0.15 becomes 0.2 and
0.149 becomes 0.1.
=back
The handling of A & P in MBI/MBF (the old core code shipped with Perl
versions <= 5.7.2) is like this:
=over 2
=item Precision
* ffround($p) is able to round to $p number of digits after the decimal
point
* otherwise P is unused
=item Accuracy (significant digits)
* fround($a) rounds to $a significant digits
* only fdiv() and fsqrt() take A as (optional) paramater
+ other operations simply create the same number (fneg etc), or more (fmul)
of digits
+ rounding/truncating is only done when explicitly calling one of fround
or ffround, and never for BigInt (not implemented)
* fsqrt() simply hands its accuracy argument over to fdiv.
* the documentation and the comment in the code indicate two different ways
on how fdiv() determines the maximum number of digits it should calculate,
and the actual code does yet another thing
POD:
max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
Comment:
result has at most max(scale, length(dividend), length(divisor)) digits
Actual code:
scale = max(scale, length(dividend)-1,length(divisor)-1);
scale += length(divisor) - length(dividend);
So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
Actually, the 'difference' added to the scale is calculated from the
number of "significant digits" in dividend and divisor, which is derived
by looking at the length of the mantissa. Which is wrong, since it includes
the + sign (oops) and actually gets 2 for '+100' and 4 for '+101'. Oops
again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
assumption that 124 has 3 significant digits, while 120/7 will get you
'17', not '17.1' since 120 is thought to have 2 significant digits.
The rounding after the division then uses the remainder and $y to determine
wether it must round up or down.
? I have no idea which is the right way. That's why I used a slightly more
? simple scheme and tweaked the few failing testcases to match it.
=back
This is how it works now:
=over 2
=item Setting/Accessing
* You can set the A global via C<< Math::BigInt->accuracy() >> or
C<< Math::BigFloat->accuracy() >> or whatever class you are using.
* You can also set P globally by using C<< Math::SomeClass->precision() >>
likewise.
* Globals are classwide, and not inherited by subclasses.
* to undefine A, use C<< Math::SomeCLass->accuracy(undef); >>
* to undefine P, use C<< Math::SomeClass->precision(undef); >>
* Setting C<< Math::SomeClass->accuracy() >> clears automatically
C<< Math::SomeClass->precision() >>, and vice versa.
* To be valid, A must be > 0, P can have any value.
* If P is negative, this means round to the P'th place to the right of the
decimal point; positive values mean to the left of the decimal point.
P of 0 means round to integer.
* to find out the current global A, use C<< Math::SomeClass->accuracy() >>
* to find out the current global P, use C<< Math::SomeClass->precision() >>
* use C<< $x->accuracy() >> respective C<< $x->precision() >> for the local
setting of C<< $x >>.
* Please note that C<< $x->accuracy() >> respective C<< $x->precision() >>
return eventually defined global A or P, when C<< $x >>'s A or P is not
set.
=item Creating numbers
* When you create a number, you can give the desired A or P via:
$x = Math::BigInt->new($number,$A,$P);
* Only one of A or P can be defined, otherwise the result is NaN
* If no A or P is give ($x = Math::BigInt->new($number) form), then the
globals (if set) will be used. Thus changing the global defaults later on
will not change the A or P of previously created numbers (i.e., A and P of
$x will be what was in effect when $x was created)
* If given undef for A and P, B<no> rounding will occur, and the globals will
B<not> be used. This is used by subclasses to create numbers without
suffering rounding in the parent. Thus a subclass is able to have its own
globals enforced upon creation of a number by using
C<< $x = Math::BigInt->new($number,undef,undef) >>:
use Math::BigInt::SomeSubclass;
use Math::BigInt;
Math::BigInt->accuracy(2);
Math::BigInt::SomeSubClass->accuracy(3);
$x = Math::BigInt::SomeSubClass->new(1234);
$x is now 1230, and not 1200. A subclass might choose to implement
this otherwise, e.g. falling back to the parent's A and P.
=item Usage
* If A or P are enabled/defined, they are used to round the result of each
operation according to the rules below
* Negative P is ignored in Math::BigInt, since BigInts never have digits
after the decimal point
* Math::BigFloat uses Math::BigInt internally, but setting A or P inside
Math::BigInt as globals does not tamper with the parts of a BigFloat.
A flag is used to mark all Math::BigFloat numbers as 'never round'.
=item Precedence
* It only makes sense that a number has only one of A or P at a time.
If you set either A or P on one object, or globally, the other one will
be automatically cleared.
* If two objects are involved in an operation, and one of them has A in
effect, and the other P, this results in an error (NaN).
* A takes precedence over P (Hint: A comes before P).
If neither of them is defined, nothing is used, i.e. the result will have
as many digits as it can (with an exception for fdiv/fsqrt) and will not
be rounded.
* There is another setting for fdiv() (and thus for fsqrt()). If neither of
A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
If either the dividend's or the divisor's mantissa has more digits than
the value of F, the higher value will be used instead of F.
This is to limit the digits (A) of the result (just consider what would
happen with unlimited A and P in the case of 1/3 :-)
* fdiv will calculate (at least) 4 more digits than required (determined by
A, P or F), and, if F is not used, round the result
(this will still fail in the case of a result like 0.12345000000001 with A
or P of 5, but this can not be helped - or can it?)
* Thus you can have the math done by on Math::Big* class in two modi:
+ never round (this is the default):
This is done by setting A and P to undef. No math operation
will round the result, with fdiv() and fsqrt() as exceptions to guard
against overflows. You must explicitly call bround(), bfround() or
round() (the latter with parameters).
Note: Once you have rounded a number, the settings will 'stick' on it
and 'infect' all other numbers engaged in math operations with it, since
local settings have the highest precedence. So, to get SaferRound[tm],
use a copy() before rounding like this:
$x = Math::BigFloat->new(12.34);
$y = Math::BigFloat->new(98.76);
$z = $x * $y; # 1218.6984
print $x->copy()->fround(3); # 12.3 (but A is now 3!)
$z = $x * $y; # still 1218.6984, without
# copy would have been 1210!
+ round after each op:
After each single operation (except for testing like is_zero()), the
method round() is called and the result is rounded appropriately. By
setting proper values for A and P, you can have all-the-same-A or
all-the-same-P modes. For example, Math::Currency might set A to undef,
and P to -2, globally.
?Maybe an extra option that forbids local A & P settings would be in order,
?so that intermediate rounding does not 'poison' further math?
=item Overriding globals
* you will be able to give A, P and R as an argument to all the calculation
routines; the second parameter is A, the third one is P, and the fourth is
R (shift right by one for binary operations like badd). P is used only if
the first parameter (A) is undefined. These three parameters override the
globals in the order detailed as follows, i.e. the first defined value
wins:
(local: per object, global: global default, parameter: argument to sub)
+ parameter A
+ parameter P
+ local A (if defined on both of the operands: smaller one is taken)
+ local P (if defined on both of the operands: bigger one is taken)
+ global A
+ global P
+ global F
* fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
arguments (A and P) instead of one
=item Local settings
* You can set A or P locally by using C<< $x->accuracy() >> or
C<< $x->precision() >>
and thus force different A and P for different objects/numbers.
* Setting A or P this way immediately rounds $x to the new value.
* C<< $x->accuracy() >> clears C<< $x->precision() >>, and vice versa.
=item Rounding
* the rounding routines will use the respective global or local settings.
fround()/bround() is for accuracy rounding, while ffround()/bfround()
is for precision
* the two rounding functions take as the second parameter one of the
following rounding modes (R):
'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common'
* you can set/get the global R by using C<< Math::SomeClass->round_mode() >>
or by setting C<< $Math::SomeClass::round_mode >>
* after each operation, C<< $result->round() >> is called, and the result may
eventually be rounded (that is, if A or P were set either locally,
globally or as parameter to the operation)
* to manually round a number, call C<< $x->round($A,$P,$round_mode); >>
this will round the number by using the appropriate rounding function
and then normalize it.
* rounding modifies the local settings of the number:
$x = Math::BigFloat->new(123.456);
$x->accuracy(5);
$x->bround(4);
Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
will be 4 from now on.
=item Default values
* R: 'even'
* F: 40
* A: undef
* P: undef
=item Remarks
* The defaults are set up so that the new code gives the same results as
the old code (except in a few cases on fdiv):
+ Both A and P are undefined and thus will not be used for rounding
after each operation.
+ round() is thus a no-op, unless given extra parameters A and P
=back
=head1 Infinity and Not a Number
While BigInt has extensive handling of inf and NaN, certain quirks remain.
=over 2
=item oct()/hex()
These perl routines currently (as of Perl v.5.8.6) cannot handle passed
inf.
te@linux:~> perl -wle 'print 2 ** 3333'
inf
te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333'
1
te@linux:~> perl -wle 'print oct(2 ** 3333)'
0
te@linux:~> perl -wle 'print hex(2 ** 3333)'
Illegal hexadecimal digit 'i' ignored at -e line 1.
0
The same problems occur if you pass them Math::BigInt->binf() objects. Since
overloading these routines is not possible, this cannot be fixed from BigInt.
=item ==, !=, <, >, <=, >= with NaNs
BigInt's bcmp() routine currently returns undef to signal that a NaN was
involved in a comparison. However, the overload code turns that into
either 1 or '' and thus operations like C<< NaN != NaN >> might return
wrong values.
=item log(-inf)
C<< log(-inf) >> is highly weird. Since log(-x)=pi*i+log(x), then
log(-inf)=pi*i+inf. However, since the imaginary part is finite, the real
infinity "overshadows" it, so the number might as well just be infinity.
However, the result is a complex number, and since BigInt/BigFloat can only
have real numbers as results, the result is NaN.
=item exp(), cos(), sin(), atan2()
These all might have problems handling infinity right.
=back
=head1 INTERNALS
The actual numbers are stored as unsigned big integers (with seperate sign).
You should neither care about nor depend on the internal representation; it
might change without notice. Use B<ONLY> method calls like C<< $x->sign(); >>
instead relying on the internal representation.
=head2 MATH LIBRARY
Math with the numbers is done (by default) by a module called
C<Math::BigInt::Calc>. This is equivalent to saying:
use Math::BigInt try => 'Calc';
You can change this backend library by using:
use Math::BigInt try => 'GMP';
B<Note>: General purpose packages should not be explicit about the library
to use; let the script author decide which is best.
If your script works with huge numbers and Calc is too slow for them,
you can also for the loading of one of these libraries and if none
of them can be used, the code will die:
use Math::BigInt only => 'GMP,Pari';
The following would first try to find Math::BigInt::Foo, then
Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
use Math::BigInt try => 'Foo,Math::BigInt::Bar';
The library that is loaded last will be used. Note that this can be
overwritten at any time by loading a different library, and numbers
constructed with different libraries cannot be used in math operations
together.
=head3 What library to use?
B<Note>: General purpose packages should not be explicit about the library
to use; let the script author decide which is best.
L<Math::BigInt::GMP> and L<Math::BigInt::Pari> are in cases involving big
numbers much faster than Calc, however it is slower when dealing with very
small numbers (less than about 20 digits) and when converting very large
numbers to decimal (for instance for printing, rounding, calculating their
length in decimal etc).
So please select carefully what libary you want to use.
Different low-level libraries use different formats to store the numbers.
However, you should B<NOT> depend on the number having a specific format
internally.
See the respective math library module documentation for further details.
=head2 SIGN
The sign is either '+', '-', 'NaN', '+inf' or '-inf'.
A sign of 'NaN' is used to represent the result when input arguments are not
numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
minus infinity. You will get '+inf' when dividing a positive number by 0, and
'-inf' when dividing any negative number by 0.
=head2 mantissa(), exponent() and parts()
C<mantissa()> and C<exponent()> return the said parts of the BigInt such
that:
$m = $x->mantissa();
$e = $x->exponent();
$y = $m * ( 10 ** $e );
print "ok\n" if $x == $y;
C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
in one go. Both the returned mantissa and exponent have a sign.
Currently, for BigInts C<$e> is always 0, except +inf and -inf, where it is
C<+inf>; and for NaN, where it is C<NaN>; and for C<$x == 0>, where it is C<1>
(to be compatible with Math::BigFloat's internal representation of a zero as
C<0E1>).
C<$m> is currently just a copy of the original number. The relation between
C<$e> and C<$m> will stay always the same, though their real values might
change.
=head1 EXAMPLES
use Math::BigInt;
sub bint { Math::BigInt->new(shift); }
$x = Math::BigInt->bstr("1234") # string "1234"
$x = "$x"; # same as bstr()
$x = Math::BigInt->bneg("1234"); # BigInt "-1234"
$x = Math::BigInt->babs("-12345"); # BigInt "12345"
$x = Math::BigInt->bnorm("-0.00"); # BigInt "0"
$x = bint(1) + bint(2); # BigInt "3"
$x = bint(1) + "2"; # ditto (auto-BigIntify of "2")
$x = bint(1); # BigInt "1"
$x = $x + 5 / 2; # BigInt "3"
$x = $x ** 3; # BigInt "27"
$x *= 2; # BigInt "54"
$x = Math::BigInt->new(0); # BigInt "0"
$x--; # BigInt "-1"
$x = Math::BigInt->badd(4,5) # BigInt "9"
print $x->bsstr(); # 9e+0
Examples for rounding:
use Math::BigFloat;
use Test;
$x = Math::BigFloat->new(123.4567);
$y = Math::BigFloat->new(123.456789);
Math::BigFloat->accuracy(4); # no more A than 4
ok ($x->copy()->fround(),123.4); # even rounding
print $x->copy()->fround(),"\n"; # 123.4
Math::BigFloat->round_mode('odd'); # round to odd
print $x->copy()->fround(),"\n"; # 123.5
Math::BigFloat->accuracy(5); # no more A than 5
Math::BigFloat->round_mode('odd'); # round to odd
print $x->copy()->fround(),"\n"; # 123.46
$y = $x->copy()->fround(4),"\n"; # A = 4: 123.4
print "$y, ",$y->accuracy(),"\n"; # 123.4, 4
Math::BigFloat->accuracy(undef); # A not important now
Math::BigFloat->precision(2); # P important
print $x->copy()->bnorm(),"\n"; # 123.46
print $x->copy()->fround(),"\n"; # 123.46
Examples for converting:
my $x = Math::BigInt->new('0b1'.'01' x 123);
print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
=head1 Autocreating constants
After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
and binary constants in the given scope are converted to C<Math::BigInt>.
This conversion happens at compile time.
In particular,
perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
prints the integer value of C<2**100>. Note that without conversion of
constants the expression 2**100 will be calculated as perl scalar.
Please note that strings and floating point constants are not affected,
so that
use Math::BigInt qw/:constant/;
$x = 1234567890123456789012345678901234567890
+ 123456789123456789;
$y = '1234567890123456789012345678901234567890'
+ '123456789123456789';
do not work. You need an explicit Math::BigInt->new() around one of the
operands. You should also quote large constants to protect loss of precision:
use Math::BigInt;
$x = Math::BigInt->new('1234567889123456789123456789123456789');
Without the quotes Perl would convert the large number to a floating point
constant at compile time and then hand the result to BigInt, which results in
an truncated result or a NaN.
This also applies to integers that look like floating point constants:
use Math::BigInt ':constant';
print ref(123e2),"\n";
print ref(123.2e2),"\n";
will print nothing but newlines. Use either L<bignum> or L<Math::BigFloat>
to get this to work.
=head1 PERFORMANCE
Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
must be made in the second case. For long numbers, the copy can eat up to 20%
of the work (in the case of addition/subtraction, less for
multiplication/division). If $y is very small compared to $x, the form
$x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
more time then the actual addition.
With a technique called copy-on-write, the cost of copying with overload could
be minimized or even completely avoided. A test implementation of COW did show
performance gains for overloaded math, but introduced a performance loss due
to a constant overhead for all other operations. So Math::BigInt does currently
not COW.
The rewritten version of this module (vs. v0.01) is slower on certain
operations, like C<new()>, C<bstr()> and C<numify()>. The reason are that it
does now more work and handles much more cases. The time spent in these
operations is usually gained in the other math operations so that code on
the average should get (much) faster. If they don't, please contact the author.
Some operations may be slower for small numbers, but are significantly faster
for big numbers. Other operations are now constant (O(1), like C<bneg()>,
C<babs()> etc), instead of O(N) and thus nearly always take much less time.
These optimizations were done on purpose.
If you find the Calc module to slow, try to install any of the replacement
modules and see if they help you.
=head2 Alternative math libraries
You can use an alternative library to drive Math::BigInt. See the section
L<MATH LIBRARY> for more information.
For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
=head2 SUBCLASSING
=head1 Subclassing Math::BigInt
The basic design of Math::BigInt allows simple subclasses with very little
work, as long as a few simple rules are followed:
=over 2
=item *
The public API must remain consistent, i.e. if a sub-class is overloading
addition, the sub-class must use the same name, in this case badd(). The
reason for this is that Math::BigInt is optimized to call the object methods
directly.
=item *
The private object hash keys like C<$x->{sign}> may not be changed, but
additional keys can be added, like C<$x->{_custom}>.
=item *
Accessor functions are available for all existing object hash keys and should
be used instead of directly accessing the internal hash keys. The reason for
this is that Math::BigInt itself has a pluggable interface which permits it
to support different storage methods.
=back
More complex sub-classes may have to replicate more of the logic internal of
Math::BigInt if they need to change more basic behaviors. A subclass that
needs to merely change the output only needs to overload C<bstr()>.
All other object methods and overloaded functions can be directly inherited
from the parent class.
At the very minimum, any subclass will need to provide its own C<new()> and can
store additional hash keys in the object. There are also some package globals
that must be defined, e.g.:
# Globals
$accuracy = undef;
$precision = -2; # round to 2 decimal places
$round_mode = 'even';
$div_scale = 40;
Additionally, you might want to provide the following two globals to allow
auto-upgrading and auto-downgrading to work correctly:
$upgrade = undef;
$downgrade = undef;
This allows Math::BigInt to correctly retrieve package globals from the
subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or
t/Math/BigFloat/SubClass.pm completely functional subclass examples.
Don't forget to
use overload;
in your subclass to automatically inherit the overloading from the parent. If
you like, you can change part of the overloading, look at Math::String for an
example.
=head1 UPGRADING
When used like this:
use Math::BigInt upgrade => 'Foo::Bar';
certain operations will 'upgrade' their calculation and thus the result to
the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
use Math::BigInt upgrade => 'Math::BigFloat';
As a shortcut, you can use the module C<bignum>:
use bignum;
Also good for oneliners:
perl -Mbignum -le 'print 2 ** 255'
This makes it possible to mix arguments of different classes (as in 2.5 + 2)
as well es preserve accuracy (as in sqrt(3)).
Beware: This feature is not fully implemented yet.
=head2 Auto-upgrade
The following methods upgrade themselves unconditionally; that is if upgrade
is in effect, they will always hand up their work:
=over 2
=item bsqrt()
=item div()
=item blog()
=item bexp()
=back
Beware: This list is not complete.
All other methods upgrade themselves only when one (or all) of their
arguments are of the class mentioned in $upgrade (This might change in later
versions to a more sophisticated scheme):
=head1 EXPORTS
C<Math::BigInt> exports nothing by default, but can export the following methods:
bgcd
blcm
=head1 CAVEATS
Some things might not work as you expect them. Below is documented what is
known to be troublesome:
=over 1
=item bstr(), bsstr() and 'cmp'
Both C<bstr()> and C<bsstr()> as well as automated stringify via overload now
drop the leading '+'. The old code would return '+3', the new returns '3'.
This is to be consistent with Perl and to make C<cmp> (especially with
overloading) to work as you expect. It also solves problems with C<Test.pm>,
because its C<ok()> uses 'eq' internally.
Mark Biggar said, when asked about to drop the '+' altogether, or make only
C<cmp> work:
I agree (with the first alternative), don't add the '+' on positive
numbers. It's not as important anymore with the new internal
form for numbers. It made doing things like abs and neg easier,
but those have to be done differently now anyway.
So, the following examples will now work all as expected:
use Test;
BEGIN { plan tests => 1 }
use Math::BigInt;
my $x = new Math::BigInt 3*3;
my $y = new Math::BigInt 3*3;
ok ($x,3*3);
print "$x eq 9" if $x eq $y;
print "$x eq 9" if $x eq '9';
print "$x eq 9" if $x eq 3*3;
Additionally, the following still works:
print "$x == 9" if $x == $y;
print "$x == 9" if $x == 9;
print "$x == 9" if $x == 3*3;
There is now a C<bsstr()> method to get the string in scientific notation aka
C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
for comparison, but Perl will represent some numbers as 100 and others
as 1e+308. If in doubt, convert both arguments to Math::BigInt before
comparing them as strings:
use Test;
BEGIN { plan tests => 3 }
use Math::BigInt;
$x = Math::BigInt->new('1e56'); $y = 1e56;
ok ($x,$y); # will fail
ok ($x->bsstr(),$y); # okay
$y = Math::BigInt->new($y);
ok ($x,$y); # okay
Alternatively, simple use C<< <=> >> for comparisons, this will get it
always right. There is not yet a way to get a number automatically represented
as a string that matches exactly the way Perl represents it.
See also the section about L<Infinity and Not a Number> for problems in
comparing NaNs.
=item int()
C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a
Perl scalar:
$x = Math::BigInt->new(123);
$y = int($x); # BigInt 123
$x = Math::BigFloat->new(123.45);
$y = int($x); # BigInt 123
In all Perl versions you can use C<as_number()> or C<as_int> for the same
effect:
$x = Math::BigFloat->new(123.45);
$y = $x->as_number(); # BigInt 123
$y = $x->as_int(); # ditto
This also works for other subclasses, like Math::String.
If you want a real Perl scalar, use C<numify()>:
$y = $x->numify(); # 123 as scalar
This is seldom necessary, though, because this is done automatically, like
when you access an array:
$z = $array[$x]; # does work automatically
=item length
The following will probably not do what you expect:
$c = Math::BigInt->new(123);
print $c->length(),"\n"; # prints 30
It prints both the number of digits in the number and in the fraction part
since print calls C<length()> in list context. Use something like:
print scalar $c->length(),"\n"; # prints 3
=item bdiv
The following will probably not do what you expect:
print $c->bdiv(10000),"\n";
It prints both quotient and remainder since print calls C<bdiv()> in list
context. Also, C<bdiv()> will modify $c, so be careful. You probably want
to use
print $c / 10000,"\n";
print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c
instead.
The quotient is always the greatest integer less than or equal to the
real-valued quotient of the two operands, and the remainder (when it is
nonzero) always has the same sign as the second operand; so, for
example,
1 / 4 => ( 0, 1)
1 / -4 => (-1,-3)
-3 / 4 => (-1, 1)
-3 / -4 => ( 0,-3)
-11 / 2 => (-5,1)
11 /-2 => (-5,-1)
As a consequence, the behavior of the operator % agrees with the
behavior of Perl's built-in % operator (as documented in the perlop
manpage), and the equation
$x == ($x / $y) * $y + ($x % $y)
holds true for any $x and $y, which justifies calling the two return
values of bdiv() the quotient and remainder. The only exception to this rule
are when $y == 0 and $x is negative, then the remainder will also be
negative. See below under "infinity handling" for the reasoning behind this.
Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
not change BigInt's way to do things. This is because under 'use integer' Perl
will do what the underlying C thinks is right and this is different for each
system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
the author to implement it ;)
=item infinity handling
Here are some examples that explain the reasons why certain results occur while
handling infinity:
The following table shows the result of the division and the remainder, so that
the equation above holds true. Some "ordinary" cases are strewn in to show more
clearly the reasoning:
A / B = C, R so that C * B + R = A
=========================================================
5 / 8 = 0, 5 0 * 8 + 5 = 5
0 / 8 = 0, 0 0 * 8 + 0 = 0
0 / inf = 0, 0 0 * inf + 0 = 0
0 /-inf = 0, 0 0 * -inf + 0 = 0
5 / inf = 0, 5 0 * inf + 5 = 5
5 /-inf = 0, 5 0 * -inf + 5 = 5
-5/ inf = 0, -5 0 * inf + -5 = -5
-5/-inf = 0, -5 0 * -inf + -5 = -5
inf/ 5 = inf, 0 inf * 5 + 0 = inf
-inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf
inf/ -5 = -inf, 0 -inf * -5 + 0 = inf
-inf/ -5 = inf, 0 inf * -5 + 0 = -inf
5/ 5 = 1, 0 1 * 5 + 0 = 5
-5/ -5 = 1, 0 1 * -5 + 0 = -5
inf/ inf = 1, 0 1 * inf + 0 = inf
-inf/-inf = 1, 0 1 * -inf + 0 = -inf
inf/-inf = -1, 0 -1 * -inf + 0 = inf
-inf/ inf = -1, 0 1 * -inf + 0 = -inf
8/ 0 = inf, 8 inf * 0 + 8 = 8
inf/ 0 = inf, inf inf * 0 + inf = inf
0/ 0 = NaN
These cases below violate the "remainder has the sign of the second of the two
arguments", since they wouldn't match up otherwise.
A / B = C, R so that C * B + R = A
========================================================
-inf/ 0 = -inf, -inf -inf * 0 + inf = -inf
-8/ 0 = -inf, -8 -inf * 0 + 8 = -8
=item Modifying and =
Beware of:
$x = Math::BigFloat->new(5);
$y = $x;
It will not do what you think, e.g. making a copy of $x. Instead it just makes
a second reference to the B<same> object and stores it in $y. Thus anything
that modifies $x (except overloaded operators) will modify $y, and vice versa.
Or in other words, C<=> is only safe if you modify your BigInts only via
overloaded math. As soon as you use a method call it breaks:
$x->bmul(2);
print "$x, $y\n"; # prints '10, 10'
If you want a true copy of $x, use:
$y = $x->copy();
You can also chain the calls like this, this will make first a copy and then
multiply it by 2:
$y = $x->copy()->bmul(2);
See also the documentation for overload.pm regarding C<=>.
=item bpow
C<bpow()> (and the rounding functions) now modifies the first argument and
returns it, unlike the old code which left it alone and only returned the
result. This is to be consistent with C<badd()> etc. The first three will
modify $x, the last one won't:
print bpow($x,$i),"\n"; # modify $x
print $x->bpow($i),"\n"; # ditto
print $x **= $i,"\n"; # the same
print $x ** $i,"\n"; # leave $x alone
The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
=item Overloading -$x
The following:
$x = -$x;
is slower than
$x->bneg();
since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
needs to preserve $x since it does not know that it later will get overwritten.
This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
=item Mixing different object types
In Perl you will get a floating point value if you do one of the following:
$float = 5.0 + 2;
$float = 2 + 5.0;
$float = 5 / 2;
With overloaded math, only the first two variants will result in a BigFloat:
use Math::BigInt;
use Math::BigFloat;
$mbf = Math::BigFloat->new(5);
$mbi2 = Math::BigInteger->new(5);
$mbi = Math::BigInteger->new(2);
# what actually gets called:
$float = $mbf + $mbi; # $mbf->badd()
$float = $mbf / $mbi; # $mbf->bdiv()
$integer = $mbi + $mbf; # $mbi->badd()
$integer = $mbi2 / $mbi; # $mbi2->bdiv()
$integer = $mbi2 / $mbf; # $mbi2->bdiv()
This is because math with overloaded operators follows the first (dominating)
operand, and the operation of that is called and returns thus the result. So,
Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
the result should be a Math::BigFloat or the second operant is one.
To get a Math::BigFloat you either need to call the operation manually,
make sure the operands are already of the proper type or casted to that type
via Math::BigFloat->new():
$float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5
Beware of simple "casting" the entire expression, this would only convert
the already computed result:
$float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!
Beware also of the order of more complicated expressions like:
$integer = ($mbi2 + $mbi) / $mbf; # int / float => int
$integer = $mbi2 / Math::BigFloat->new($mbi); # ditto
If in doubt, break the expression into simpler terms, or cast all operands
to the desired resulting type.
Scalar values are a bit different, since:
$float = 2 + $mbf;
$float = $mbf + 2;
will both result in the proper type due to the way the overloaded math works.
This section also applies to other overloaded math packages, like Math::String.
One solution to you problem might be autoupgrading|upgrading. See the
pragmas L<bignum>, L<bigint> and L<bigrat> for an easy way to do this.
=item bsqrt()
C<bsqrt()> works only good if the result is a big integer, e.g. the square
root of 144 is 12, but from 12 the square root is 3, regardless of rounding
mode. The reason is that the result is always truncated to an integer.
If you want a better approximation of the square root, then use:
$x = Math::BigFloat->new(12);
Math::BigFloat->precision(0);
Math::BigFloat->round_mode('even');
print $x->copy->bsqrt(),"\n"; # 4
Math::BigFloat->precision(2);
print $x->bsqrt(),"\n"; # 3.46
print $x->bsqrt(3),"\n"; # 3.464
=item brsft()
For negative numbers in base see also L<brsft|brsft>.
=back
=head1 LICENSE
This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.
=head1 SEE ALSO
L<Math::BigFloat>, L<Math::BigRat> and L<Math::Big> as well as
L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
The pragmas L<bignum>, L<bigint> and L<bigrat> also might be of interest
because they solve the autoupgrading/downgrading issue, at least partly.
The package at
L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
more documentation including a full version history, testcases, empty
subclass files and benchmarks.
=head1 AUTHORS
Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
Completely rewritten by Tels http://bloodgate.com in late 2000, 2001 - 2006
and still at it in 2007.
Many people contributed in one or more ways to the final beast, see the file
CREDITS for an (incomplete) list. If you miss your name, please drop me a
mail. Thank you!
=cut
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/5.10/Math/BigInt.pm | Perl | bsd-3-clause | 151,391 |
#!/usr/bin/perl
# Simple script to generate a 302 HTTP redirect
print "Status: 302 Moved Temporarily\r\n";
print "Location: success200.html\r\n";
print "Content-type: text/html\r\n";
print "\r\n";
print <<HERE_DOC_END
<html><body>
This page should not be seen - it is a 302 redirect to another page.
The key aspect is that this page should not wind up in the back/forward
list, since there should only be one entry for the navigation through
this page to the eventual target.
</body></html>
HERE_DOC_END
| nwjs/chromium.src | third_party/blink/web_tests/http/tests/navigation/resources/redirect302.pl | Perl | bsd-3-clause | 506 |
package DDG::Goodie::URLDecode;
# ABSTRACT: Displays the decoded URL for a percent encoded uri
use DDG::Goodie;
use URI::Escape::XS qw(decodeURIComponent);
use warnings;
use strict;
my $trigger_words = qr#urlunescape|unescapeurl|(unescape url)|decodeurl|(decode url)|urldecode|(url decode)|(url unescape)#;
triggers query_raw => qr#%[0-9A-Fa-f]{2}#;
primary_example_queries 'url decode https%3A%2F%2Fduckduckgo.com%2F', 'decode url xkcd.com%2Fblag';
secondary_example_queries 'http%3A%2F%2Farstechnica.com%2F url unescape', 'linux.com%2Ftour%2F unescape url';
zci answer_type => 'decoded_url';
zci is_cached => 1;
name 'URLDecode';
description 'Displays the uri from a percent encoded url';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/URLDecode.pm';
category 'computing_tools';
topics 'programming', 'web_design';
attribution web => [ 'https://www.duckduckgo.com', 'DuckDuckGo' ],
github => [ 'duckduckgo', 'DuckDuckGo'],
twitter => ['duckduckgo', 'DuckDuckGo'];
handle query_raw => sub {
# unless trigger words exist, only answer when we have a single word
unless (m/$trigger_words/) {
return if m/\s+/;
}
#remove triggers and trim
s/(^$trigger_words)|($trigger_words$)//i;
s/(^\s+)|(\s+$)//;
my $in = $_;
my $decoded = decodeURIComponent($in);
if ($decoded =~ /^\s+$/) {
$decoded =~ s/\r/CReturn/;
$decoded =~ s/\n/Newline/;
$decoded =~ s/\t/Tab/;
$decoded =~ s/\s/Space/;
}
my $text = "URL Decoded: $decoded";
return $text,
structured_answer => {
input => [html_enc($in)],
operation => 'URL decode',
result => html_enc($decoded)
};
};
1;
| Faiz7412/zeroclickinfo-goodies | lib/DDG/Goodie/URLDecode.pm | Perl | apache-2.0 | 1,760 |
package ComplaintGroup::Tokenizer::Backend;
use ComplaintGroup::Tokenizer::Backend::KyotoCabinet;
use ComplaintGroup::Tokenizer::Backend::Redis;
sub new {
my $invocant = shift;
my $class = ref( $invocant ) || $invocant;
my $self = {
@_,
};
return bless $self, $class;
}
sub store ($$$) {
my ($self,$key,$value) = @_;
warn "Calling store from interface\n";
}
sub fetch ($$) {
my ($self,$key) = @_;
warn "Calling fetch from interface\n";
}
# a class method
sub create {
my $class = shift;
my $options = {
backend => 'redis',
@_,
};
use Data::Dumper;
if( $options->{backend} eq 'redis' ){
return ComplaintGroup::Tokenizer::Backend::Redis->new( %$options );
} elsif ( $options->{backend} eq 'kyotocabinet' ){
return ComplaintGroup::Tokenizer::Backend::KyotoCabinet->new( %$options );
}
return undef;
}
1;
| petermblair/libemail | complaintgroup/lib/ComplaintGroup/Tokenizer/Backend.pm | Perl | mit | 840 |
package Eldhelm::AI::NeuralNetwork::Neuron;
use strict;
use Carp qw(confess longmess);
use Data::Dumper;
use Eldhelm::AI::NeuralNetwork::TransferFunction;
my $eta = .2;
my $alpha = .5;
sub new {
my ($class, %args) = @_;
my $self = {%args};
bless $self, $class;
$self->{value} = 1 if $self->{bias} && !$self->{value};
$self->weightsFromList($args{weights}) if $args{weights};
return $self;
}
sub value {
my ($self, $val) = @_;
if (defined $val) {
$self->{value} = $val;
return;
}
return $self->{value};
}
sub weightsFromList {
my ($self, $list) = @_;
$self->{_weights} ||= [];
my $i = 0;
foreach (@$list) {
$self->{_weights}[ $i++ ]{value} = $_;
}
}
sub generateWeights {
my ($self, $ln) = @_;
$self->{_weights} ||= [];
foreach (0 .. $ln - 1) {
$self->{_weights}[$_] = { value => rand() };
}
}
sub weights {
my ($self) = @_;
return @{ $self->{_weights} };
}
sub weightValue {
my ($self, $index) = @_;
return $self->{_weights}[$index]{value};
}
sub weightDelta {
my ($self, $index) = @_;
return $self->{_weights}[$index]{delta};
}
sub updateWeight {
my ($self, $index, $delta) = @_;
my $w = $self->{_weights}[$index];
$w->{delta} = $delta;
$w->{value} += $delta;
}
sub connection {
my ($self, $index) = @_;
return $self->value * $self->weightValue($index);
}
sub transferFunction {
my ($self, $value) = @_;
return Eldhelm::AI::NeuralNetwork::TransferFunction->sigmoid($value);
}
sub transferFunctionDerivative {
my ($self, $value) = @_;
return Eldhelm::AI::NeuralNetwork::TransferFunction->sigmoidDerivative($value);
}
sub calculate {
my ($self, $layer) = @_;
my $sum = 0;
my $index = $self->{index};
foreach my $n ($layer->neurons) {
$sum += $n->connection($index);
}
$self->value($self->transferFunction($sum));
}
sub gradient {
my ($self, $target) = @_;
return $self->{gradient};
}
sub calculateOutputGradient {
my ($self, $target) = @_;
$self->{gradient} = ($target - $self->value) * $self->transferFunctionDerivative($self->value);
}
sub calculateHiddenGradient {
my ($self, $nextLayer) = @_;
$self->{gradient} = $self->sumDow($nextLayer) * $self->transferFunctionDerivative($self->value);
}
sub sumDow {
my ($self, $layer) = @_;
my $sum = 0;
my $i = 0;
foreach my $n ($layer->neurons) {
$sum += $self->weightValue($i++) * $n->gradient;
}
return $sum;
}
sub updateInputWeights {
my ($self, $prevLayer) = @_;
my $index = $self->{index};
foreach my $n ($prevLayer->neurons) {
$n->updateWeight($index, $eta * $n->value * $self->gradient + $alpha * $n->weightDelta($index));
}
}
sub serialize {
my ($self) = @_;
return {
weights => [ map $_->{value}, @{ $self->{_weights} } ],
map { +$_ => $self->{$_} } grep { $self->{$_} } qw(bias)
};
}
1;
| wastedabuser/eldhelm-platform | lib/Eldhelm/AI/NeuralNetwork/Neuron.pm | Perl | mit | 2,750 |
package O2::Template::Critic::Policy::RequireO2Tag;
use strict;
use Readonly;
use base 'O2::Template::Critic::Policy';
my %tags = (
input => 'input',
form => 'form',
a => ['link', 'popupWindow'],
html => 'header',
select => 'select',
option => 'option',
# link => 'addCssFile',
script => 'addJsFile',
);
#-----------------------------------------------------------------------------
sub new {
my ($package, %config) = @_;
my $obj = bless {}, $package;
return $obj;
}
#-----------------------------------------------------------------------------
sub getSupportedParameters {
return ();
}
#-----------------------------------------------------------------------------
sub getDefaultSeverity {
return 1;
}
#-----------------------------------------------------------------------------
sub appliesTo {
return qw( Node::HtmlTag );
}
#-----------------------------------------------------------------------------
sub violates {
my ($obj, $element, $root) = @_;
foreach my $htmlTag (keys %tags) {
if (lc($element->getValue()) =~ m{ \A < $htmlTag \s+ }xms) {
my $betterTag = '<o2 ' . (ref( $tags{$htmlTag} ) eq 'ARRAY' ? (join ' .. > or <o2 ', @{ $tags{$htmlTag} }) : $tags{$htmlTag}) . ' .. >';
my $desc = "Found <$htmlTag .. >. It may be better to use $betterTag instead";
return $obj->violation($desc, $desc, $element);
}
}
return;
}
#-----------------------------------------------------------------------------
1;
| haakonsk/O2-Framework | lib/O2/Template/Critic/Policy/RequireO2Tag.pm | Perl | mit | 1,494 |
#!/usr/bin/env perl
# Author: Christiana Evelyn Johnson
# Copyright (c) 2014 Reno Bridgewire
# license: The MIT License (MIT)
use v5.10.0;
package Koike::Part;
use warnings;
use strict;
use Math::Trig;
use Clone 'clone';
BEGIN
{
use Exporter ();
our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
# set the version for version checking
$VERSION = 0.01;
@ISA = qw(Koike);
@EXPORT = qw(); # eg: qw(&func1 &func2 &func4);
%EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
# your exported package globals go here,
# as well as any optionally exported functions
@EXPORT_OK = qw();
}
our @EXPORT_OK;
sub new {
my $class = shift;
my $self = {};
my %args = @_;
# this is the command list, which is the heart of a Part.
# think of this most as a list of coordinates, but also "how to get there."
$self->{clist} = [];
$self->{clist_position} = -1; # for use in "get_next_command()"
die "a Koike::Part needs an instances of a Koike object in koikeobj" if ! exists($args{koikeobj});
$self->{k} = $args{koikeobj};
my( $kx, $ky ) = $self->{k}->get_current_position();
# $self->{startx} = exists($args{startx}) ? $args{startx} : $kx; # our starting point.
# $self->{starty} = exists($args{starty}) ? $args{starty} : $ky;
if( exists($args{startx}) )
{
$self->{startx} = $args{startx};
$self->{starty} = $args{starty};
$self->{k}->print_debug( 2, sprintf('Koike::Part::new() got startx,starty from args -- %.03f,%.03f', $self->{startx}, $self->{starty} ) );
}
else
{
$self->{startx} = $kx; # our starting point.
$self->{starty} = $ky;
$self->{k}->print_debug( 2, sprintf('Koike::Part::new() got startx,starty from k -- %.03f,%.03f', $self->{startx}, $self->{starty} ) );
}
$self->{x} = $self->{startx}; # is also current position
$self->{y} = $self->{starty};
$self->{k}->update_position( $self->{x}, $self->{y} );
# bounding box. XXX this doesn't correctly handle arcs,
# whose extent will often pass beyond end points.
$self->{xmin} = $self->{x};
$self->{xmax} = $self->{x};
$self->{ymin} = $self->{y};
$self->{ymax} = $self->{y};
# offsets and scaling
$self->{mult} = exists($args{multsclr}) ? $args{multsclr} : 1;
$self->{mark_dot_radius} = .2; # how big around should the mark be?
bless($self,$class); # bless me! and all who are like me. bless us everyone.
return $self;
}
sub copy()
{
my $self = shift;
my $c = new Koike::Part( koikeobj => $self->{k} );
$c->set_otherargs(
startx => $self->{startx},
starty => $self->{starty},
clist => $self->{clist},
clist_position => $self->{clist_position},
x => $self->{x},
y => $self->{y},
xmin => $self->{xmin},
xmax => $self->{xmax},
ymin => $self->{ymin},
ymax => $self->{ymax},
mult => $self->{mult},
mark_dot_radius => $self->{mark_dot_radius}
);
return $c;
}
# go through the whole path of $self and reverse the direction of travel.
# the last command becomes the first, the last set of coordinates becomes
# startx,starty, and the old startx,starty becomes the current position: x,y.
sub reverse_path()
{
my $self = shift;
$self->{k}->print_debug( 2, 'reverse_path() running' );
my ( $new_startx, $new_starty ) = $self->end_coords();
my ( $new_curx , $new_cury ) = $self->start_coords();
my $new_clist = [];
my ($x,$y);
my $h;
for( my $i = $#{$self->{clist}}; $i >= 0; $i-- )
{
$h = ${$self->{clist}}[$i];
if( exists( $h->{toy} ) )
{
my ($oldtox, $oldtoy) = ( $h->{tox}, $h->{toy} );
$h->{tox} = $h->{sox};
$h->{toy} = $h->{soy};
$h->{sox} = $oldtox;
$h->{soy} = $oldtoy;
}
elsif( $h->{cmd} eq 'os' || $h->{cmd} eq 'oe' )
{
# start and end marks may need to look ahead (or 'back'...
# decrementing $i) in the list to see where they should actually be
if( $i < $#{$self->{clist}} && $i > 0 )
{
# NOTE: $prev_h is already altered but $next_h is not
my $prev_h = ${$self->{clist}}[$i+1];
my $next_h = ${$self->{clist}}[$i-1];
if( $h->{cmd} eq 'os' && exists($prev_h->{toy}) )
{
# os (martk-start) got it's coordinates from $i-1:tox,toy and gave them to $i+1:$sox,soy
# but should take them now from $i+1
if( $h->{sox} == $prev_h->{tox} && $h->{soy} == $prev_h->{toy} )
{
# if verified, execute the switch
$h->{sox} = $prev_h->{sox};
$h->{soy} = $prev_h->{soy};
}
}
elsif( $h->{cmd} eq 'oe' && exists($next_h->{toy}) )
{
# start got it's coordinates from $i+1
# but should take them now from $i-1
# if verified, execute the switch
if( $h->{sox} == $prev_h->{sox} && $h->{soy} == $prev_h->{soy} )
{
$h->{sox} = $next_h->{tox};
$h->{soy} = $next_h->{toy};
}
}
}
elsif ( $i == 0 )
{
my $prev_h = ${$self->{clist}}[1];
if( $h->{sox} == $prev_h->{sox} && $h->{soy} == $prev_h->{soy} )
{
$h->{sox} = $prev_h->{tox};
$h->{soy} = $prev_h->{toy};
}
}
elsif ( $i == $#{$self->{clist}} )
{
# this is a mark that was at the end and should now be at the start
my $next_h = ${$self->{clist}}[$i-1];
if( $h->{sox} == $next_h->{tox} && $h->{soy} == $next_h->{toy} )
{
$h->{sox} = $next_h->{sox};
$h->{soy} = $next_h->{soy};
}
}
}
# reversing the direction of travel means reversing direction of the angle too.
# The center and long vs. short arc length don't change, so this completes the arc changes.
if( exists( $h->{sweep} ) )
{
$h->{sweep} = ! $h->{sweep};
}
# hopefully it is helpful to reverse start and end marks
if( $h->{cmd} eq 'os' || $h->{cmd} eq 'oe' )
{
$h->{cmd} = ( $h->{cmd} eq 'oe' ? 'os' : 'oe' );
if ( $h->{cmd} eq 'os' ) { $h->{clr} = $self->{k}->get_color('mark_start_color'); }
elsif( $h->{cmd} eq 'oe' ) { $h->{clr} = $self->{k}->get_color('mark_end_color'); }
}
push( @{$new_clist}, $h );
}
( $self->{startx}, $self->{starty} ) = ( $new_startx, $new_starty );
$self->update_position( $new_curx, $new_cury, 0 );
$self->{clist} = $new_clist;
}
# the intended syntax of merge: '$part->merge( $otherpart )' suggests to me
# that if one or the other of these parts is 'dominant' then it would be $part
# since that's the one whose member function is being called. The mechanics of
# how this is actually done, however, due to ease of access to the clist, the
# actual implemenation likely appends $part to $otherpart, which has the 'feel'
# of $otherpart being dominant. so we export 'merge' as the implementor of this
# functionality, but in order to make merge operate more intuitively, we add
# 'reverse_merge' which is the actual implementation, and merge() simply calls
# reverse_merge after, itself, reversing the sense of the call.
sub reverse_merge()
{
# begin with cloning otherpart
# 'this' part cyles through its own command-list (the clist) and uses the otherpart's push_cmd
# method to append our commands to it's commands
my $self = shift;
my $root = shift; # 'root' is the part that self gets merged into
my $n; # 'n' will be the new part, a combination of the two merging
my ($r_xs, $r_ys, $r_xe, $r_ye) = ( $root->start_coords(), $root->end_coords() );
my ($s_xs, $s_ys, $s_xe, $s_ye) = ( $self->start_coords(), $self->end_coords() );
$self->{k}->print_debug( 2, sprintf('reverse_merge got: root(xs:%f, ys:%f, xe:%f, ye:%f) -- self(xs:%f, ys:%f, xe:%f, ye:%f) -- r_xe is%s equal to s_xe',
$r_xs, $r_ys, $r_xe, $r_ye,
$s_xs, $s_ys, $s_xe, $s_ye,
(($r_xe == $s_xe) ? "" : " not") )
);
# simplest case: if self starts where root ends, then append self to root
if( abs($s_xs - $r_xe) < .00001 && abs($s_ys - $r_ye) < .00001 )
{
$self->{k}->print_debug( 2, 'reverse_merge handling simples case' );
$n = $root->copy();
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
$n->push_cmd( ${$self->{clist} }[$i] );
}
$n->update_position( $self->{x}, $self->{y}, 0 );
$n->auto_remake_bounding_box();
}
# next simplest.
# else: if other start where self ends, then use recursion to reverse the roles
# XXX or... if we want to preserve the roles, do we reverse both paths?
#elsif( $r_xs == $s_xe && $r_ys == $s_ye )
elsif( abs($r_xs - $s_xe) < .00001 && abs($r_ys - $s_ye) < .00001 )
{
$self->{k}->print_debug( 2, 'reverse_merge handling next simples case' );
$n = $root->reverse_merge( $self );
}
# more complex
# else:
# we have already established that the start of neither is the end of the other
# so if the two parts have any endpoints in common, either the starts are the
# same or the ends are the same. first test for common starts.
#elsif( $r_xs == $s_xs && $r_ys == $s_ys )
elsif( abs($r_xs - $s_xs) < .00001 && abs($r_ys - $s_ys) < .00001 )
{
# how to deal with this? in the paradigm used by this library (a part
# is a single path with a clear start and clear end, with possible
# self-intersection), we cannot start in the middle of a path. We have
# to start at one end or the other, thus one of the two parts must be
# reversed. Since we want 'root' to provide the startx,starty to the
# merged part, we reverse root so that its last coordinate becomes its
# first, reversing commands too. this is most trick with respect to
# arcs. we'll have to reverse the sweep. do this in a seperate function,
# called 'reverse_path'
$self->{k}->print_debug( 2, 'reverse_merge doing root->reverse_path' );
$root->reverse_path();
$n = $root->merge( $self );
}
# else:
# the two parts meet at their respective ends.
# reverse the path of 'self' (as opposed to reversing root)
#elsif( $r_xe == $s_xe && $r_ye == $s_ye )
elsif( abs($r_xe - $s_xe) < .00001 && abs($r_ye - $s_ye) < .00001 )
{
$self->{k}->print_debug( 2, 'reverse_merge doing self->reverse_path' );
$self->reverse_path();
# now we have ( $r_xe = $s_xs && $r_ye = $s_ys )
($s_xs, $s_ys, $s_xe, $s_ye) = ( $self->start_coords(), $self->end_coords() );
#die "assertion failed" if ! ( $s_xs == $r_xe && $s_ys == $r_ye );
die "assertion failed" if ! (abs($s_xs - $r_xe) < .00001 && abs($s_ys - $r_ye) < .00001);
$n = $root->merge( $self );
}
# if none of the endpoints match up then we just do a 'moveto' from the
# enpoint
else
{
$self->{k}->print_debug( 2, 'reverse_merge doing the original algo.' );
$root->dump_part('root'); # dump produces output at debug level 7.
$self->dump_part('self');
$self->{k}->print_debug( 2, sprintf('adding a moveto from: root(xe:%f, ye:%f) -- self(xs:%f, ys:%f)', $r_xe, $r_ye, $s_xs, $s_ys ) );
$n = $root->copy();
$n->moveto( $self->start_coords() );
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
$n->push_cmd( ${$self->{clist} }[$i] );
}
$n->update_position( $self->{x}, $self->{y}, 0 );
$n->auto_remake_bounding_box();
}
return $n;
}
sub merge()
{
my $self = shift;
my $o = shift; # 'o' is the 'otherpart'
# to make the 'merge' syntax more intuitive (to me) internally we reverse the order...
return $o->reverse_merge( $self );
}
sub set_otherargs()
{
my $self = shift;
my %args = @_;
$self->{clist} = clone( $args{clist} );
$self->{clist_position} = $args{clist_position};
$self->{startx} = $args{startx};
$self->{starty} = $args{starty};
$self->{x} = $args{x};
$self->{y} = $args{y};
$self->{xmin} = $args{xmin};
$self->{xmax} = $args{xmax};
$self->{ymin} = $args{ymin};
$self->{ymax} = $args{ymax};
$self->{mult} = $args{mult};
$self->{mark_dot_radius} = $args{mark_dot_radius};
}
sub rewind_command_list()
{
my $self = shift;
$self->{clist_position} = -1;
}
sub next_command()
{
my $self = shift;
$self->{clist_position} += 1;
if( exists( ${$self->{clist}}[ $self->{clist_position} ]) )
{
return ${$self->{clist}}[ $self->{clist_position} ];
}
$self->{clist_position} -= 1;
return undef;
}
sub start_coords()
{
my $self = shift;
my ( $x, $y ) = ( $self->{startx}, $self->{starty} );
my $h = $self->first_command();
if( defined($h) && exists( $h->{sox} ) && ($h->{sox} != $x || $h->{soy} != $y) )
{
$self->{k}->print_debug( 2, sprintf('start_coords fouind that startx,starty:(%.03f,%.03f) != first_command(%s):sox,soy:(%.03f,%.03f). returning sox,soy;',
$x, $y, $h->{cmd}, $h->{sox}, $h->{soy}) );
( $x, $y ) = ($h->{sox}, $h->{soy});
}
return ( $x, $y );
}
sub end_coords()
{
my $self = shift;
my ( $x, $y ) = ( $self->{startx}, $self->{starty} );
my $h = $self->last_command();
if( defined($h) )
{
my $debug_coords_source = 'sox,soy';
if( exists( $h->{toy} ) )
{
( $x, $y ) = ($h->{tox}, $h->{toy});
$debug_coords_source = 'tox,toy';
}
else
{
( $x, $y ) = ($h->{sox}, $h->{soy});
}
$self->{k}->print_debug( 2, sprintf('end_coords pulled %s: %.02f,%.02f via cmd:%s', $debug_coords_source, $x, $y, $h->{cmd} ) );
}
return ( $x, $y );
}
sub first_command()
{
my $self = shift;
if( $#{$self->{clist}} > -1 ) { return ${$self->{clist}}[0]; }
return undef;
}
sub last_command()
{
my $self = shift;
if( $#{$self->{clist}} > -1 ) { return ${$self->{clist}}[$#{$self->{clist}}]; }
return undef;
}
# this is like translate() but it does an absolute shift instead of a relative shift
# $shiftfrom_x and $shiftfrom_y allow a different point in $self to represent the "handle" of $self
sub reposition()
{
my $self = shift;
my $shifto_x = shift;
my $shifto_y = shift;
my $shiftfrom_x = shift || $self->{startx};
my $shiftfrom_y = shift || $self->{starty};
#$self->{k}->print_debug( 2, sprintf('resposition doing translate() and translate()', -$shiftfrom_x, -$shiftfrom_y, $shifto_x, $shifto_y ) );
$self->translate( -$shiftfrom_x, -$shiftfrom_y );
$self->translate( $shifto_x, $shifto_y );
}
sub translate()
{
my $self = shift;
my $xshift = shift;
my $yshift = shift;
my $id = 1000000*rand();
if( ${$self->{clist}}[0]->{sox} != $self->{startx} || ${$self->{clist}}[0]->{soy} != $self->{starty} )
{
$self->{k}->print_debug( 1, sprintf('%d: start-point mismatch at start of translate: sox,soy:(%.03f,%.03f) != startx,starty:(%.03f,%.03f)', $id,
${$self->{clist}}[0]->{sox}, ${$self->{clist}}[0]->{soy}, $self->{startx}, $self->{starty} ) );
}
# shift every coordinate
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
${$self->{clist}}[$i]->{sox} += $xshift;
${$self->{clist}}[$i]->{soy} += $yshift;
if( exists( ${$self->{clist}}[$i]->{toy} ) )
{
${$self->{clist}}[$i]->{tox} += $xshift;
${$self->{clist}}[$i]->{toy} += $yshift;
}
if( ${$self->{clist}}[$i]->{cmd} eq 'a' )
{
${$self->{clist}}[$i]->{cx} += $xshift;
${$self->{clist}}[$i]->{cy} += $yshift;
}
}
# all meta-coordinates are aspects of this part too...
$self->{x} += $xshift;
$self->{y} += $yshift;
$self->{k}->update_position( $self->{x}, $self->{y} );
$self->{startx} += $xshift;
$self->{starty} += $yshift;
$self->auto_remake_bounding_box();
if( ${$self->{clist}}[0]->{sox} != $self->{startx} || ${$self->{clist}}[0]->{soy} != $self->{starty} )
{
$self->{k}->print_debug( 1, sprintf('%d: start-point mismatch at end of translate: sox,soy:(%.03f,%.03f) != startx,starty:(%.03f,%.03f)', $id,
${$self->{clist}}[0]->{sox}, ${$self->{clist}}[0]->{soy}, $self->{startx}, $self->{starty} ) );
}
}
sub scale()
{
my $self = shift;
my $scaler = shift;
$self->linear_transform( [[$scaler,0],[0,$scaler]] );
}
sub matrix_mult()
{
my $self = shift;
my $mat = shift;
my $vec = shift;
my $dbg = shift || "";
$self->{k}->print_debug( 10,
$dbg.
'$$mat[0][0] == '.(exists($$mat[0][0]) && defined($$mat[0][0])?"exists:".$$mat[0][0]:"nonesuch").
'$$vec[0] == '.(exists($$vec[0]) && defined($$vec[0])?"exists:".$$vec[0]:"nonesuch").
'$$mat[0][1] == '.(exists($$mat[0][1]) && defined($$mat[0][1])?"exists:".$$mat[0][1]:"nonesuch").
'$$vec[1] == '.(exists($$vec[1]) && defined($$vec[1])?"exists:".$$vec[1]:"nonesuch").
'$$mat[1][0] == '.(exists($$mat[1][0]) && defined($$mat[1][0])?"exists:".$$mat[1][0]:"nonesuch").
'$$vec[0] == '.(exists($$vec[0]) && defined($$vec[0])?"exists:".$$vec[0]:"nonesuch").
'$$mat[1][1] == '.(exists($$mat[1][1]) && defined($$mat[1][1])?"exists:".$$mat[1][1]:"nonesuch").
'$$vec[1] == '.(exists($$vec[1]) && defined($$vec[1])?"exists:".$$vec[1]:"nonesuch")
);
return (
$$mat[0][0] * $$vec[0] +
$$mat[0][1] * $$vec[1],
$$mat[1][0] * $$vec[0] +
$$mat[1][1] * $$vec[1] );
}
sub linear_transform()
{
my $self = shift;
my $mat = shift;
my ($x,$y);
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
( ${$self->{clist}}[$i]->{sox}, ${$self->{clist}}[$i]->{soy} ) =
$self->matrix_mult( $mat, [${$self->{clist}}[$i]->{sox}, ${$self->{clist}}[$i]->{soy}], "a - " );
if( exists( ${$self->{clist}}[$i]->{toy} ) )
{
( ${$self->{clist}}[$i]->{tox}, ${$self->{clist}}[$i]->{toy} ) =
$self->matrix_mult( $mat, [${$self->{clist}}[$i]->{tox}, ${$self->{clist}}[$i]->{toy}], "b - " );
}
if( ${$self->{clist}}[$i]->{cmd} eq 'a' )
{
(${$self->{clist}}[$i]->{cx}, ${$self->{clist}}[$i]->{cy} ) =
$self->matrix_mult( $mat, [ ${$self->{clist}}[$i]->{cx}, ${$self->{clist}}[$i]->{cy}], "c - " );
}
}
# apply transform also to the start and current positions
($self->{startx}, $self->{starty}) = $self->matrix_mult( $mat, [$self->{startx}, $self->{starty}], "d - " );
$self->update_position( $self->matrix_mult( $mat, [$self->{x}, $self->{y}], "f - " ), 0 ); # ($self->{x}, $self->{y}) =
$self->auto_remake_bounding_box();
}
sub nonlinear_transform_helper()
{
my $self = shift;
my $mat = shift;
my $vec = shift;
my $x = shift;
my $y = shift;
my $dbgl = shift;
my $xx = $$mat[0][0];
my $xy = $$mat[0][1];
my $yx = $$mat[1][0];
my $yy = $$mat[1][1];
my $vx = $$vec[0];
my $vy = $$vec[1];
my $m = [ [&$xx( $x, $y ), &$xy( $x, $y )], [&$yx( $x, $y ), &$yy( $x, $y )]];
my ($newx, $newy) = $self->matrix_mult( $m, [ $x, $y ], $dbgl );
my ($xoffset, $yoffset) = ( &$vx( $x, $y ), &$vy( $x, $y ) );
return ($newx + $xoffset, $newy + $yoffset);
}
sub make_numeric_coderef($)
{
my $ref = shift;
if( ref $ref ne "CODE" )
{
if( ref $ref eq "" )
{
if( $ref =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ )
{
return sub { return $ref; };
}
else
{
return sub { return 0; };
}
}
elsif( ref $ref eq "SCALAR" )
{
my $v = $$ref;
if( $v =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ )
{
return sub { return $v; };
}
else
{
return sub { return 0; };
}
}
else
{
return sub { return 0; };
}
}
return $ref;
}
sub nonlinear_transform()
{
my $self = shift;
my $mat = shift;
my $vec = shift;
if( ref $mat ne 'ARRAY' ) { $mat = [[sub{1;},sub{0;}],[sub{0;},sub{1;}]]; } # default transform matrix is identity
$$mat[0][0] = &make_numeric_coderef( $$mat[0][0] );
$$mat[1][0] = &make_numeric_coderef( $$mat[1][0] );
$$mat[0][1] = &make_numeric_coderef( $$mat[0][1] );
$$mat[1][1] = &make_numeric_coderef( $$mat[1][1] );
if( ref $vec ne 'ARRAY' ) { $vec = [sub{0;}, sub{0;}]; } # default offset vector is zero
$$vec[0] = &make_numeric_coderef( $$vec[0] );
$$vec[1] = &make_numeric_coderef( $$vec[1] );
my ($x,$y,$m);
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
( ${$self->{clist}}[$i]->{sox}, ${$self->{clist}}[$i]->{soy} ) =
$self->nonlinear_transform_helper( $mat, $vec, ${$self->{clist}}[$i]->{sox}, ${$self->{clist}}[$i]->{soy}, "a - " );
if( exists( ${$self->{clist}}[$i]->{toy} ) )
{
( ${$self->{clist}}[$i]->{tox}, ${$self->{clist}}[$i]->{toy} ) =
$self->nonlinear_transform_helper( $mat, $vec, ${$self->{clist}}[$i]->{tox}, ${$self->{clist}}[$i]->{toy}, "b - " );
}
# XXX this is inadequate.
if( ${$self->{clist}}[$i]->{cmd} eq 'a' )
{
( ${$self->{clist}}[$i]->{cx}, ${$self->{clist}}[$i]->{cy} ) =
$self->nonlinear_transform_helper( $mat, $vec, ${$self->{clist}}[$i]->{cx}, ${$self->{clist}}[$i]->{cy}, "c - " );
}
}
# apply transform also to the start and current positions
($self->{startx}, $self->{starty}) = $self->nonlinear_transform_helper( $mat, $vec, $self->{startx}, $self->{starty}, "d - " );
$self->update_position( $self->nonlinear_transform_helper( $mat, $vec, $self->{x}, $self->{y}, "f - " ), 0 );
$self->auto_remake_bounding_box();
}
sub rotate()
{
my $self = shift;
my $angle = shift;
my $units = shift || 'radians'; # what's the angle unit? default is radians.
$self->{k}->print_debug( 9, "rotate() received -- angle:$angle , units:$units" );
if( $units =~ /degree/ ) { $angle = deg2rad($angle); }
$self->linear_transform( [[cos($angle),-sin($angle)],[sin($angle),cos($angle)]] );
}
sub set_colors()
{
my $self = shift;
$self->{k}->set_colors( @_ );
}
sub set_marker_parameters()
{
my $self = shift;
my %args = @_;
if( exists($args{mark_start_color}) ) { $self->{k}->set_colors(mark_start_color=>$args{mark_start_color}); }
if( exists($args{mark_end_color}) ) { $self->{k}->set_colors( mark_end_color=>$args{mark_end_color}); }
$self->{mark_dot_radius} = exists($args{mark_dot_radius}) ? $args{mark_dot_radius} : $self->{mark_dot_radius};
}
sub update_bounds()
{
my $self = shift;
my $newx = shift;
my $newy = shift;
if( ! exists($self->{xmin}) || ! defined($self->{xmin}) )
{
$self->{xmin} = $self->{xmax} = $newx;
$self->{ymin} = $self->{ymax} = $newy;
}
else
{
$self->{xmin} = ( $self->{xmin} < $newx ? $self->{xmin} : $newx );
$self->{xmax} = ( $self->{xmax} > $newx ? $self->{xmax} : $newx );
$self->{ymin} = ( $self->{ymin} < $newy ? $self->{ymin} : $newy );
$self->{ymax} = ( $self->{ymax} > $newy ? $self->{ymax} : $newy );
}
}
sub get_bounding_box()
{
my $self = shift;
return ( 'xmin'=>$self->{xmin}, 'ymin'=>$self->{ymin}, 'xmax'=>$self->{xmax}, 'ymax'=>$self->{ymax} );
}
sub set_bounding_box()
{
my $self = shift;
my %args = @_;
$self->{xmin} = exists($args{xmin}) ? $args{xmin} : $self->{xmin};
$self->{xmax} = exists($args{xmax}) ? $args{xmax} : $self->{xmax};
$self->{ymin} = exists($args{ymin}) ? $args{ymin} : $self->{ymin};
$self->{ymax} = exists($args{ymax}) ? $args{ymax} : $self->{ymax};
}
sub auto_remake_bounding_box()
{
my $self = shift;
$self->{xmin} = $self->{xmax} = $self->{startx};
$self->{ymin} = $self->{ymax} = $self->{starty};
my ($x,$y);
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
$self->update_bounds( ${$self->{clist}}[$i]->{sox}, ${$self->{clist}}[$i]->{soy} );
if( exists( ${$self->{clist}}[$i]->{toy} ) )
{
$self->update_bounds( ${$self->{clist}}[$i]->{tox}, ${$self->{clist}}[$i]->{toy} );
}
}
}
sub update_position()
{
my $self = shift;
my $newx = shift;
my $newy = shift;
my $update_startxy = shift;
$update_startxy = 1 if ( ! defined( $update_startxy ) );
if( defined($self->{x}) && $self->{x} == $newx && $self->{y} == $newy )
{
# did the position change?
return 0; # no it did not. return false.
}
$self->update_bounds( $newx, $newy );
# if we haven't started yet, then update_position() changes the start position
if( $update_startxy && $#{$self->{clist}} < 0 )
{
$self->{startx} = $newx;
$self->{starty} = $newy;
}
$self->{x} = $newx;
$self->{y} = $newy;
$self->{k}->update_position( $self->{x}, $self->{y} );
return 1; # return true
}
sub get_current_position()
{
my $self = shift;
return ( $self->{x}, $self->{y} );
}
sub moveto()
{
my $self = shift;
my $newx = shift;
my $newy = shift;
my $sox = $self->{x};
my $soy = $self->{y};
if( $self->update_position( $newx, $newy, 0 ) )
{
$self->push_cmd( {
cmd=>'m', clr=>$self->{k}->get_color('moveto_color'),
sox=>$sox, soy=>$soy,
tox=>$newx, toy=>$newy } );
}
}
sub do_mark()
{
my $self = shift;
my $cmd = shift;
my $clr = shift;
$self->push_cmd( { cmd=>$cmd, clr=>$clr, sox => $self->{x}, soy => $self->{y}, r => $self->{mark_dot_radius} } );
}
sub mark_start() { my $self = shift; my $clr = shift || $self->{k}->get_color('mark_start_color'); $self->do_mark('os',$clr); }
sub mark_end() { my $self = shift; my $clr = shift || $self->{k}->get_color('mark_end_color'); $self->do_mark('oe',$clr); }
sub lineto()
{
my $self = shift;
my $newx = shift;
my $newy = shift;
my $sox = $self->{x};
my $soy = $self->{y};
if( $self->update_position( $newx, $newy, 0 ) )
{
$self->push_cmd( {
cmd=>'l', clr=>$self->{k}->get_color('cut_color'),
sox=>$sox, soy=>$soy,
tox=>$newx, toy=>$newy } );
}
}
# svg can do ellipses, but gcode cannot. for now, allow only circular arcs.
sub arcto()
{
my $self = shift;
my %args = @_;
my $tox = $args{newx};
my $toy = $args{newy};
my $rdus = undef;
if( exists($args{radius}) ) { $rdus = $args{radius}; }
my $sweep = undef;
if( exists($args{sweep}) ) { $sweep = $args{sweep}; } # ifdef sweep, ignore clockwise
my $largearc = undef;
if( exists($args{largearc}) ) { $largearc = $args{largearc}; }
my $cx = undef;
my $cy = undef;
my $radius_tolerance = .00000001; # arbitrary tiny number. this maybe needs to come from the machine spec.
my $sox = $self->{x};
my $soy = $self->{y};
if( exists($args{cx}) && exists($args{cy}) && ( defined($largearc) || defined($sweep) ) )
{
# combined with the starting point, ending point, and sweep,
# we can calculate the radius and largearc-flag
$cx = $args{cx};
$cy = $args{cy};
# to find the largearc-flag, do a cross-product.
# here's the algo.:
# u = s - c # u is the vector from the center to start (sox, soy, 0)
# v = t - c # v is the vector from the center to end (tox, toy, 0)
# let (u x v)k be the third (the kth) coodinate of (u x v)
#
# if( (u x v)k > 0 && $sweep ) largearc-flag = 0;
# if( (u x v)k > 0 && ! $sweep ) largearc-flag = 1;
# if( (u x v)k < 0 && $sweep ) largearc-flag = 1;
# if( (u x v)k < 0 && ! $sweep ) largearc-flag = 0;
my $ux = $sox - $cx;
my $uy = $soy - $cy;
my $vx = $tox - $cx;
my $vy = $toy - $cy;
my $cross = $ux*$vy - $uy*$vx;
if( defined($sweep) && ! defined($largearc) )
{
if( $cross < 0 ){ $largearc = $sweep; }
elsif( $cross > 0 ){ $largearc = ! $sweep; }
else { $largearc = 1; }
}
elsif( ! defined($sweep) && defined($largearc) )
{
if( $cross < 0 ){ $sweep = $largearc; }
elsif( $cross > 0 ){ $sweep = ! $largearc; }
else { die "sweep is ambiguous with 180-degree arc. sweep must be defined"; }
}
else
{
# verify that the everything is in agreement
if( $cross < 0 && $sweep != $largearc ){ die "sweep disagrees with largearc given start,stop,center"; }
if( $cross > 0 && $sweep == $largearc ){ die "sweep disagrees with largearc given start,stop,center"; }
}
# assert( at this point, largearc and sweep are defined and agree )
my $r1 = sqrt( $ux**2 + $uy**2 );
my $r2 = sqrt( $vx**2 + $vy**2 );
$self->{k}->print_debug( 5, sprintf('sox,soy == %.02f,%.02f; tox,toy == %.02f,%.02f; cx,cy == %.02f,%.02f; '.
'ux,uy == %.02f,%.02f; vx,vy == %.02f,%.02f; cross = %.02f; r1,r1 == %.02f,%.02f;',
$sox, $soy, $tox, $toy, $cx, $cy, $ux, $uy, $vx, $vy, $cross, $r1, $r2 ) );
if( abs($r1 - $r2) > $radius_tolerance )
{
die "the calculated radii for a circular arc must be reasonably equal. r1:$r1 != r2:$r2 diff: ".abs($r1 - $r2);
}
if( defined($rdus) )
{
if( abs( $rdus - $r2 ) > $radius_tolerance )
{
die "the specified radius differs from the calculated radii by too much. ".
"given:$rdus != calc'd:$r2. diff: ".abs( $rdus - $r2 );
}
# rdus is within tolerance. leave it alone.
}
else
{
$rdus = ($r1 == $r2 ? $r1 : .5*($r1 + $r2));
}
}
# if the center point is not defined then we need a radius, sweep, *and* largearc flag to find the center.
# However, g-code interpreters seem to allow for a radius and sweep defined without also specifying which
# arc to use. I will allow this, and assume, as interpreters seem to as a convention, to use largearc=0
# when it's not specified.
# elsif( defined($rdus) && defined($sweep) && defined($largearc) )
elsif( defined($rdus) && defined($sweep) )
{
if( ! defined($largearc) ) { $largearc = 0; }
# make a vector named U
my $ux = $tox - $sox;
my $uy = $toy - $soy;
my $u_norm = sqrt( $ux**2 + $uy**2 ); # this is: ||U|| in description below
if( $rdus < .5*$u_norm && abs($rdus - .5*$u_norm) > $radius_tolerance )
{
die "radius ($rdus) between specified points (s: $sox,$soy) -> (t: $tox,$toy) is too short (||t-s||:$u_norm)";
}
elsif( abs($rdus - .5*$u_norm) > $radius_tolerance )
{
# the radius is long enough that the center of the circle is not on the line
# between the two points (we're rotating trough a non-180 degree angle.)
################################## SVG
# First, we're dealing with a left-hand coord. system. This means the
# cross product, at least for vectors in the x,y plane, has this
# definition: U x V == i.0 + j.0 + k.(v1*u2 - v2*u1). Thus if
# U=(u1,u2) then defining V=(u2,-u1) and taking the above cross product
# produces a vector in the (left-handed) positive z direction.
#
# so, let...
# T=(tox,toy)
# S=(sox,soy)
# U=T-S = (u1,u2)
# * note: U is a cord between S and T on the circle we're trying to define with center C and radius rdus
# * let V be a vector between the midpoint of U and the center of the circle C. notice that U and V are
# * at right angles from each other and that: rdus**2 = (1/2 * ||U||)^2 + ||V||^2
# * therefore: ||V|| == sqrt( rdus**2 - (.5 * ||U||)^2 ). This allows us to define V in terms of U and rdus
# V= ((u2,-u1)/||U||) * sqrt( rdus^2 - (1/4)*||U||^2)
# remember, by this definition of V, that since this is a left-hand system that UxV is positive.
# It follows that the center, C, of the circle is located either at:
# S + (1/2)*U + V ... or:
# S + (1/2)*U - V
#
# The sign given to V in the above sum is given by $sweep and $largearc
# and can be denoted thus:
# C == S + (1/2)*U + ( $sweep == $largearc ? -1 : 1 )*V
################################## GCODE
# For the Koike, we have an ordinary right handed coordinate
# system. the math is almost entirely the same but, for one, the
# cross product and V must be defined differently. The cross
# product is defined differently (normally) because "counter
# clockwise" is the usual positive angle direction, so 'sweep'...
# may have a different meaning.
# make U; made above
#my $ux = $tox - $sox;
#my $uy = $toy - $soy;
# make V
# my $u_norm = sqrt( $ux**2 + $uy**2 ); # this is: ||U||
# my $vscaler = sqrt( ($rdus**2) - .25 *($u_norm**2) ) / $u_norm;
my $vscaler = sqrt( ($rdus**2)/($ux**2 + $uy**2) - .25 ); # algebraicly equivalent
my $vx = $uy * $vscaler ;
my $vy = -$ux * $vscaler ;
# if gcode is in use we're using the ordinary right-handed coordinate system. adjust.
if( $self->{k}->get_protocol() eq 'gcode' )
{
$vx = -$uy * $vscaler ;
$vy = $ux * $vscaler ;
}
# make C (the center vector)
($cx, $cy) = ( $sox + $ux/2.0, $soy + $uy/2.0 ) ;
if( $sweep == $largearc )
{
$cx -= $vx;
$cy -= $vy;
}
else
{
$cx += $vx;
$cy += $vy;
}
}
else
{
# This yields the point half way between T and S. see explanation above.
($cx, $cy) = ( $sox + $ux/2.0, $soy + $uy/2.0 ) ;
}
}
else
{
die "(the arc center and (largearc or sweep) must be defined) or\n(the radius sweep and largearc must all be defined)\n";
}
# for complete circles the next position will equal the start, so add command
# even if the current position didn't change.
$self->push_cmd( {
cmd=>'a', clr=>(exists($args{clr}) ? $args{clr} : $self->{k}->get_color('cut_color') ),
sox=>$sox, soy=>$soy,
tox=>$tox, toy=>$toy,
sweep=>$sweep, largearc=>$largearc,
cx=>$cx, cy=>$cy,
radius=>$rdus } );
$self->{k}->print_debug( 5,
sprintf( 'arc debug -- sox=>%.03f, soy=>%.03f, tox=>%.03f, toy=>%.03f, sweep=>%d, largearc=>%d, cx=>%.03f, cy=>%.03f, radius=>%.03f',
$sox, $soy,
$tox, $toy,
$sweep, $largearc,
$cx, $cy,
$rdus * $self->{mult} ));
$self->update_position( $tox, $toy, 0 );
}
sub push_cmd
{
my $self = shift;
my $args = shift;
my $href = {};
if( exists($args->{sox}) ){ $href->{sox} = $args->{sox}; }
if( exists($args->{soy}) ){ $href->{soy} = $args->{soy}; }
if( exists($args->{tox}) ){ $href->{tox} = $args->{tox}; }
if( exists($args->{toy}) ){ $href->{toy} = $args->{toy}; }
if( exists($args->{r}) ){ $href->{r} = $args->{r}; }
if( exists($args->{cmd}) ){ $href->{cmd} = $args->{cmd}; }
if( exists($args->{clr}) ){ $href->{clr} = $args->{clr}; }
if( exists($args->{sweep}) ){ $href->{sweep} = $args->{sweep}; }
if( exists($args->{largearc}) ){ $href->{largearc} = $args->{largearc}; }
if( exists($args->{cx}) ){ $href->{cx} = $args->{cx}; }
if( exists($args->{cy}) ){ $href->{cy} = $args->{cy}; }
if( exists($args->{radius}) ){ $href->{radius} = $args->{radius}; }
push(@{$self->{clist}}, $href) if( keys %{$href} >= 1 ) ;
}
sub dump_part()
{
my $self = shift;
my $lbl = shift;
if( $self->{k}->debug_level_sufficient( 7 ) )
{
for( my $i = 0; $i <= $#{$self->{clist}}; $i++ )
{
my $dbgs = '';
my $cmd = ${$self->{clist}}[$i];
foreach my $c ( 'cmd', 'sox', 'soy', 'tox', 'toy', 'r', 'sweep', 'largearc', 'cx', 'cy', 'radius', 'clr')
{
if( exists( ${$cmd}{$c} ) )
{
$dbgs .= "$c: ".$self->mnum(${$cmd}{$c}, 3)."; ";
}
}
$self->{k}->print_debug( 7, "$lbl: $dbgs" );
}
}
}
# massage_numeric
sub mnum()
{
my $self = shift;
my $arg = shift;
my $precision = shift;
if( $arg =~ /^[-+.0-9e]+$/ )
{
if( abs($arg) != int(abs($arg)) ) # integers are clean as they are
{
my $fmt = '%f';
if( defined($precision) )
{
$fmt = '%.0'.$precision.'f';
}
$arg = sprintf( $fmt, $arg );
}
$arg =~ s/^-([0.]+)$/$1/; # we don't like negative zero
}
return $arg;
}
# /* vim: set ai et tabstop=4 shiftwidth=4: */
1;
| bridgewire/SillyGCodeProjects | perl/Koike/Part.pm | Perl | mit | 39,100 |
# back compatibility package for any code explicitly checking
# that the filehandle object is a Fh
package Fh;
$Fh::VERSION = '4.26';
1;
| jkb78/extrajnm | local/lib/perl5/Fh.pm | Perl | mit | 139 |
#!/usr/bin/env perl
#
# use fc-list to list all fonts and shows sorted font name
#
use strict;
my %hh = {};
my $ret = qx('fc-list');
my $cnt = 0;
while ( $ret =~ m/([^\n]+)\n/g ) {
my $line = $1;
#print $line,"\t";
if ($line =~ m/:\s*([^:]+)\s*:/ ) {
#print $1,"\n";
$hh{$1} ++;
}
$cnt ++;
}
foreach my $kk (sort(keys(%hh))) {
print $kk, "\n";
}
| ericosur/myqt | qml/list_fontname.pl | Perl | mit | 389 |
# -*- perl -*-
# !!! DO NOT EDIT !!!
# This file was automatically generated.
package Net::Amazon::Validate::ItemSearch::us::MusicLabel;
use 5.006;
use strict;
use warnings;
sub new {
my ($class , %options) = @_;
my $self = {
'_default' => 'Music',
%options,
};
push @{$self->{_options}}, 'Classical';
push @{$self->{_options}}, 'Merchants';
push @{$self->{_options}}, 'Music';
push @{$self->{_options}}, 'SilverMerchants';
bless $self, $class;
}
sub user_or_default {
my ($self, $user) = @_;
if (defined $user && length($user) > 0) {
return $self->find_match($user);
}
return $self->default();
}
sub default {
my ($self) = @_;
return $self->{_default};
}
sub find_match {
my ($self, $value) = @_;
for (@{$self->{_options}}) {
return $_ if lc($_) eq lc($value);
}
die "$value is not a valid value for us::MusicLabel!\n";
}
1;
__END__
=head1 NAME
Net::Amazon::Validate::ItemSearch::us::MusicLabel;
=head1 DESCRIPTION
The default value is Music, unless mode is specified.
The list of available values are:
Classical
Merchants
Music
SilverMerchants
=cut
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/Net/Amazon/Validate/ItemSearch/us/MusicLabel.pm | Perl | mit | 1,192 |
#!/usr/bin/perl -w
# get some sequences from a fasta file
use strict;
my $inf=shift || die "file of sequences we need?";
open(IN, $inf) || die "Can't open $inf";
my %need;
while (<IN>) {chomp; $need{$_}=1}
close IN;
my $fa=shift || die "fasta file?";
open(IN, $fa) || die "Can't iope $fa";
my $print;
while (<IN>) {
if (/^>(\S+)/) {
my $t=$1;
if ($need{$t}) {$print = 1}
else {undef $print}
}
print if ($print);
}
| linsalrob/bioinformatics | bin/getseqs.pl | Perl | mit | 429 |
#!/usr/bin/env perl
=head1 NAME
sample from fasta
=head1 DESCRIPTION
This script takes a fasta file and a number of sequences (n) to sample. It writes n
randomly selected sequences to the output file.
This script can also clean the fasta file: Linebreaks in the sequence as well as empty
lines and leading whitespaces in headers (> id) are removed by default. Additionally,
non ACGT charachters can be converted to N and lowercase sequence characters can be
converted to uppercase.
=head1 SYNOPSIS
./sample_from_fasta.pl [--convert-to-N --uppercase --debug --outfile <outfile.fa>] --in <input.fa> --number-of-seqs|-n <Number of Sequences to sample>
=head1 OPTIONS
=over
=back
=head2 required
=over
=item --in
Fasta file to be sampled from
=item --number-of-seqs | -n
Number of sequences, that should be written to <outfile.fa>
=back
=head2 optional
=over
=item --outfile
Name of the output file. Default: input.fa.sampled-n
(Where n is the number specified)
=item --convert-to-N
convert non ACGT charachters to N
=item --uppercase
convert lowercase acgt to uppercase ACGT
=item --debug
Verbose debug messages.
=item -V|--version
Display version.
=item -h|--help
Display this help.
=item --man
Display man page
=back
=head1 CHANGELOG
see git log.
=head1 TODO
=head1 CODE
=cut
#-----------------------------------------------------------------------------#
# Modules
# core
use strict;
use warnings;
no warnings 'qw';
use Getopt::Long qw(:config no_ignore_case bundling);
use Pod::Usage;
use Log::Log4perl qw(:no_extra_logdie_message);
use Log::Log4perl::Level;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
#-----------------------------------------------------------------------------#
# Globals
our $VERSION = 0.01;
# get a logger
my $L = Log::Log4perl::get_logger();
Log::Log4perl->init( \q(
log4perl.rootLogger = INFO, Screen
log4perl.appender.Screen = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.stderr = 1
log4perl.appender.Screen.layout = PatternLayout
log4perl.appender.Screen.layout.ConversionPattern = [%d{yy-MM-dd HH:mm:ss}] [%C] %m%n
));
#-----------------------------------------------------------------------------#
# GetOptions
my%opt;
GetOptions( # use %opt (Cfg) as defaults
\%opt, qw(
uppercase
convert-to-N
in|i=s
outfile|o=s
number-of-seqs|n=s
version|V!
debug|D!
help|h!
man!
)
) or $L->logcroak('Failed to "GetOptions"');
# help
$opt{help} && pod2usage(-verbose=>1);
$opt{man} && pod2usage(-verbose=>2);
# version
if($opt{version}){
print "$VERSION\n";
exit 0;
}
$L->level($DEBUG) if $opt{debug};
$L->debug('Verbose level set to DEBUG');
$L->debug(Dumper(\%opt));
# required stuff
for(qw(in number-of-seqs)){
pod2usage("required: --$_") unless defined ($opt{$_})
};
#set output file
unless(exists $opt{outfile})
{
$opt{"outfile"}=$opt{"in"}.".sampled-".$opt{"number-of-seqs"};
}
#-----------------------------------------------------------------------------#
# MAIN
$L->info('reading input from ',$opt{in});
open(IN,'<',$opt{in}) or $L->logdie($!);
$/="\n>";
my%fasta;
while(<IN>)
{
my@obj=split(/\n/,$_);
#get header and remove > and leading whitespace
my$id=shift(@obj);
$id=~s/^>//g;
$id=~s/^\s+//g;
my$seq=join("",@obj);
$seq=~s/>//g;
$seq=uc($seq) if $opt{'uppercase'};
$seq=~s/[^ACGTacgt]/N/g if $opt{'convert-to-N'};
$L->warn("found duplicate for $id.\nYou might want to deduplicate your fasta file first.") if exists $fasta{$id};
$fasta{$id}=$seq;
}
close IN or $L->logdie($!);
$L->info("finished reading");
$L->info("starting sampling ",$opt{"number-of-seqs"}," sequences");
$L->info("writing output to ",$opt{outfile});
open(OUT,'>',$opt{outfile}) or $L->logdie($!);
my$count=0;
my@IDs=keys(%fasta);
my$numSeqs=@IDs+0;
while($count < $opt{"number-of-seqs"})
{
my$index=int(rand($numSeqs)); #get random index
$L->debug("index: ",$index);
my$id=$IDs[$index];
print OUT ">",$id,"\n",$fasta{$id},"\n"; #print sequence
#remove index from pool
splice(@IDs, $index, 1);
$numSeqs--;
$count++;
}
close OUT or $L->logdie($!);
$L->info("done");
#-----------------------------------------------------------------------------#
=head1 AUTHOR
Niklas Terhoeven S<niklas.terhoeven@uni-wuerzburg.de>
=cut
| nterhoeven/sequence_processing | sample_from_fasta.pl | Perl | mit | 4,603 |
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 2008-2015, University of 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(http_hook,
[]).
/** <module> HTTP library hooks
Get the declarations of the HTTP package using
==
:- use_module(library(http/http_hook)).
==
@tbd This should be using include, but then it cannot be a module
and this would cause more overhead in SWI-Prolog
@tbd Complete this and document the hooks.
*/
/*******************************
* HTTP-PATH *
*******************************/
:- multifile http:location/3.
:- dynamic http:location/3.
/*******************************
* HTML-WRITE *
*******************************/
:- multifile
html_write:expand//1,
html_write:expand_attribute_value//1,
html_write:html_head_expansion/2,
html_write:layout/3.
/*******************************
* HTTP-DISPATCH *
*******************************/
:- multifile
http:authenticate/3.
/*******************************
* HTTP-PARAMETERS *
*******************************/
%! http:convert_parameter(+Type, +ValueIn, -ValueOut) is semidet.
%
% Hook to execute a step in the HTTP parameter conversion process.
%
% @see http_parameters:check_type/4.
:- multifile
http:convert_parameter/3.
/*******************************
* PROXIES *
*******************************/
%! http:http_connection_over_proxy(+Proxy, +URLParts, +Endpoint,
%! -StreamPair, +Options, -NewOptions).
%
% Try to connect to the host Endpoint via Proxy for the purposes
% of retrieving the resource identified by URLParts. Different
% options can be returned in NewOptions, which may be required if
% you have defined a non-standard proxy method in
% socket:proxy_for_url/3 (such as one requiring authentication)
:- multifile
http:http_connection_over_proxy/6.
| TeamSPoon/logicmoo_workspace | docker/rootfs/usr/local/lib/swipl/library/http/http_hook.pl | Perl | mit | 3,673 |
package Hadouken::AsyncSocket;
use strict;
use warnings;
use utf8;
use Errno;
use AnyEvent;
use AnyEvent::HTTP;
use AnyEvent::HTTP::Request;
use AnyEvent::HTTP::Response;
use AnyEvent::Util;
use AnyEvent::Socket;
use AnyEvent::Handle;
use HTTP::Request::Common ();
use HTTP::Request;
use HTTP::Response;
use HTTP::Cookies;
use Time::HiRes qw(time);
use LWP::UserAgent;
use Log::Log4perl qw( get_logger );
use Encode;
use Moose;
use Moose::Util::TypeConstraints;
use namespace::autoclean;
use Data::UUID;
no strict "subs";
no strict "refs";
use feature qw( switch say );
#if($] ge '5.018') {
# use experimental qw(lexical_subs smartmatch);
#} else {
# warn "lexical_subs and smartwatch disabled";
#}
our $VERSION = '0.03';
subtype 'Hadouken::AsyncSocket::Cookies' => as class_type('HTTP::Cookies');
coerce 'Hadouken::AsyncSocket::Cookies' => from 'HashRef' =>
via { HTTP::Cookies->new( %{$_} ) };
has timeout => ( is => 'rw', isa => 'Int', default => sub { 30 } );
has agent => (
is => 'rw',
isa => 'Str',
default => sub { 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)' }
);
has cookies => (
is => 'rw',
isa => 'Hadouken::AsyncSocket::Cookies',
coerce => 1,
default => sub { HTTP::Cookies->new }
);
has proxypac => ( is => 'rw', isa => 'Str', required => 0 );
has proxyhost => ( is => 'rw', isa => 'Str', required => 0 );
has proxyport => ( is => 'rw', isa => subtype( 'Int' => where { $_ > 0 } ), required => 0 );
has proxytype => ( is => 'rw', isa => enum( [qw(none https socks pac)] ), default => 'none' );
has useragent => (
is => 'rw',
isa => 'Str',
required => 0,
default => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0'
);
sub BUILD {
my $self = shift;
my $args = shift;
$self->{debug} = $args->{debug} || 0;
$self->{slave} = $args->{slave} || undef;
$self->{hexdump} = $args->{hexdump} || 0;
$self->{sock} = undef;
$self->{socket} = undef;
# Global handlers to be propagated to all sub-classes.
#$self->{handlers} => {};
$self->{cv} = AnyEvent->condvar( cb => sub { warn "done"; } );
$self->{cbresult} = undef;
my $uuid = Data::UUID->new;
$self->{id} = $uuid->create_str();
undef $uuid;
$self->debug( "Hadouken::AsyncSocket initialized. UUID: " . $self->{id} );
} ## ---------- end sub BUILD
sub get { _request( GET => @_ ) }
sub head { _request( HEAD => @_ ) }
sub post { _request( POST => @_ ) }
sub put { _request( PUT => @_ ) }
sub delete { _request( DELETE => @_ ) }
sub _request {
my $cb = pop;
my $method = shift;
my $self = shift;
no strict 'refs';
my $req = &{"HTTP::Request::Common::$method"}(@_);
$self->request( $req, $cb );
} ## ---------- end sub _request
sub request {
my ( $self, $request, $cb ) = @_;
$self->debug("SENDING REQUEST");
$self->debug( "A" x 50 );
$request->headers->user_agent( $self->agent );
$self->cookies->add_cookie_header($request);
my %options = (
timeout => $self->timeout,
headers => $request->headers,
body => $request->content,
keepalive => 1,
ssl_opts => { verify_hostname => 0 },
session => $self->{id}, #re-use connection for this exact instance.
);
AnyEvent::HTTP::http_request $request->method, $request->uri, %options, sub {
#my $a_res = AnyEvent::HTTP::Response->new(@_);
#$self->hexdump(" Response", $a_res->header);
#my $http_res = $a_res->to_http_message;
#$self->debug("Status", $http_res->status_line);
my ( $body, $header ) = @_;
if ( defined $header->{'set-cookie'} ) {
my @cookies;
my $set_cookie = $header->{'set-cookie'};
my @tmp = split( /,/, $set_cookie );
while (@tmp) {
my $t1 = shift @tmp;
my $t2 = shift @tmp;
push @cookies, "$t1,$t2"; # if defined $t1 && defined $t2;
}
$header->{'set-cookie'} = \@cookies;
}
my $res = HTTP::Response->new( $header->{Status}, $header->{Reason} );
$res->request($request);
$res->header(%$header);
$self->cookies->extract_cookies($res);
$cb->( $body, $header );
};
} ## ---------- end sub request
# $request is an HTTP::Request
sub request2 {
my ( $self, $request, $cb ) = @_;
$self->debug("SENDING REQUEST");
$self->debug( "A" x 50 );
my %params;
$params{session} = $self->{id};
$request->header( 'user-agent' => $self->useragent );
my $req = AnyEvent::HTTP::Request->new(
$request,
{
cb => sub { my ( $body, $header ) = @_; $cb->( $body, $header ); },
params => \%params,
}
);
$req->send();
} ## ---------- end sub request2
sub processPacket {
my ( $self, $resp ) = @_;
my $body = $resp->content;
#use Data::Dumper;
#print Dumper $resp;
$self->debug( "SUCCESS " . $resp->is_success );
$self->debug( "BODY IS " . length( ${ $resp->content_ref } ) . "BYTES!" );
$self->debug( ${ $resp->content_ref } );
#$self->{cv}->end();
return 0;
} ## ---------- end sub processPacket
sub addHandler {
my ( $self, %handlers ) = @_;
foreach my $key ( keys %handlers ) {
if ( ref( $handlers{$key} ) ne "CODE" ) {
warn "Handlers must be CODE references.";
}
$self->{handlers}->{ lc($key) } = $handlers{$key};
$self->debug("Global handler '$key' registered.");
}
} ## ---------- end sub addHandler
sub addHandlers {
return shift->addHandler(@_);
}
sub event {
my ( $self, $name, @args ) = @_;
$name = lc($name);
if ( exists $self->{handlers}->{$name} ) {
return $self->{handlers}->{$name}->( $self, @args );
}
elsif ( defined $self->{slave} ) {
return $self->{slave}->event( $name, $self, @args );
}
return;
} ## ---------- end sub event
sub hexdump {
my $self = shift;
return unless $self->{hexdump};
my ( $label, $data );
if ( scalar(@_) == 2 ) {
$label = shift;
}
$data = shift;
say "$label:" if ($label);
# Show 16 columns in a row.
my @bytes = split( //, $data );
my $col = 0;
my $buffer = '';
for ( my $i = 0; $i < scalar(@bytes); $i++ ) {
my $char = sprintf( "%02x", unpack( "C", $bytes[$i] ) );
my $escaped = unpack( "C", $bytes[$i] );
if ( $escaped < 20 || $escaped > 126 ) {
$escaped = ".";
}
else {
$escaped = chr($escaped);
}
$buffer .= $escaped;
print "$char ";
$col++;
if ( $col == 8 ) {
print " ";
}
if ( $col == 16 ) {
$buffer .= " " until length $buffer == 16;
print " |$buffer|\n";
$buffer = "";
$col = 0;
}
}
while ( $col < 16 ) {
print " ";
$col++;
if ( $col == 8 ) {
print " ";
}
if ( $col == 16 ) {
$buffer .= " " until length $buffer == 16;
print " |$buffer|\n";
$buffer = "";
}
}
if ( length $buffer ) {
print "|$buffer|\n";
}
} ## ---------- end sub hexdump
sub debug {
my ( $self, $line ) = @_;
if ( !$self->{debug} ) {
return;
}
say STDERR "$line";
} ## ---------- end sub debug
sub DESTROY {
my $self = shift;
$self->debug("DESTROY() enter.");
$self->{handlers} = undef;
$self->{id} = undef;
$self->{cv} = undef;
}
no Moose;
#__PACKAGE__->meta->make_immutable;
1;
| gitdek/hadouken | lib/Hadouken/AsyncSocket.pm | Perl | mit | 7,790 |
package Redismq::StrictSequenceTRQueue;
use strict;
use warnings;
use Moo;
use Redismq::RedisScript::PopSS;
extends 'Redismq::TimedRetryQueue';
has '+pop_s'
=> (
is => 'lazy',
default => sub { Redismq::RedisScript::PopSS->new(
redis => $_[0]->redis
);
},
);
1;
=head1 NAME
Redismq::StrictSequenceTRQueue - message queue forcing a strict sequence of messages with time out and retry capabilities
=head1 DESCRIPTION
message queue system based on redis, with time out and retry capabilities and strict sequence message delivery
=head1 AUTHOR
pedro.frazao
=cut
| pedrofrazao/smq | Redismq/StrictSequenceTRQueue.pm | Perl | mit | 615 |
# 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::Services::CustomerAssetService::GetCustomerAssetRequest;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Services/CustomerAssetService/GetCustomerAssetRequest.pm | Perl | apache-2.0 | 1,059 |
package SDBM_File;
use strict;
use vars qw($VERSION @ISA);
require Tie::Hash;
require DynaLoader;
@ISA = qw(Tie::Hash DynaLoader);
$VERSION = "1.00" ;
bootstrap SDBM_File $VERSION;
1;
__END__
=head1 NAME
SDBM_File - Tied access to sdbm files
=head1 SYNOPSIS
use SDBM_File;
tie(%h, 'SDBM_File', 'Op.dbmx', O_RDWR|O_CREAT, 0640);
untie %h;
=head1 DESCRIPTION
See L<perlfunc/tie>
=cut
| wolispace/cow_windows_server | oldcow_on_apache/perl/lib/SDBM_File.pm | Perl | apache-2.0 | 401 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package storage::emc::isilon::snmp::mode::clusterusage;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'status: ' . $self->{result_values}->{status};
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'};
return 0;
}
sub custom_usage_perfdata {
my ($self, %options) = @_;
my $label = 'ifs_used';
my $value_perf = $self->{result_values}->{used};
if (defined($self->{instance_mode}->{option_results}->{free})) {
$label = 'ifs_free';
$value_perf = $self->{result_values}->{free};
}
my %total_options = ();
if ($self->{instance_mode}->{option_results}->{units} eq '%') {
$total_options{total} = $self->{result_values}->{total};
$total_options{cast_int} = 1;
}
$self->{output}->perfdata_add(label => $label, unit => 'B',
value => $value_perf,
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{label}, %total_options),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{label}, %total_options),
min => 0, max => $self->{result_values}->{total});
}
sub custom_usage_threshold {
my ($self, %options) = @_;
my ($exit, $threshold_value);
$threshold_value = $self->{result_values}->{used};
$threshold_value = $self->{result_values}->{free} if (defined($self->{instance_mode}->{option_results}->{free}));
if ($self->{instance_mode}->{option_results}->{units} eq '%') {
$threshold_value = $self->{result_values}->{prct_used};
$threshold_value = $self->{result_values}->{prct_free} if (defined($self->{instance_mode}->{option_results}->{free}));
}
$exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'critical-' . $self->{label}, exit_litteral => 'critical' }, { label => 'warning-'. $self->{label}, exit_litteral => 'warning' } ]);
return $exit;
}
sub custom_usage_output {
my ($self, %options) = @_;
my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total});
my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used});
my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free});
my $msg = sprintf("IFS Usage Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)",
$total_size_value . " " . $total_size_unit,
$total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used},
$total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free});
return $msg;
}
sub custom_usage_calc {
my ($self, %options) = @_;
$self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_total'};
$self->{result_values}->{used} = $options{new_datas}->{$self->{instance} . '_used'};
$self->{result_values}->{free} = $self->{result_values}->{total} - $self->{result_values}->{used};
$self->{result_values}->{prct_used} = $self->{result_values}->{used} * 100 / $self->{result_values}->{total};
$self->{result_values}->{prct_free} = 100 - $self->{result_values}->{prct_used};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'cluster', type => 0, cb_prefix_output => 'prefix_cluster_output', message_separator => ' - ' },
];
$self->{maps_counters}->{cluster} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'status' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
{ label => 'health', set => {
key_values => [ { name => 'health' } ],
output_template => 'Node health: %.2f%%',
perfdatas => [
{ label => 'health', value => 'health', template => '%.2f',
min => 0, max => 100, unit => '%' },
],
}
},
{ label => 'ifs-usage', set => {
key_values => [ { name => 'used' }, { name => 'total' } ],
closure_custom_calc => $self->can('custom_usage_calc'),
closure_custom_output => $self->can('custom_usage_output'),
closure_custom_perfdata => $self->can('custom_usage_perfdata'),
closure_custom_threshold_check => $self->can('custom_usage_threshold'),
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'warning-status:s' => { name => 'warning_status', default => '%{status} =~ /attn/' },
'critical-status:s' => { name => 'critical_status', default => '%{status} =~ /down|invalid/' },
'units:s' => { name => 'units', default => '%' },
'free' => { name => 'free' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
sub prefix_cluster_output {
my ($self, %options) = @_;
return "Cluster ";
}
my %mapping_health = (
0 => 'ok',
1 => 'attn',
2 => 'down',
3 => 'invalid',
);
my $mapping = {
clusterHealth => { oid => '.1.3.6.1.4.1.12124.1.1.2', map => \%mapping_health },
nodeCount => { oid => '.1.3.6.1.4.1.12124.1.1.4' },
onlineNodes => { oid => '.1.3.6.1.4.1.12124.1.1.6' },
ifsTotalBytes => { oid => '.1.3.6.1.4.1.12124.1.3.1' },
ifsUsedBytes => { oid => '.1.3.6.1.4.1.12124.1.3.2' },
ifsAvailableBytes => { oid => '.1.3.6.1.4.1.12124.1.3.3' },
};
my $oid_clusterStatus = '.1.3.6.1.4.1.12124.1.1';
my $oid_ifsFilesystem = '.1.3.6.1.4.1.12124.1.3';
sub manage_selection {
my ($self, %options) = @_;
$self->{results} = $options{snmp}->get_multiple_table(oids => [{ oid => $oid_clusterStatus },
{ oid => $oid_ifsFilesystem },
],
nothing_quit => 1, return_type => 1);
my $result = $options{snmp}->map_instance(mapping => $mapping, results => $self->{results}, instance => '0');
my @online_nodes = split(/,/, $result->{onlineNodes});
my $health = scalar(@online_nodes) * 100 / $result->{nodeCount};
$self->{cluster} = {
status => $result->{clusterHealth},
health => $health,
total => $result->{ifsTotalBytes},
used => $result->{ifsUsedBytes},
};
}
1;
__END__
=head1 MODE
Check cluster usages.
=over 8
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='^status$'
=item B<--warning-status>
Set warning threshold for status (Default: '%{status} =~ /attn/).
Can used special variables like: %{status}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} =~ /down|invalid/').
Can used special variables like: %{status}
=item B<--warning-*>
Threshold warning.
Can be: 'ifs-usage', 'health'.
=item B<--critical-*>
Threshold critical.
Can be: 'ifs-usage', 'health'.
=item B<--units>
Units of thresholds (Default: '%') ('%', 'B').
=item B<--free>
Thresholds are on free space left.
=back
=cut
| Tpo76/centreon-plugins | storage/emc/isilon/snmp/mode/clusterusage.pm | Perl | apache-2.0 | 9,009 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Services::GoogleAdsService;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);
sub mutate {
my $self = shift;
my $request_body = shift;
my $http_method = 'POST';
my $request_path = 'v8/customers/{+customerId}/googleAds:mutate';
my $response_type =
'Google::Ads::GoogleAds::V8::Services::GoogleAdsService::MutateGoogleAdsResponse';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
sub search {
my $self = shift;
my $request_body = shift;
my $http_method = 'POST';
my $request_path = 'v8/customers/{+customerId}/googleAds:search';
my $response_type =
'Google::Ads::GoogleAds::V8::Services::GoogleAdsService::SearchGoogleAdsResponse';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
sub search_stream {
my $self = shift;
my $request_body = shift;
my $content_callback = shift;
my $http_method = 'POST';
my $request_path = 'v8/customers/{+customerId}/googleAds:searchStream';
my $response_type =
'Google::Ads::GoogleAds::V8::Services::GoogleAdsService::SearchGoogleAdsStreamResponse';
return $self->SUPER::call(
$http_method, $request_path, $request_body,
$response_type, $content_callback
);
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Services/GoogleAdsService.pm | Perl | apache-2.0 | 1,921 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Services::HotelPerformanceViewService::GetHotelPerformanceViewRequest;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Services/HotelPerformanceViewService/GetHotelPerformanceViewRequest.pm | Perl | apache-2.0 | 1,073 |
package Google::Ads::AdWords::v201809::SharedCriterionService::mutateResponse;
use strict;
use warnings;
{ # BLOCK to scope variables
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' }
__PACKAGE__->__set_name('mutateResponse');
__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::v201809::SharedCriterionReturnValue',
},
{
'rval' => 'rval',
}
);
} # end BLOCK
} # end of BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201809::SharedCriterionService::mutateResponse
=head1 DESCRIPTION
Perl data type class for the XML Schema defined element
mutateResponse from the namespace https://adwords.google.com/api/adwords/cm/v201809.
=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::v201809::SharedCriterionService::mutateResponse->new($data);
Constructor. The following data structure may be passed to new():
{
rval => $a_reference_to, # see Google::Ads::AdWords::v201809::SharedCriterionReturnValue
},
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/SharedCriterionService/mutateResponse.pm | Perl | apache-2.0 | 1,822 |
=pod
=head1 NAME
OSSL_STORE_LOADER,
OSSL_STORE_LOADER_fetch,
OSSL_STORE_LOADER_up_ref,
OSSL_STORE_LOADER_free,
OSSL_STORE_LOADER_get0_provider,
OSSL_STORE_LOADER_get0_properties,
OSSL_STORE_LOADER_is_a,
OSSL_STORE_LOADER_get0_description,
OSSL_STORE_LOADER_do_all_provided,
OSSL_STORE_LOADER_names_do_all,
OSSL_STORE_LOADER_CTX, OSSL_STORE_LOADER_new,
OSSL_STORE_LOADER_get0_engine, OSSL_STORE_LOADER_get0_scheme,
OSSL_STORE_LOADER_set_open, OSSL_STORE_LOADER_set_open_ex,
OSSL_STORE_LOADER_set_attach, OSSL_STORE_LOADER_set_ctrl,
OSSL_STORE_LOADER_set_expect, OSSL_STORE_LOADER_set_find,
OSSL_STORE_LOADER_set_load, OSSL_STORE_LOADER_set_eof,
OSSL_STORE_LOADER_set_error, OSSL_STORE_LOADER_set_close,
OSSL_STORE_register_loader, OSSL_STORE_unregister_loader,
OSSL_STORE_open_fn, OSSL_STORE_open_ex_fn,
OSSL_STORE_attach_fn, OSSL_STORE_ctrl_fn,
OSSL_STORE_expect_fn, OSSL_STORE_find_fn,
OSSL_STORE_load_fn, OSSL_STORE_eof_fn, OSSL_STORE_error_fn,
OSSL_STORE_close_fn - Types and functions to manipulate, register and
unregister STORE loaders for different URI schemes
=head1 SYNOPSIS
#include <openssl/store.h>
typedef struct ossl_store_loader_st OSSL_STORE_LOADER;
OSSL_STORE_LOADER *OSSL_STORE_LOADER_fetch(OSSL_LIB_CTX *libctx,
const char *scheme,
const char *properties);
int OSSL_STORE_LOADER_up_ref(OSSL_STORE_LOADER *loader);
void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader);
const OSSL_PROVIDER *OSSL_STORE_LOADER_get0_provider(const OSSL_STORE_LOADER *
loader);
const char *OSSL_STORE_LOADER_get0_properties(const OSSL_STORE_LOADER *loader);
const char *OSSL_STORE_LOADER_get0_description(const OSSL_STORE_LOADER *loader);
int OSSL_STORE_LOADER_is_a(const OSSL_STORE_LOADER *loader,
const char *scheme);
void OSSL_STORE_LOADER_do_all_provided(OSSL_LIB_CTX *libctx,
void (*user_fn)(OSSL_STORE_LOADER *loader,
void *arg),
void *user_arg);
int OSSL_STORE_LOADER_names_do_all(const OSSL_STORE_LOADER *loader,
void (*fn)(const char *name, void *data),
void *data);
The following functions have been deprecated since OpenSSL 3.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:
OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme);
const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER
*store_loader);
const char *OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER
*store_loader);
/* struct ossl_store_loader_ctx_st is defined differently by each loader */
typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX;
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_fn)(
const char *uri, const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_open_fn store_open_function);
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_ex_fn)(
const char *uri, const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_open_ex
(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_open_ex_fn store_open_ex_function);
typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_attach_fn)
(const OSSL_STORE_LOADER *loader, BIO *bio,
OSSL_LIB_CTX *libctx, const char *propq,
const UI_METHOD *ui_method, void *ui_data);
int OSSL_STORE_LOADER_set_attach(OSSL_STORE_LOADER *loader,
OSSL_STORE_attach_fn attach_function);
typedef int (*OSSL_STORE_ctrl_fn)(OSSL_STORE_LOADER_CTX *ctx, int cmd,
va_list args);
int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_ctrl_fn store_ctrl_function);
typedef int (*OSSL_STORE_expect_fn)(OSSL_STORE_LOADER_CTX *ctx, int expected);
int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader,
OSSL_STORE_expect_fn expect_function);
typedef int (*OSSL_STORE_find_fn)(OSSL_STORE_LOADER_CTX *ctx,
OSSL_STORE_SEARCH *criteria);
int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader,
OSSL_STORE_find_fn find_function);
typedef OSSL_STORE_INFO *(*OSSL_STORE_load_fn)(OSSL_STORE_LOADER_CTX *ctx,
UI_METHOD *ui_method,
void *ui_data);
int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_load_fn store_load_function);
typedef int (*OSSL_STORE_eof_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_eof_fn store_eof_function);
typedef int (*OSSL_STORE_error_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_error_fn store_error_function);
typedef int (*OSSL_STORE_close_fn)(OSSL_STORE_LOADER_CTX *ctx);
int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *store_loader,
OSSL_STORE_close_fn store_close_function);
void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *store_loader);
int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader);
OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme);
=head1 DESCRIPTION
B<OSSL_STORE_LOADER> is a method for OSSL_STORE loaders, which implement
OSSL_STORE_open(), OSSL_STORE_open_ex(), OSSL_STORE_load(),
OSSL_STORE_eof(), OSSL_STORE_error() and OSSL_STORE_close() for specific
storage schemes.
OSSL_STORE_LOADER_fetch() looks for an implementation for a storage
I<scheme> within the providers that has been loaded into the B<OSSL_LIB_CTX>
given by I<libctx>, and with the properties given by I<properties>.
OSSL_STORE_LOADER_up_ref() increments the reference count for the given
I<loader>.
OSSL_STORE_LOADER_free() decrements the reference count for the given
I<loader>, and when the count reaches zero, frees it.
OSSL_STORE_LOADER_get0_provider() returns the provider of the given
I<loader>.
OSSL_STORE_LOADER_get0_properties() returns the property definition associated
with the given I<loader>.
OSSL_STORE_LOADER_is_a() checks if I<loader> is an implementation
of an algorithm that's identifiable with I<scheme>.
OSSL_STORE_LOADER_get0_description() returns a description of the I<loader>, meant
for display and human consumption. The description is at the discretion of the
I<loader> implementation.
OSSL_STORE_LOADER_do_all_provided() traverses all store implementations
by all activated providers in the library context I<libctx>, and for each
of the implementations, calls I<user_fn> with the implementation method and
I<user_arg> as arguments.
OSSL_STORE_LOADER_names_do_all() traverses all names for the given
I<loader>, and calls I<fn> with each name and I<data>.
=head2 Legacy Types and Functions (deprecated)
These functions help applications and engines to create loaders for
schemes they support. These are all deprecated and discouraged in favour of
provider implementations, see L<provider-storemgmt(7)>.
B<OSSL_STORE_LOADER_CTX> is a type template, to be defined by each loader
using C<struct ossl_store_loader_ctx_st { ... }>.
B<OSSL_STORE_open_fn>, B<OSSL_STORE_open_ex_fn>,
B<OSSL_STORE_ctrl_fn>, B<OSSL_STORE_expect_fn>, B<OSSL_STORE_find_fn>,
B<OSSL_STORE_load_fn>, B<OSSL_STORE_eof_fn>, and B<OSSL_STORE_close_fn>
are the function pointer types used within a STORE loader.
The functions pointed at define the functionality of the given loader.
=over 4
=item B<OSSL_STORE_open_fn> and B<OSSL_STORE_open_ex_fn>
B<OSSL_STORE_open_ex_fn> takes a URI and is expected to
interpret it in the best manner possible according to the scheme the
loader implements. It also takes a B<UI_METHOD> and associated data,
to be used any time something needs to be prompted for, as well as a
library context I<libctx> with an associated property query I<propq>,
to be used when fetching necessary algorithms to perform the loads.
Furthermore, this function is expected to initialize what needs to be
initialized, to create a private data store (B<OSSL_STORE_LOADER_CTX>,
see above), and to return it.
If something goes wrong, this function is expected to return NULL.
B<OSSL_STORE_open_fn> does the same thing as
B<OSSL_STORE_open_ex_fn> but uses NULL for the library
context I<libctx> and property query I<propq>.
=item B<OSSL_STORE_attach_fn>
This function takes a B<BIO>, otherwise works like
B<OSSL_STORE_open_ex_fn>.
=item B<OSSL_STORE_ctrl_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer, a command number
I<cmd> and a B<va_list> I<args> and is used to manipulate loader
specific parameters.
=begin comment
Globally known command numbers are documented in L<OSSL_STORE_ctrl(3)>,
along with what I<args> are expected with each of them.
=end comment
Loader specific command numbers must begin at B<OSSL_STORE_C_CUSTOM_START>.
Any number below that is reserved for future globally known command
numbers.
This function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_expect_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a B<OSSL_STORE_INFO>
identity I<expected>, and is used to tell the loader what object type is
expected.
I<expected> may be zero to signify that no specific object type is expected.
This function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_find_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a
B<OSSL_STORE_SEARCH> search criterion, and is used to tell the loader what
to search for.
When called with the loader context being NULL, this function is expected
to return 1 if the loader supports the criterion, otherwise 0.
When called with the loader context being something other than NULL, this
function is expected to return 1 on success, 0 on error.
=item B<OSSL_STORE_load_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and a B<UI_METHOD>
with associated data.
It's expected to load the next available data, mold it into a data
structure that can be wrapped in a B<OSSL_STORE_INFO> using one of the
L<OSSL_STORE_INFO(3)> functions.
If no more data is available or an error occurs, this function is
expected to return NULL.
The B<OSSL_STORE_eof_fn> and B<OSSL_STORE_error_fn> functions must indicate if
it was in fact the end of data or if an error occurred.
Note that this function retrieves I<one> data item only.
=item B<OSSL_STORE_eof_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
return 1 to indicate that the end of available data has been reached.
It is otherwise expected to return 0.
=item B<OSSL_STORE_error_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
return 1 to indicate that an error occurred in a previous call to the
B<OSSL_STORE_load_fn> function.
It is otherwise expected to return 0.
=item B<OSSL_STORE_close_fn>
This function takes a B<OSSL_STORE_LOADER_CTX> pointer and is expected to
close or shut down what needs to be closed, and finally free the
contents of the B<OSSL_STORE_LOADER_CTX> pointer.
It returns 1 on success and 0 on error.
=back
OSSL_STORE_LOADER_new() creates a new B<OSSL_STORE_LOADER>.
It takes an B<ENGINE> I<e> and a string I<scheme>.
I<scheme> must I<always> be set.
Both I<e> and I<scheme> are used as is and must therefore be alive as
long as the created loader is.
OSSL_STORE_LOADER_get0_engine() returns the engine of the I<store_loader>.
OSSL_STORE_LOADER_get0_scheme() returns the scheme of the I<store_loader>.
OSSL_STORE_LOADER_set_open() sets the opener function for the
I<store_loader>.
OSSL_STORE_LOADER_set_open_ex() sets the opener with library context
function for the I<store_loader>.
OSSL_STORE_LOADER_set_attach() sets the attacher function for the
I<store_loader>.
OSSL_STORE_LOADER_set_ctrl() sets the control function for the
I<store_loader>.
OSSL_STORE_LOADER_set_expect() sets the expect function for the
I<store_loader>.
OSSL_STORE_LOADER_set_load() sets the loader function for the
I<store_loader>.
OSSL_STORE_LOADER_set_eof() sets the end of file checker function for the
I<store_loader>.
OSSL_STORE_LOADER_set_close() sets the closing function for the
I<store_loader>.
OSSL_STORE_LOADER_free() frees the given I<store_loader>.
OSSL_STORE_register_loader() register the given I<store_loader> and
thereby makes it available for use with OSSL_STORE_open(),
OSSL_STORE_open_ex(), OSSL_STORE_load(), OSSL_STORE_eof()
and OSSL_STORE_close().
OSSL_STORE_unregister_loader() unregister the store loader for the given
I<scheme>.
=head1 RETURN VALUES
OSSL_STORE_LOADER_fetch() returns a pointer to an OSSL_STORE_LOADER object,
or NULL on error.
OSSL_STORE_LOADER_up_ref() returns 1 on success, or 0 on error.
OSSL_STORE_LOADER_names_do_all() returns 1 if the callback was called for all
names. A return value of 0 means that the callback was not called for any names.
OSSL_STORE_LOADER_free() doesn't return any value.
OSSL_STORE_LOADER_get0_provider() returns a pointer to a provider object, or
NULL on error.
OSSL_STORE_LOADER_get0_properties() returns a pointer to a property
definition string, or NULL on error.
OSSL_STORE_LOADER_is_a() returns 1 if I<loader> was identifiable,
otherwise 0.
OSSL_STORE_LOADER_get0_description() returns a pointer to a description, or NULL if
there isn't one.
The functions with the types B<OSSL_STORE_open_fn>,
B<OSSL_STORE_open_ex_fn>, B<OSSL_STORE_ctrl_fn>,
B<OSSL_STORE_expect_fn>, B<OSSL_STORE_load_fn>, B<OSSL_STORE_eof_fn>
and B<OSSL_STORE_close_fn> have the same return values as OSSL_STORE_open(),
OSSL_STORE_open_ex(), OSSL_STORE_ctrl(), OSSL_STORE_expect(),
OSSL_STORE_load(), OSSL_STORE_eof() and OSSL_STORE_close(), respectively.
OSSL_STORE_LOADER_new() returns a pointer to a B<OSSL_STORE_LOADER> on success,
or NULL on failure.
OSSL_STORE_LOADER_set_open(), OSSL_STORE_LOADER_set_open_ex(),
OSSL_STORE_LOADER_set_ctrl(), OSSL_STORE_LOADER_set_load(),
OSSL_STORE_LOADER_set_eof() and OSSL_STORE_LOADER_set_close() return 1
on success, or 0 on failure.
OSSL_STORE_register_loader() returns 1 on success, or 0 on failure.
OSSL_STORE_unregister_loader() returns the unregistered loader on success,
or NULL on failure.
=head1 SEE ALSO
L<ossl_store(7)>, L<OSSL_STORE_open(3)>, L<OSSL_LIB_CTX(3)>,
L<provider-storemgmt(7)>
=head1 HISTORY
OSSL_STORE_LOADER_fetch(), OSSL_STORE_LOADER_up_ref(),
OSSL_STORE_LOADER_free(), OSSL_STORE_LOADER_get0_provider(),
OSSL_STORE_LOADER_get0_properties(), OSSL_STORE_LOADER_is_a(),
OSSL_STORE_LOADER_do_all_provided() and
OSSL_STORE_LOADER_names_do_all() were added in OpenSSL 3.0.
OSSL_STORE_open_ex_fn() was added in OpenSSL 3.0.
B<OSSL_STORE_LOADER>, B<OSSL_STORE_LOADER_CTX>, OSSL_STORE_LOADER_new(),
OSSL_STORE_LOADER_set0_scheme(), OSSL_STORE_LOADER_get0_scheme(),
OSSL_STORE_LOADER_get0_engine(), OSSL_STORE_LOADER_set_expect(),
OSSL_STORE_LOADER_set_find(), OSSL_STORE_LOADER_set_attach(),
OSSL_STORE_LOADER_set_open_ex(), OSSL_STORE_LOADER_set_open(),
OSSL_STORE_LOADER_set_ctrl(),
OSSL_STORE_LOADER_set_load(), OSSL_STORE_LOADER_set_eof(),
OSSL_STORE_LOADER_set_close(), OSSL_STORE_LOADER_free(),
OSSL_STORE_register_loader(), OSSL_STORE_LOADER_set_error(),
OSSL_STORE_unregister_loader(), OSSL_STORE_open_fn(), OSSL_STORE_ctrl_fn(),
OSSL_STORE_load_fn(), OSSL_STORE_eof_fn() and OSSL_STORE_close_fn()
were added in OpenSSL 1.1.1, and became deprecated in OpenSSL 3.0.
=head1 COPYRIGHT
Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| openssl/openssl | doc/man3/OSSL_STORE_LOADER.pod | Perl | apache-2.0 | 16,226 |
#
# 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::alcatel::omniswitch::snmp::mode::hardware;
use base qw(centreon::plugins::templates::hardware);
use network::alcatel::omniswitch::snmp::mode::components::resources qw(%oids);
sub set_system {
my ($self, %options) = @_;
$self->{regexp_threshold_overload_check_section_option} = '^(backplane|chassis|container|fan|module|other|port|psu|sensor|stack|unknown)$';
$self->{cb_hook2} = 'snmp_execute';
$self->{thresholds} = {
admin => [
['^(reset|takeover|resetWithFabric|takeoverWithFabrc)$', 'WARNING'],
['^(powerOff)$', 'CRITICAL'],
['powerOn', 'OK'],
['standby', 'OK'],
],
oper => [
['^(testing)$', 'WARNING'],
['^(unpowered|down|notpresent)$', 'CRITICAL'],
['up', 'OK'],
['secondary', 'OK'],
['master', 'OK'],
['idle', 'OK'],
],
fan => [
['^noStatus$', 'UNKNOWN'],
['^notRunning$', 'CRITICAL'],
['running', 'OK'],
],
};
$self->{components_path} = 'network::alcatel::omniswitch::snmp::mode::components';
$self->{components_module} = ['backplane', 'chassis', 'container', 'fan', 'module', 'other', 'port', 'psu', 'sensor', 'stack', 'unknown'];
}
sub snmp_execute {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->{results} = $self->{snmp}->get_multiple_table(oids => [
{ oid => $oids{entPhysicalClass} },
{ oid => $oids{alaChasEntPhysFanStatus} },
]);
$self->{results}->{entity} = $self->{snmp}->get_multiple_table(oids => [
{ oid => $oids{entPhysicalDescr} },
{ oid => $oids{entPhysicalName} },
{ oid => $oids{chasEntPhysAdminStatus} },
{ oid => $oids{chasEntPhysOperStatus} },
{ oid => $oids{chasEntPhysPower} },
], return_type => 1);
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
});
return $self;
}
1;
__END__
=head1 MODE
Check status of alcatel hardware (AlcatelIND1Chassis.mib).
=over 8
=item B<--component>
Which component to check (Default: '.*').
Can be: 'other', 'unknown', 'chassis', 'backplane', 'container', 'psu', 'fan',
'sensor', 'module', 'port, 'stack'.
Some not exists ;)
=item B<--filter>
Exclude some parts (comma seperated list) (Example: --filter=fan)
Can also exclude specific instance: --filter=fan,1.2
=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='psu.oper,CRITICAL,standby'
=back
=cut
| wilfriedcomte/centreon-plugins | network/alcatel/omniswitch/snmp/mode/hardware.pm | Perl | apache-2.0 | 3,791 |
#!/usr/bin/perl
# Obeyed env variables:
# OXI_TEST_ONLY (Str: comma separated list of tests dirs/files)
# OXI_TEST_ALL (Bool: 1 = run all tests)
# OXI_TEST_COVERAGE (Bool: 1 = only run coverage tests)
# OXI_TEST_GITREPO (Str: Git repository)
# OXI_TEST_GITBRANCH (Str: Git branch, default branch if not specified)
use strict;
use warnings;
# Core modules
use Cwd qw( realpath );
use File::Copy;
use File::Path qw( make_path );
use FindBin qw( $Bin );
use Getopt::Long;
use IPC::Open3 qw( open3 );
use List::Util qw( sum );
use Pod::Usage;
use POSIX ":sys_wait_h";
use Symbol qw( gensym );
# Exit handler - run bash on errors to allow inspection of log files
#
sub _exit {
my ($start_bash, $code, $msg) = @_;
if ($start_bash) {
print STDERR "\n==========[ ERROR ]==========\n";
print STDERR "$msg\n" if $msg;
print STDERR "You may now inspect the log files below /var/log/openxpki/\n";
print STDERR "To finally stop the Docker container type 'exit'.\n\n";
system "/bin/bash", "-l";
}
else {
print STDERR "\n$msg\n\n" if $msg;
}
exit $code;
}
sub _failure {
my ($die_on_error, $code, $msg) = @_;
return $code unless $die_on_error;
my $start_bash = not $ENV{OXI_TEST_NONINTERACTIVE};
_exit $start_bash, $code, $msg;
}
sub _stop {
my ($code, $msg) = @_;
_exit 0, $code, $msg;
}
# $mode:
# code - hide output and return exit code
# capture - hide output and return it as string instead, exit on errors
# show - show output and return nothing, exit on errors
sub execute {
my ($mode, $args, $tolerate_errors) = @_;
$args = [ split /\s+/, $args ] unless ref $args eq "ARRAY";
my $output = ($mode eq "show") ? ">&STDOUT" : gensym; # gensym = filehandle
# execute command and wait for it to finish
my $pid = open3(0, $output, 0, @$args);
waitpid($pid, 0);
my $die_on_error = not ($mode eq "code" or $tolerate_errors);
my $output_str = ref $output eq "GLOB" ? do { local $/; <$output> } : "";
return _failure($die_on_error, -1) if $? == -1; # execute failed: error message was already shown by system()
return _failure($die_on_error, $? & 127, sprintf( "'%s' died with signal %d: %s", $args->[0], ($? & 127), $output_str )) if ($? & 127);
return _failure($die_on_error, $? >> 8, sprintf( "'%s' exited with code %d: %s", $args->[0], $? >> 8, $output_str )) if ($? >> 8);
return if $mode eq "show";
return $output_str if $mode eq "capture";
return 0;
}
my $clone_dir = "/opt/openxpki";
my @test_only = split ",", $ENV{OXI_TEST_ONLY};
my $mode = $ENV{OXI_TEST_ALL} ? "all" : (
$ENV{OXI_TEST_COVERAGE} ? "coverage" : "selected"
);
my @tests_unit;
my @tests_qa;
if ($mode eq "all") {
@tests_unit = "t/";
# testing api/ before nice/ leads to errors!
@tests_qa = qw( qatest/backend/nice qatest/backend/api qatest/backend/api2 qatest/backend/webui qatest/client );
}
elsif ($mode eq "selected") {
my @tests = split /,/, $ENV{OXI_TEST_ONLY};
@tests_unit = grep { /^t\// } map { $_ =~ s/ ^ core\/server\/ //x; $_ } @tests;
@tests_qa = grep { /^qatest\// } @tests;
}
#
# Test arguments and repository
#
my $repo;
my $is_local_repo = 0;
# remote repo as specified
if ($ENV{OXI_TEST_GITREPO}) {
$repo = $ENV{OXI_TEST_GITREPO};
_stop 100, "Sorry, local repositories specified by file:// are not supported:\n$repo"
if $repo =~ / \A file /msx;
}
# local repo from host (if Docker volume is mounted)
else {
# check if /repo is a mountpoint (= dev number differs from parent dir)
_stop 101, "I need either a remote or local Git repo:\ndocker run -e OXI_TEST_GITREPO=https://...\ndocker run -v /my/path:/repo"
unless ((stat "/repo")[0]) != ((stat "/")[0]);
$repo = "file:///repo";
$is_local_repo = 1;
}
_stop 103, "Code coverage tests only work with local repo" if ($mode eq "coverage" and not $is_local_repo);
my $code = execute code => [ "git", "ls-remote", "-h", $repo ];
_stop 104, "Remote repo either does not exist or is not readable" if $code;
#
# Clone repository
#
print "\n.--==##[ Run tests in Docker container ]##==\n";
print "| Cloning repo... ";
my @branch_spec = $ENV{OXI_TEST_GITBRANCH} ? "--branch=".$ENV{OXI_TEST_GITBRANCH} : ();
my @restrict_depth = $ENV{OXI_TEST_GITCOMMIT} ? () : ("--depth=1");
execute capture => [ "git", "clone", @restrict_depth, @branch_spec, $repo, $clone_dir ];
if ($ENV{OXI_TEST_GITCOMMIT}) {
print "Checking out given commit... ";
chdir $clone_dir;
execute capture => [ "git", "checkout", $ENV{OXI_TEST_GITCOMMIT} ];
}
print "\n";
#
# Info
#
printf "| Repo: %s\n", $ENV{OXI_TEST_GITREPO} ? $ENV{OXI_TEST_GITREPO} : "local";
printf "| Branch: %s\n", $ENV{OXI_TEST_GITBRANCH} // "(default)";
printf "| Commit: %s\n", $ENV{OXI_TEST_GITCOMMIT} // "HEAD";
chdir $clone_dir;
my $logmsg = execute capture => [ "git", "log", "--format=%B", "-n" => 1, $ENV{OXI_TEST_GITCOMMIT} // "HEAD", ];
$logmsg =~ s/\R$//gm; # remove trailing newline
($logmsg) = split /\R/, $logmsg; # only print first line
printf "| » %s «\n", $logmsg;
my $msg = $ENV{OXI_TEST_ALL} ? " all tests" : ($ENV{OXI_TEST_COVERAGE} ? " code coverage" : " selected tests:");
my $big_msg = `figlet '$msg'`; $big_msg =~ s/^/| /msg;
print $big_msg;
printf "| - $_\n" for @test_only;
print "|\n";
print ".--==#####################################==\n";
#
# Grab and install Perl module dependencies from Makefile.PL using PPI
#
print "\n====[ Scanning Makefile.PL for new Perl dependencies ]====\n";
my $cpanfile = execute capture => "/tools-copy/scripts/makefile2cpanfile.pl $clone_dir/core/server/Makefile.PL";
open my $fh, ">", "$clone_dir/cpanfile";
print $fh $cpanfile;
close $fh;
execute show => "cpanm --quiet --notest --installdeps $clone_dir";
#
# Database setup
#
print "\n====[ MySQL ]====\n";
my $dummy = gensym;
my $pid = open3(0, $dummy, 0, qw(sh -c mysqld) );
execute show => "/tools-copy/testenv/mysql-wait-for-db.sh";
execute show => "/tools-copy/testenv/mysql-create-user.sh";
# if there are only qatests, we create the database later on
if ($mode eq "coverage" or scalar @tests_unit) {
execute show => "/tools-copy/testenv/mysql-create-db.sh";
execute show => "/tools-copy/testenv/mysql-create-schema.sh $clone_dir/config/sql/schema-mysql.sql";
}
#
# OpenXPKI compilation
#
print "\n====[ Compile OpenXPKI ]====\n";
## Config::Versioned reads USER env variable
#export USER=dummy
chdir "$clone_dir/core/server";
`perl Makefile.PL`;
`make`;
#
# Test coverage
#
if ($mode eq "coverage") {
print "\n====[ Testing the code coverage (this will take a while) ]====\n";
my $code = execute code => "cover -test";
print "Please note that some unit tests did not pass\n" if $code != 0;
use DateTime;
my $dirname = "code-coverage-".DateTime->new->strftime('%Y%m%d-%H%M%S');
move "./cover_db", "/repo/$dirname";
`chmod -R g+w,o+w "/repo/$dirname`;
print "\nCode coverage results available in project root dir:\n$dirname\n";
exit;
}
#
# Unit tests
#
if (scalar @tests_unit) {
print "\n====[ Testing: unit tests ]====\n";
execute show => "prove -b -r -q $_" for @tests_unit;
}
exit unless scalar @tests_qa;
#
# OpenXPKI installation
#
print "\n====[ Install OpenXPKI ]====\n";
print "Copying files\n";
`make install`;
# directory list borrowed from /package/debian/core/libopenxpki-perl.dirs
make_path "/var/openxpki/session", "/var/log/openxpki";
# copy config
`cp -R $clone_dir/config/openxpki /etc`;
# customize config
use File::Slurp qw( edit_file );
edit_file { s/ ^ ( (user|group): \s+ ) \w+ /$1root/gmsx } "/etc/openxpki/config.d/system/server.yaml";
execute show => "/tools-copy/testenv/mysql-oxi-config.sh";
#
# Database (re-)creation
#
execute show => "/tools-copy/testenv/mysql-create-db.sh";
execute show => "/tools-copy/testenv/mysql-create-schema.sh $clone_dir/config/sql/schema-mysql.sql";
#
# Sample config (CA certificates etc.)
#
execute show => "/tools-copy/testenv/insert-certificates.sh";
#
# Start OpenXPKI
#
execute show => "/usr/local/bin/openxpkictl start";
#
# QA tests
#
print "\n====[ Testing: QA tests ]====\n";
chdir "$clone_dir/qatest";
my @t = map { $_ =~ s/ ^ qatest\/ //x; $_ } @tests_qa;
execute show => "prove -l -r -q $_" for @t;
| stefanomarty/openxpki | tools/docker-test/startup.pl | Perl | apache-2.0 | 8,337 |
package Paws::Rekognition::Eyeglasses;
use Moose;
has Confidence => (is => 'ro', isa => 'Num');
has Value => (is => 'ro', isa => 'Bool');
1;
### main pod documentation begin ###
=head1 NAME
Paws::Rekognition::Eyeglasses
=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::Rekognition::Eyeglasses object:
$service_obj->Method(Att1 => { Confidence => $value, ..., Value => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::Rekognition::Eyeglasses object:
$result = $service_obj->Method(...);
$result->Att1->Confidence
=head1 DESCRIPTION
Indicates whether or not the face is wearing eye glasses, and the
confidence level in the determination.
=head1 ATTRIBUTES
=head2 Confidence => Num
Level of confidence in the determination.
=head2 Value => Bool
Boolean value that indicates whether the face is wearing eye glasses or
not.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::Rekognition>
=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/Rekognition/Eyeglasses.pm | Perl | apache-2.0 | 1,503 |
=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::Component::Family::ComparaFamily;
use strict;
use warnings;
no warnings "uninitialized";
use base qw(EnsEMBL::Web::Component::Gene::FamilyProteins);
sub _get_details {
### Override parent method, so we can get the desired objects
### from the tree, not the gene
my $self = shift;
return (undef, $self->object->family);
}
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Web/Component/Family/ComparaFamily.pm | Perl | apache-2.0 | 1,065 |
# OpenXPKI::Crypto::Profile::CRL.pm
# Written 2005 by Michael Bell for the OpenXPKI project
# Copyright (C) 2005-2006 by The OpenXPKI Project
=head1 Name
OpenXPKI::Crypto::Profile::CRL - cryptographic profile for CRLs.
=cut
use strict;
use warnings;
package OpenXPKI::Crypto::Profile::CRL;
use base qw(OpenXPKI::Crypto::Profile::Base);
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Debug;
use OpenXPKI::Exception;
use English;
use DateTime;
use Data::Dumper;
#use Smart::Comments;
=head2 new ( { CA, [VALIDITY, CA_VALIDITY, CACERTIFICATE] } )
Create a new profile instance.
=over
=item CA
The alias of the ca token to be used (from the alias table)
=item VALIDITY
optional, override validity from profile definition.
Must be a hashref useable with OpenXPKI::DateTime::get_validity.
Only relative dates are supported.
=item CA_VALIDITY
optional, if given the computed nextupdate is checked if it exceeds the
ca validity and uses the validity set in I<crl.<profile>.lastcrl>.
Absolute dates are supported but the actual timestamp in the crl might
differ as it is converted to "hours from now".
=item CACERTIFICATE
PEM encoded ca certificate to use. This is mainly for testing, in regular
operation the certificate is determined using the API.
=back
=cut
sub new {
my $that = shift;
my $class = ref($that) || $that;
my $self = {};
bless $self, $class;
my $keys = { @_ };
$self->{CA} = $keys->{CA} if ($keys->{CA});
$self->{VALIDITY} = $keys->{VALIDITY} if ($keys->{VALIDITY});
$self->{CA_VALIDITY} = $keys->{CA_VALIDITY} if ($keys->{CA_VALIDITY});
if (not $self->{CA})
{
OpenXPKI::Exception->throw (
message => "I18N_OPENXPKI_CRYPTO_PROFILE_CRL_NEW_MISSING_CA");
}
##! 2: "parameters ok"
$self->__load_profile ();
##! 2: "config loaded"
return $self;
}
=head2 __load_profile
Load the profile, called from constructor
=cut
sub __load_profile
{
my $self = shift;
my $config = CTX('config');
my $ca_profile_name = $self->{CA};
my $pki_realm = CTX('session')->get_pki_realm();
my $path;
my $validity;
# Check if there is a named profile, otherwise use default
if (!$config->get_meta("crl.$ca_profile_name")) {
$ca_profile_name = 'default';
}
$path = "crl.default";
##! 16: "Using config at $path";
$self->{PROFILE}->{DIGEST} = $config->get("$path.digest");
# use local setting for validity
if ($self->{VALIDITY}) {
##! 16: "Override validity: " . $self->{VALIDITY}
$validity = $self->{VALIDITY};
} else {
$validity = {
VALIDITYFORMAT => 'relativedate',
VALIDITY => $config->get("$path.validity.nextupdate"),
};
}
if (!$validity || !$validity->{VALIDITY}) {
OpenXPKI::Exception->throw (
message => "I18N_OPENXPKI_CRYPTO_PROFILE_CRL_LOAD_PROFILE_VALIDITY_NOTAFTER_NOT_DEFINED",
);
}
# for error handling
delete $self->{PROFILE}->{DAYS};
delete $self->{PROFILE}->{HOURS};
my $notafter;
# plain days
if ($validity->{VALIDITYFORMAT} eq "days") {
$self->{PROFILE}->{DAYS} = $validity->{VALIDITY};
$self->{PROFILE}->{HOURS} = 0;
$notafter = DateTime->now( time_zone => 'UTC' )->add( days => $validity->{VALIDITY} );
}
# handle relative date formats ("+0002" for two months)
if ($validity->{VALIDITYFORMAT} eq "relativedate") {
$notafter = OpenXPKI::DateTime::get_validity($validity);
my $hours = sprintf("%d", ($notafter->epoch() - time) / 3600);
my $days = sprintf("%d", $hours / 24);
$hours = $hours % 24;
$self->{PROFILE}->{DAYS} = $days;
$self->{PROFILE}->{HOURS} = $hours;
}
# only relative dates are allowed for CRLs
if (! exists $self->{PROFILE}->{DAYS}) {
OpenXPKI::Exception->throw (
message => "I18N_OPENXPKI_CRYPTO_PROFILE_CRL_LOAD_PROFILE_INVALID_VALIDITY_FORMAT",
params => $validity,
);
}
# Check if the CA would be valid at the next update or if its time for the "End of Life" CRL
my $ca_validity;
$ca_validity = OpenXPKI::DateTime::get_validity($self->{CA_VALIDITY}) if ($self->{CA_VALIDITY});
if ($ca_validity && $notafter > $ca_validity) {
my $last_crl_validity = $config->get("$path.validity.lastcrl");
if (!$last_crl_validity) {
CTX('log')->log(
MESSAGE => 'CRL for CA ' . $self->{CA}. ' in realm ' . $pki_realm . ' will be end of life before next update is scheduled!',
PRIORITY => 'warn',
FACILITY => [ 'monitor', 'application' ],
);
} else {
$notafter = OpenXPKI::DateTime::get_validity({
VALIDITYFORMAT => 'detect',
VALIDITY => $last_crl_validity,
});
my $hours = sprintf("%d", ($notafter->epoch() - time) / 3600);
my $days = sprintf("%d", $hours / 24);
$hours = $hours % 24;
$self->{PROFILE}->{DAYS} = $days;
$self->{PROFILE}->{HOURS} = $hours;
CTX('log')->log(
MESSAGE => 'CRL for CA ' . $self->{CA} . ' in realm ' . $pki_realm . ' nearly EOL - will issue with last crl interval!',
PRIORITY => 'info',
FACILITY => [ 'monitor', 'application' ],
);
}
}
# TODO - implement crl_number (but not here ...)
# possibly:
# RFC 3280, 5.2.5 - issuing_distributing_point (if someone really
# needs it ...)
foreach my $ext (qw( authority_info_access authority_key_identifier issuer_alt_name )) {
##! 16: 'load extension ' . $ext
$self->load_extension({
PATH => $path,
EXT => $ext,
});
}
##! 2: Dumper($self->{PROFILE})
##! 1: "end"
return 1;
}
sub get_nextupdate_in_days
{
my $self = shift;
return $self->{PROFILE}->{DAYS};
}
sub get_nextupdate_in_hours
{
my $self = shift;
return $self->{PROFILE}->{HOURS};
}
sub get_digest
{
my $self = shift;
return $self->{PROFILE}->{DIGEST};
}
# FIXME: this is not really needed, in fact it can damage the initial
# validity computation
# sub set_days
# {
# my $self = shift;
# $self->{PROFILE}->{DAYS} = shift;
# return 1;
# }
1;
__END__
| durko/openxpki | core/server/OpenXPKI/Crypto/Profile/CRL.pm | Perl | apache-2.0 | 6,575 |
package Paws::ApiGateway::DeleteDeployment;
use Moose;
has DeploymentId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'deploymentId', required => 1);
has RestApiId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'restApiId', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DeleteDeployment');
class_has _api_uri => (isa => 'Str', is => 'ro', default => '/restapis/{restapi_id}/deployments/{deployment_id}');
class_has _api_method => (isa => 'Str', is => 'ro', default => 'DELETE');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ApiGateway::DeleteDeployment - Arguments for method DeleteDeployment on Paws::ApiGateway
=head1 DESCRIPTION
This class represents the parameters used for calling the method DeleteDeployment on the
Amazon API Gateway service. Use the attributes of this class
as arguments to method DeleteDeployment.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DeleteDeployment.
As an example:
$service_obj->DeleteDeployment(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> DeploymentId => Str
The identifier of the Deployment resource to delete.
=head2 B<REQUIRED> RestApiId => Str
The string identifier of the associated RestApi.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DeleteDeployment in L<Paws::ApiGateway>
=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/ApiGateway/DeleteDeployment.pm | Perl | apache-2.0 | 2,082 |
package Paws::OpsWorksCM::AssociateNode;
use Moose;
has EngineAttributes => (is => 'ro', isa => 'ArrayRef[Paws::OpsWorksCM::EngineAttribute]', required => 1);
has NodeName => (is => 'ro', isa => 'Str', required => 1);
has ServerName => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'AssociateNode');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::OpsWorksCM::AssociateNodeResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::OpsWorksCM::AssociateNode - Arguments for method AssociateNode on Paws::OpsWorksCM
=head1 DESCRIPTION
This class represents the parameters used for calling the method AssociateNode on the
AWS OpsWorks for Chef Automate service. Use the attributes of this class
as arguments to method AssociateNode.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to AssociateNode.
As an example:
$service_obj->AssociateNode(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> EngineAttributes => ArrayRef[L<Paws::OpsWorksCM::EngineAttribute>]
Engine attributes used for associating the node.
B<Attributes accepted in a AssociateNode request:>
=over
=item *
C<CHEF_ORGANIZATION>: The Chef organization with which the node is
associated. By default only one organization named C<default> can
exist.
=item *
C<CHEF_NODE_PUBLIC_KEY>: A PEM-formatted public key. This key is
required for the C<chef-client> agent to access the Chef API.
=back
=head2 B<REQUIRED> NodeName => Str
The name of the Chef client node.
=head2 B<REQUIRED> ServerName => Str
The name of the server with which to associate the node.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method AssociateNode in L<Paws::OpsWorksCM>
=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/OpsWorksCM/AssociateNode.pm | Perl | apache-2.0 | 2,372 |
:- module(tmpbased_common, [module_to_addressfile/2], []).
common_directory('/tmp/'). % Directory where address files are saved
module_to_addressfile(Mod, AddrPath) :-
atom_concat(Mod,'_address',AddrFile),
common_directory(Dir),
atom_concat(Dir, AddrFile, AddrPath).
| leuschel/ecce | www/CiaoDE/ciao/library/actmods/tmpbased_common.pl | Perl | apache-2.0 | 293 |
package Video::Delay::Func;
# Pragmas.
use strict;
use warnings;
# Modules.
use Class::Utils qw(set_params);
use English qw(-no_match_vars);
use Error::Pure qw(err);
# Version.
our $VERSION = 0.07;
# Constructor.
sub new {
my ($class, @params) = @_;
# Create object.
my $self = bless {}, $class;
# Math function.
$self->{'func'} = sub {
my $t = shift;
return 1000 * sin($t);
};
# Counter increment.
$self->{'incr'} = 0.1;
# Process params.
set_params($self, @params);
# Counter.
$self->{'counter'} = 0;
# Check 'func' parameters.
if (ref $self->{'func'} ne '' && ref $self->{'func'} ne 'CODE') {
err "Parameter 'func' must be scalar or code.";
}
# Object.
return $self;
}
# Get delay.
sub delay {
my $self = shift;
# Counter.
$self->{'counter'} += $self->{'incr'};
# Function string.
my $ret;
if (ref $self->{'func'} eq '') {
my $input = $self->{'func'};
my $c = $self->{'counter'};
$input =~ s/t/$c/g;
# Eval.
$ret = eval $input;
if ($EVAL_ERROR) {
err 'Error in function.',
'Error', $EVAL_ERROR;
}
# Callback.
} else {
$ret = $self->{'func'}->($self->{'counter'});
}
return $ret;
}
1;
__END__
=pod
=encoding utf8
=head1 NAME
Video::Delay::Func - Video::Delay class for delays defined by math function.
=head1 SYNOPSIS
use Video::Delay::Func;
my $obj = Video::Delay::Func->new(%parameters);
my $delay = $obj->delay;
=head1 METHODS
=over 8
=item C<new(%parameters)>
Constructor
=over 8
=item * C<func>
Math function in string with 't' time variable.
Or callback with one input argument as time variable.
Default value is reference to subroutine:
sub {
my $t = shift;
return 1000 * sin($t);
};
=item * C<incr>
Counter increment.
Default value is 0.1.
=back
=item C<delay()>
Returns delay defined by function in miliseconds.
Time si affected by 'incr' increment parameter.
=back
=head1 ERRORS
new():
Parameter 'func' must be scalar or code.
From Class::Utils::set_params():
Unknown parameter '%s'.
delay():
Error in function.
Error, %s
=head1 EXAMPLE1
# Pragmas.
use strict;
use warnings;
# Modules.
use Video::Delay::Func;
# Object.
my $obj = Video::Delay::Func->new(
'func' => sub {
my $t = shift;
return 1000 * sin($t);
},
'incr' => 0.1,
);
# Print delay.
print $obj->delay."\n";
print $obj->delay."\n";
print $obj->delay."\n";
# Output:
# 99.8334166468282
# 198.669330795061
# 295.52020666134
=head1 EXAMPLE2
# Pragmas.
use strict;
use warnings;
# Modules.
use Video::Delay::Func;
# Object.
my $obj = Video::Delay::Func->new(
'func' => '1000 * sin(t)',
'incr' => 0.1,
);
# Print delay.
print $obj->delay."\n";
print $obj->delay."\n";
print $obj->delay."\n";
# Output:
# 99.8334166468282
# 198.669330795061
# 295.52020666134
=head1 DEPENDENCIES
L<Class::Utils>,
L<English>,
L<Error::Pure>.
=head1 SEE ALSO
=over
=item L<Video::Delay>
Perl classes for delays between frames generation.
=back
=head1 REPOSITORY
L<https://github.com/tupinek/Video-Delay>
=head1 AUTHOR
Michal Špaček L<mailto:skim@cpan.org>
L<http://skim.cz>
=head1 LICENSE AND COPYRIGHT
© 2012-2015 Michal Špaček
BSD 2-Clause License
=head1 VERSION
0.07
=cut
| tupinek/Video-Delay | Delay/Func.pm | Perl | bsd-2-clause | 3,357 |
#
# Copyright (c) 2011-14, Mitchell Cooper
#
# Evented::Object: a simple yet featureful base class event framework.
# https://github.com/cooper/evented-object
#
package Evented::Object::EventFire; # leave this package name the same FOREVER.
use warnings;
use strict;
use utf8;
use 5.010;
##########################
### EVENT FIRE OBJECTS ###
##########################
our $VERSION = '5.50';
our $events = $Evented::Object::events;
our $props = $Evented::Object::props;
# create a new event object.
sub new {
my ($class, %opts) = @_;
$opts{callback_i} ||= 0;
return bless { $props => \%opts }, $class;
}
# cancel all future callbacks once.
# if stopped already, returns the reason.
sub stop {
my ($fire, $reason) = @_;
$fire->{$props}{stop} ||= $reason || 'unspecified';
}
# returns a true value if the given callback has been called.
# with no argument, returns number of callbacks called so far.
sub called {
my ($fire, $callback) = @_;
# return the number of callbacks called.
# this includes the current callback.
if (!defined $callback) {
my $called = scalar keys %{ $fire->{$props}{called} };
$called++ unless $fire->{$props}{complete};
return $called;
}
# return whether the specified callback was called.
return $fire->{$props}{called}{$callback};
}
# returns a true value if the given callback will be called soon.
# with no argument, returns number of callbacks pending.
sub pending {
my ($fire, $cb_name) = @_;
my $pending = $fire->{$props}{collection}{pending};
# return number of callbacks remaining.
if (!defined $cb_name) {
return scalar keys %$pending;
}
# return whether the specified callback is pending.
return $pending->{$cb_name};
}
# cancels a future callback once.
sub cancel {
my ($fire, $cb_name) = @_;
# if there is no argument given, we will just
# treat this like a ->stop on the event.
defined $cb_name or return $fire->stop;
# cancel the callback.
delete $fire->{$props}{collection}{pending}{$cb_name};
return 1;
}
# returns the return value of the given callback.
# if it has not yet been called, this will return undef.
# if the return value has a possibility of being undef,
# the only way to be sure is to first test ->callback_called.
sub return_of {
my ($fire, $callback) = @_;
return $fire->{$props}{return}{$callback};
}
# returns the callback that was last called.
sub last {
shift->{$props}{last_callback};
}
# returns the return value of the last-called callback.
sub last_return {
shift->{$props}{last_return};
}
# returns the callback that stopped the event.
sub stopper {
shift->{$props}{stopper};
}
# returns the name of the event being fired.
sub event_name {
shift->{$props}{name};
}
# returns the name of the callback being called.
sub callback_name {
shift->{$props}{callback_name};
}
# returns the caller(1) value of ->fire_event().
sub caller {
@{ shift->{$props}{caller} };
}
# returns the priority of the callback being called.
sub callback_priority {
shift->{$props}{callback_priority};
}
# returns the value of the 'data' option when the callback was registered.
# if an argument is provided, it is used as the key to the data hash.
sub callback_data {
my $data = shift->{$props}{callback_data};
my $key_maybe = shift;
if (ref $data eq 'HASH') {
return $data->{$key_maybe} if defined $key_maybe;
return $data->{data} // $data;
}
return $data;
}
# returns the value of the 'data' option on the ->fire().
# if an argument is provided, it is used as the key to the data hash.
sub data {
my $data = shift->{$props}{data};
my $key_maybe = shift;
if (ref $data eq 'HASH') {
return $data->{$key_maybe} if defined $key_maybe;
return $data->{data} // $data;
}
return $data;
}
# returns the evented object.
sub object {
shift->{$props}{object};
}
# returns the exception from 'safe' option, if any.
sub exception {
shift->{$props}{exception};
}
###############
### ALIASES ###
###############
sub object;
BEGIN {
*eo = *object;
}
1;
| gitpan/Evented-Object | lib/Evented/Object/EventFire.pm | Perl | bsd-3-clause | 4,203 |
# caldera-driver.pl
# Functions for printer drivers as generated by COAS
%paper_sizes = ( 'a4', 'A4',
'a3', 'A3',
'a5', 'A5',
'letter', 'US Letter',
'legal', 'Legal',
'ledger', 'Ledger' );
$driver_dir = "/etc/sysconfig/printers";
$base_driver = "$module_root_directory/base_coas_driver";
$webmin_windows_driver = 1;
# is_windows_driver(path)
# Returns the server, share, username, password, workgroup, program
# if path is a webmin windows driver
sub is_windows_driver
{
return &is_webmin_windows_driver(@_);
}
# is_driver(path)
# Returns the driver name and dpi if some path is a webmin driver, or undef
sub is_driver
{
if (!$_[0]) {
return { 'mode' => 0,
'desc' => 'None' };
}
open(DRV, $_[0]);
local @lines = <DRV>;
close(DRV);
if ($lines[1] =~ /^source ($driver_dir\/\S+)/) {
# Looks like a caldera driver! Read the sysconfig file
local %conf;
&read_env_file($1, \%conf);
if ($conf{'GSDEVICE'} eq 'NET' || $conf{'GSDEVICE'} eq 'RAW') {
# Driver isn't even used
return { 'mode' => 0,
'desc' => 'None' };
}
elsif ($conf{'GSDEVICE'} eq 'uniprint') {
# Uniprint driver
foreach $u (&list_uniprint()) {
$desc = $u->[1] if ($u->[0] eq $conf{'UPP'});
}
$desc =~ s/,.*$//g;
return { 'mode' => 3,
'upp' => $conf{'UPP'},
'paper' => $conf{'PAPERSIZE'},
'double' => lc($conf{'DOUBLEPAGE'}),
'eof' => lc($conf{'SENDEOF'}),
'desc' => $desc ? $desc : $conf{'UPP'} };
}
else {
# A caldera printer driver
open(COAS, $config{'coas_printers'});
local $plist = &parse_coas(COAS);
close(COAS);
local ($desc, $p);
foreach $p (values %$plist) {
$desc = $p->{'description'}
if ($p->{'type'}->{'0'} eq $conf{'GSDEVICE'} &&
!$desc);
}
return { 'mode' => 1,
'gsdevice' => $conf{'GSDEVICE'},
'gsname' => $conf{'GSNAME'},
'res' => $conf{'RESOLUTION'},
'paper' => $conf{'PAPERSIZE'},
'eof' => lc($conf{'SENDEOF'}),
'double' => lc($conf{'DOUBLEPAGE'}),
'gsopts' => $conf{'GSOPTS'},
'desc' => $conf{'GSNAME'} ? $conf{'GSNAME'} : $desc };
}
}
else {
# A driver of some kind, but not caldera's
return { 'mode' => 2,
'file' => $_[0],
'desc' => $_[0] };
}
}
# create_windows_driver(&printer, &driver)
sub create_windows_driver
{
return &create_webmin_windows_driver(@_);
}
# create_driver(&printer, &driver)
sub create_driver
{
if ($_[1]->{'mode'} == 0) {
return undef;
}
elsif ($_[1]->{'mode'} == 2) {
return $_[1]->{'file'};
}
else {
# Create or update the parameters file
local %conf;
&read_env_file("$driver_dir/$_[0]->{'name'}", \%conf);
$conf{'GSDEVICE'} = $_[1]->{'gsdevice'};
$conf{'GSNAME'} = $_[1]->{'gsname'};
$conf{'NAME'} = $_[0]->{'name'};
$conf{'RESOLUTION'} = $_[1]->{'res'};
$conf{'PAPERSIZE'} = $_[1]->{'paper'};
$conf{'DESC'} = $_[0]->{'desc'};
$conf{'SENDEOF'} = $_[1]->{'eof'};
$conf{'DOUBLEPAGE'} = $_[1]->{'double'};
$conf{'GSOPTS'} = $_[1]->{'gsopts'};
$conf{'UPP'} = $_[1]->{'upp'};
&write_env_file("$driver_dir/$_[0]->{'name'}", \%conf);
# Create the standard driver program
open(DRIVER, $base_driver);
local @lines = <DRIVER>;
close(DRIVER);
$lines[1] = "source $driver_dir/$_[0]->{'name'}\n";
mkdir("$config{'spool_dir'}/$_[0]->{'name'}", 0755);
local $drv = "$config{'spool_dir'}/$_[0]->{'name'}/printfilter";
open(DRV, ">$drv");
print DRV @lines;
close(DRV);
return $drv;
}
}
# delete_driver(name)
sub delete_driver
{
&delete_webmin_driver($_[0]);
unlink("$driver_dir/$_[0]");
}
# driver_input(&printer, &driver)
sub driver_input
{
local $mode = $_[0]->{'rhost'} ? 0 : $_[1]->{'mode'};
printf "<tr> <td><input type=radio name=mode value=0 %s> %s</td>\n",
$mode == 0 ? 'checked' : '', $text{'caldera_none'};
print "<td>($text{'caldera_nonemsg'})</td> </tr>\n";
printf "<tr> <td><input type=radio name=mode value=2 %s> %s</td>",
$mode == 2 ? 'checked' : '', $text{'caldera_prog'};
printf "<td><input name=program size=40 value='%s'></td> </tr>\n",
$mode == 2 ? $_[0]->{'iface'} : '';
# Normal driver options
printf "<tr> <td valign=top><input type=radio name=mode value=1 %s> %s</td>\n",
$mode == 1 ? 'checked' : '', $text{'caldera_coas'};
print "<td><table width=100%>\n";
print "<tr> <td valign=top><b>$text{'caldera_printer'}</b></td>\n";
print "<td colspan=3><select size=5 name=gsdevice onChange='setres(0)'>\n";
open(COAS, $config{'coas_printers'});
local $plist = &parse_coas(COAS);
close(COAS);
local ($i, $j, $p, $k, $found, $select_res);
foreach $p (values %$plist) {
if ($p->{'description'} eq $_[1]->{'gsname'} &&
$p->{'type'}->{'0'} ne $_[1]->{'gsdevice'}) {
# COAS has changed the device
$_[1]->{'gsname'} = undef;
}
}
foreach $k (sort { $a <=> $b } keys %$plist) {
$p = $plist->{$k};
next if ($p->{'type'}->{'0'} =~ /NET|RAW/);
local @thisres = values %{$p->{'resolution'}};
local $got = ($_[1]->{'gsname'} eq $p->{'description'} &&
$_[1]->{'gsdevice'} eq $p->{'type'}->{'0'}) ||
(!$_[1]->{'gsname'} && !$found &&
$_[1]->{'gsdevice'} eq $p->{'type'}->{'0'});
printf "<option %s value='%s'>%s\n",
$got ? 'selected' : '',
$p->{'description'}.";".join(";", @thisres),
$p->{'description'};
$found++ if ($got);
$select_res = &indexof($_[1]->{'res'}, @thisres) if ($got);
map { $gotres{$_}++ } @thisres;
}
print "</select><select name=res size=5>\n";
foreach $r (sort { $a <=> $b} keys %gotres) {
printf "<option %s>%s\n",
$_[1]->{'res'} eq $r ? 'selected' : '', $r;
}
print "</select></td> </tr>\n";
print "<tr> <td><b>$text{'caldera_eof'}</b></td>\n";
printf "<td><input type=radio name=eof value=true %s> $text{'yes'}\n",
$_[1]->{'eof'} eq 'true' ? 'checked' : '';
printf "<input type=radio name=eof value=false %s> $text{'no'}</td>\n",
$_[1]->{'eof'} eq 'true' ? '' : 'checked';
print "<td><b>$text{'caldera_paper'}</b></td> <td><select name=paper>\n";
foreach $p (sort { $a cmp $b } keys %paper_sizes) {
printf "<option value='%s' %s>%s\n",
$p, $_[1]->{'paper'} eq $p ? 'selected' : '',
$paper_sizes{$p};
}
print "</select></td> </tr>\n";
print "<tr> <td><b>$text{'caldera_double'}</b></td>\n";
printf "<td><input type=radio name=double value=true %s> $text{'yes'}\n",
$_[1]->{'double'} eq 'true' ? 'checked' : '';
printf "<input type=radio name=double value=false %s> $text{'no'}</td>\n",
$_[1]->{'double'} eq 'true' ? '' : 'checked';
print "<td><b>$text{'caldera_gsopts'}</b></td>\n";
printf "<td><input name=gsopts size=30 value='%s'></td> </tr>\n",
$_[1]->{'gsopts'};
print "</table></td></tr>\n";
# Uniprint driver options
printf "<tr> <td valign=top><input type=radio name=mode value=3 %s> %s</td>\n",
$mode == 3 ? 'checked' : '', $text{'caldera_uniprint'};
print "<td><table width=100%>\n";
print "<tr> <td valign=top><b>$text{'caldera_printer'}</b></td>\n";
print "<td colspan=3><select name=uniprint size=5>\n";
foreach $u (&list_uniprint()) {
printf "<option value=%s %s>%s\n",
$u->[0], $u->[0] eq $_[1]->{'upp'} ? 'selected' : '', $u->[1];
}
closedir(DIR);
print "</select></td> </tr>\n";
print "<tr> <td><b>$text{'caldera_eof'}</b></td>\n";
printf "<td><input type=radio name=ueof value=true %s> $text{'yes'}\n",
$_[1]->{'eof'} eq 'true' ? 'checked' : '';
printf "<input type=radio name=ueof value=false %s> $text{'no'}</td>\n",
$_[1]->{'eof'} eq 'true' ? '' : 'checked';
print "<td><b>$text{'caldera_paper'}</b></td> <td><select name=upaper>\n";
foreach $p (sort { $a cmp $b } keys %paper_sizes) {
printf "<option value='%s' %s>%s\n",
$p, $_[1]->{'paper'} eq $p ? 'selected' : '',
$paper_sizes{$p};
}
print "</select></td> </tr>\n";
print "<tr> <td><b>$text{'caldera_double'}</b></td>\n";
printf "<td><input type=radio name=udouble value=true %s> $text{'yes'}\n",
$_[1]->{'double'} eq 'true' ? 'checked' : '';
printf "<input type=radio name=udouble value=false %s> $text{'no'}</td>\n",
$_[1]->{'double'} eq 'true' ? '' : 'checked';
print "</table></td></tr>\n";
return <<EOF;
<script>
function setres(sel)
{
var idx = document.forms[0].gsdevice.selectedIndex;
var v = new String(document.forms[0].gsdevice.options[idx].value);
var vv = v.split(";");
var res = document.forms[0].res;
res.length = 0;
for(var i=1; i<vv.length; i++) {
res.options[i-1] = new Option(vv[i], vv[i]);
}
if (res.length > 0) {
res.options[sel].selected = true;
}
}
setres($select_res);
</script>
EOF
}
# parse_driver()
# Parse driver selection from %in and return a driver structure
sub parse_driver
{
if ($in{'mode'} == 0) {
return { 'mode' => 0 };
}
elsif ($in{'mode'} == 2) {
$in{'program'} =~ /^(\S+)/ && -x $1 ||
&error(&text('caldera_eprog', $in{'program'}));
return { 'mode' => 2,
'file' => $in{'program'} };
}
elsif ($in{'mode'} == 1) {
# Normal ghostscript driver
open(COAS, $config{'coas_printers'});
local $plist = &parse_coas(COAS);
close(COAS);
$in{'gsdevice'} || &error($text{'caldera_edriver'});
$in{'gsdevice'} =~ s/;(.*)$//;
local ($p, $gsdevice);
foreach $p (values %$plist) {
$gsdevice = $p->{'type'}->{'0'}
if ($p->{'description'} eq $in{'gsdevice'});
}
$gsdevice eq 'PostScript' || $in{'res'} ||
&error($text{'caldera_eres'});
return { 'mode' => 1,
'gsdevice' => $gsdevice,
'gsname' => $in{'gsdevice'},
'res' => $in{'res'},
'paper' => $in{'paper'},
'eof' => $in{'eof'},
'double' => $in{'double'},
'gsopts' => $in{'gsopts'} };
}
else {
# Uniprint ghostscript driver
$in{'uniprint'} || &error($text{'caldera_edriver'});
return { 'mode' => 3,
'gsdevice' => 'uniprint',
'upp' => $in{'uniprint'},
'paper' => $in{'upaper'},
'eof' => $in{'ueof'},
'double' => $in{'udouble'} };
}
}
# parse_coas(handle)
sub parse_coas
{
local $h = $_[0];
local (%rv, $_);
while(<$h>) {
s/#.*$//g;
s/\r|\n//g;
if (/^\s*(\S+)\s+{/) {
# start of a section
local $k = $1;
$rv{$k} = &parse_coas($h);
}
elsif (/^\s*}/) {
# end of a section
last;
}
elsif (/^\s*(\S+)\s+(.*)/) {
# a value in a section
$rv{$1} = $2;
}
}
return \%rv;
}
1;
| xtso520ok/webmin | lpadmin/old-caldera-driver.pl | Perl | bsd-3-clause | 9,911 |
# vim:ts=4:sw=4:expandtab
# © 2010-2012 Michael Stapelberg (see also: LICENSE)
use v5.14;
use utf8;
package RaumZeitChef 1.9.1;
# These modules are in core:
use File::Basename ();
# All these modules are not in core:
use AnyEvent;
use Moose;
use RaumZeitChef::IRC;
use RaumZeitChef::Config;
use RaumZeitChef::Log;
use RaumZeitChef::PluginFactory;
use RaumZeitChef::PluginSuperClass;
has config => (
is => 'ro',
isa => 'RaumZeitChef::Config',
required => 1,
handles => [qw/server port nick channel nickserv_password/],
);
# load base roles
# with("RaumZeitChef::$_") for qw/IRC HTTPD/;
sub run {
my ($self) = @_;
my $nick = $self->nick;
my $server = $self->server;
my $port = $self->port;
log_debug('configuration complete');
log_debug('instantiating IRC');
my $irc = RaumZeitChef::IRC->new(config => $self->config);
log_debug('building PluginFactory singleton');
my $factory = RaumZeitChef::PluginFactory->initialize(
config => $self->config,
irc => $irc,
);
$factory->build_plugins;
$irc->add_action($_)
for $factory->build_all_actions;
$irc->add_event($_)
for $factory->build_all_events;
log_info('Starting up');
while (1) {
# resolve hosts manually.
# For whatever reason, tcp_connect doesn't try to connect to all available hosts.
# since we wait for 5 seconds after a disconnection,
# connecting to a available host would take unnecessarily long.
my @hosts = _resolve_host($server, $port);
for my $host (@hosts) {
log_info("Connecting to $host as $nick...");
$irc->_client->connect($host, $port, { nick => $nick, user => $nick });
$irc->wait_for_disconnect;
}
# Wait 5 seconds before reconnecting, else we might get banned
log_info('Connection lost.');
sleep 5;
}
}
sub _resolve_host {
my ($host, $port) = @_;
my $resolve = AnyEvent->condvar;
my @hosts;
AnyEvent::Socket::resolve_sockaddr(
$host, $port, 'tcp', undef, undef, sub {
for (@_) {
my $sa = $_->[3];
my (undef, $ipn) = AnyEvent::Socket::unpack_sockaddr($sa);
push @hosts, AnyEvent::Socket::format_address($ipn);
}
$resolve->send;
}
);
$resolve->recv;
return @hosts;
}
1;
__END__
=head1 NAME
RaumZeitChef - RaumZeitChef IRC bot
=head1 DESCRIPTION
This module is an IRC bot (nickname RaumZeitChef)
=head1 VERSION
Version 1.9
=head1 AUTHOR
Michael Stapelberg, C<< <michael at stapelberg.de> >>
=head1 LICENSE AND COPYRIGHT
Copyright 2010-2012 Michael Stapelberg.
Copyright 201x Simon Elsbrock
Copyright 201x Maik Fischer
This program is free software; you can redistribute it and/or modify it
under the terms of the BSD license.
=cut
| raumzeitlabor/raumzeitchef-ircbot | lib/RaumZeitChef.pm | Perl | bsd-3-clause | 2,885 |
#!/usr/bin/env perl6
use v6;
sub get-slice(@list, $start, $end)
{
@list[$start - 1 ... $end - 1];
}
say get-slice(<a b c d e>, 2, 4);
=begin pod
=head1 NAME
P18 - Extract a slice from a list. Indices start at 1.
=end pod
# vim: ft=perl6
| Mitali-Sodhi/CodeLingo | Dataset/perl/P18-topo.pl | Perl | mit | 248 |
/*
Compile EBNF rules (==>) to BNF rules (=>).
- i.e. expanding out *, +, ?, 'or'
stephen.cresswell@tso.co.uk
*/
ebnf_to_bnf:-
retractall(_=>_),
remember(change),
rewrite_until_stable.
rewrite_until_stable:-
change,
!,
retractall(change),
rewrite_any,
rewrite_until_stable.
rewrite_until_stable.
rewrite_any:-
LHS==>RHS0,
rewrite(RHS0,RHS1),
remember(LHS=>RHS1),
fail.
rewrite_any.
*(A) ===> A_star :-
atom(A),
format(atom(A_star),"*~w",[A]),
remember(A_star=>[]),
remember(A_star=>[A,A_star]).
+(A) ===> A_plus :-
atom(A),
format(atom(A_plus),"+~w",[A]),
remember(A_plus==>[A,*(A)]). % Assert as EBNF - requires further wrangling
?(A) ===> A_qm :-
atom(A),
format(atom(A_qm),"?~w",[A]),
remember(A_qm=>[]),
remember(A_qm=>[A]).
A \ B ===> A_or_B :-
format(atom(A_or_B),"(~w or ~w)",[A,B]),
remember(A_or_B=>[A]),
remember(A_or_B=>[B]).
List ===> ListAtom :-
List = [_|_],
format(atom(ListAtom),"~w",[List]),
remember(ListAtom=>List).
OrExpr ===> ListAtom :-
OrExpr =.. [or|Args],
format(atom(ListAtom),"or(~w)",[Args]),
map_disjuncts(Args,ListAtom).
map_disjuncts([],_).
map_disjuncts([D|Ds],Head):-
remember(Head=>[D]),
map_disjuncts(Ds,Head).
% Apply rewrite rules starting from inside outwards
rewrite([],[]).
rewrite([T0|Ts0],[T2|Ts1]):-
\+(T0 = [_|_]),
T0 =.. [F|Args0],
!,
rewrite(Args0,Args1),
T1 =.. [F|Args1],
rewrite_if_poss(T1,T2),
rewrite(Ts0,Ts1).
rewrite([T0|Ts0],[T2|Ts1]):-
% A raw list (that is a sequence rather than an argument list)
T0 = [_|_],
rewrite(T0,T1),
rewrite_if_poss(T1,T2),
rewrite(Ts0,Ts1).
rewrite_if_poss(T0,T1):-
T0 ===> T1,
!.
rewrite_if_poss(T,T).
remember(X):-
call(X),
!.
remember(X):-
%write(X),nl,
assertz(change),
assertz(X).
% Do avoid duplication, but don't assert change
remember1(X):-
call(X),
!.
remember1(X):-
%write(X),nl,
assertz(X).
| OpenTriply/YASGUI.YASQE | lib/grammar/util/rewrite.pl | Perl | mit | 1,873 |
package Paws::RDS::ReservedDBInstancesOfferingMessage;
use Moose;
has Marker => (is => 'ro', isa => 'Str');
has ReservedDBInstancesOfferings => (is => 'ro', isa => 'ArrayRef[Paws::RDS::ReservedDBInstancesOffering]', request_name => 'ReservedDBInstancesOffering', traits => ['NameInRequest',]);
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::RDS::ReservedDBInstancesOfferingMessage
=head1 ATTRIBUTES
=head2 Marker => Str
An optional pagination token provided by a previous request. If this
parameter is specified, the response includes only records beyond the
marker, up to the value specified by C<MaxRecords>.
=head2 ReservedDBInstancesOfferings => ArrayRef[L<Paws::RDS::ReservedDBInstancesOffering>]
A list of reserved DB instance offerings.
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/RDS/ReservedDBInstancesOfferingMessage.pm | Perl | apache-2.0 | 858 |
#!/usr/bin/perl -w
use strict;
my ($arch, $patfile, $infile, $outfile, $libdir, $thread_arch) = @ARGV;
if (not $arch or not $patfile or not $infile or not $outfile or not $libdir) {
die "Usage: $0 arch thread_arch pattern-file in-file out-file libdir [ threadarch ]";
}
$thread_arch ||= '';
open IN, "<$infile"
or die "Can't open $infile: $!";
open OUT, ">$outfile"
or die "Can't open $outfile: $!";
open PATTERN, "<$patfile"
or die "Can't open $patfile: $!";
my @patterns = <PATTERN>;
chomp @patterns;
for my $p (@patterns) {
$p =~ s/%{_libdir}/$libdir/g;
$p =~ s/%{_arch}/$arch/g;
$p =~ s/%{thread_arch}/$thread_arch/g;
}
my %exclude = map { $_ => 1 } @patterns;
close PATTERN;
while(<IN>) {
chomp;
print OUT "$_\n"
unless exists $exclude{$_}
}
close IN;
close OUT;
| google/copr-sundry | third_party/subtrees/perl/clean-manifest.pl | Perl | apache-2.0 | 800 |
# 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 Lucy::Search::PolyCompiler;
use Lucy;
our $VERSION = '0.005000';
$VERSION = eval $VERSION;
1;
__END__
| rectang/lucy | perl/lib/Lucy/Search/PolyCompiler.pm | Perl | apache-2.0 | 896 |
package Paws::IAM::GetAccessKeyLastUsedResponse;
use Moose;
has AccessKeyLastUsed => (is => 'ro', isa => 'Paws::IAM::AccessKeyLastUsed');
has UserName => (is => 'ro', isa => 'Str');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::IAM::GetAccessKeyLastUsedResponse
=head1 ATTRIBUTES
=head2 AccessKeyLastUsed => L<Paws::IAM::AccessKeyLastUsed>
Contains information about the last time the access key was used.
=head2 UserName => Str
The name of the AWS IAM user that owns this access key.
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/IAM/GetAccessKeyLastUsedResponse.pm | Perl | apache-2.0 | 600 |
package #
Date::Manip::TZ::amjune00;
# 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 10:41:44 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.org/tz
use strict;
use warnings;
require 5.010000;
our (%Dates,%LastRule);
END {
undef %Dates;
undef %LastRule;
}
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
%Dates = (
1 =>
[
[ [1,1,2,0,0,0],[1,1,2,15,2,19],'+15:02:19',[15,2,19],
'LMT',0,[1867,10,17,8,57,40],[1867,10,17,23,59,59],
'0001010200:00:00','0001010215:02:19','1867101708:57:40','1867101723:59:59' ],
],
1867 =>
[
[ [1867,10,17,8,57,41],[1867,10,17,0,0,0],'-08:57:41',[-8,-57,-41],
'LMT',0,[1900,8,20,20,57,40],[1900,8,20,11,59,59],
'1867101708:57:41','1867101700:00:00','1900082020:57:40','1900082011:59:59' ],
],
1900 =>
[
[ [1900,8,20,20,57,41],[1900,8,20,12,57,41],'-08:00:00',[-8,0,0],
'PST',0,[1942,2,9,9,59,59],[1942,2,9,1,59,59],
'1900082020:57:41','1900082012:57:41','1942020909:59:59','1942020901:59:59' ],
],
1942 =>
[
[ [1942,2,9,10,0,0],[1942,2,9,3,0,0],'-07:00:00',[-7,0,0],
'PWT',1,[1945,8,14,22,59,59],[1945,8,14,15,59,59],
'1942020910:00:00','1942020903:00:00','1945081422:59:59','1945081415:59:59' ],
],
1945 =>
[
[ [1945,8,14,23,0,0],[1945,8,14,16,0,0],'-07:00:00',[-7,0,0],
'PPT',1,[1945,9,30,8,59,59],[1945,9,30,1,59,59],
'1945081423:00:00','1945081416:00:00','1945093008:59:59','1945093001:59:59' ],
[ [1945,9,30,9,0,0],[1945,9,30,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1969,4,27,9,59,59],[1969,4,27,1,59,59],
'1945093009:00:00','1945093001:00:00','1969042709:59:59','1969042701:59:59' ],
],
1969 =>
[
[ [1969,4,27,10,0,0],[1969,4,27,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1969,10,26,8,59,59],[1969,10,26,1,59,59],
'1969042710:00:00','1969042703:00:00','1969102608:59:59','1969102601:59:59' ],
[ [1969,10,26,9,0,0],[1969,10,26,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1970,4,26,9,59,59],[1970,4,26,1,59,59],
'1969102609:00:00','1969102601:00:00','1970042609:59:59','1970042601:59:59' ],
],
1970 =>
[
[ [1970,4,26,10,0,0],[1970,4,26,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1970,10,25,8,59,59],[1970,10,25,1,59,59],
'1970042610:00:00','1970042603:00:00','1970102508:59:59','1970102501:59:59' ],
[ [1970,10,25,9,0,0],[1970,10,25,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1971,4,25,9,59,59],[1971,4,25,1,59,59],
'1970102509:00:00','1970102501:00:00','1971042509:59:59','1971042501:59:59' ],
],
1971 =>
[
[ [1971,4,25,10,0,0],[1971,4,25,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1971,10,31,8,59,59],[1971,10,31,1,59,59],
'1971042510:00:00','1971042503:00:00','1971103108:59:59','1971103101:59:59' ],
[ [1971,10,31,9,0,0],[1971,10,31,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1972,4,30,9,59,59],[1972,4,30,1,59,59],
'1971103109:00:00','1971103101:00:00','1972043009:59:59','1972043001:59:59' ],
],
1972 =>
[
[ [1972,4,30,10,0,0],[1972,4,30,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1972,10,29,8,59,59],[1972,10,29,1,59,59],
'1972043010:00:00','1972043003:00:00','1972102908:59:59','1972102901:59:59' ],
[ [1972,10,29,9,0,0],[1972,10,29,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1973,4,29,9,59,59],[1973,4,29,1,59,59],
'1972102909:00:00','1972102901:00:00','1973042909:59:59','1973042901:59:59' ],
],
1973 =>
[
[ [1973,4,29,10,0,0],[1973,4,29,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1973,10,28,8,59,59],[1973,10,28,1,59,59],
'1973042910:00:00','1973042903:00:00','1973102808:59:59','1973102801:59:59' ],
[ [1973,10,28,9,0,0],[1973,10,28,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1974,1,6,9,59,59],[1974,1,6,1,59,59],
'1973102809:00:00','1973102801:00:00','1974010609:59:59','1974010601:59:59' ],
],
1974 =>
[
[ [1974,1,6,10,0,0],[1974,1,6,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1974,10,27,8,59,59],[1974,10,27,1,59,59],
'1974010610:00:00','1974010603:00:00','1974102708:59:59','1974102701:59:59' ],
[ [1974,10,27,9,0,0],[1974,10,27,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1975,2,23,9,59,59],[1975,2,23,1,59,59],
'1974102709:00:00','1974102701:00:00','1975022309:59:59','1975022301:59:59' ],
],
1975 =>
[
[ [1975,2,23,10,0,0],[1975,2,23,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1975,10,26,8,59,59],[1975,10,26,1,59,59],
'1975022310:00:00','1975022303:00:00','1975102608:59:59','1975102601:59:59' ],
[ [1975,10,26,9,0,0],[1975,10,26,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1976,4,25,9,59,59],[1976,4,25,1,59,59],
'1975102609:00:00','1975102601:00:00','1976042509:59:59','1976042501:59:59' ],
],
1976 =>
[
[ [1976,4,25,10,0,0],[1976,4,25,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1976,10,31,8,59,59],[1976,10,31,1,59,59],
'1976042510:00:00','1976042503:00:00','1976103108:59:59','1976103101:59:59' ],
[ [1976,10,31,9,0,0],[1976,10,31,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1977,4,24,9,59,59],[1977,4,24,1,59,59],
'1976103109:00:00','1976103101:00:00','1977042409:59:59','1977042401:59:59' ],
],
1977 =>
[
[ [1977,4,24,10,0,0],[1977,4,24,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1977,10,30,8,59,59],[1977,10,30,1,59,59],
'1977042410:00:00','1977042403:00:00','1977103008:59:59','1977103001:59:59' ],
[ [1977,10,30,9,0,0],[1977,10,30,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1978,4,30,9,59,59],[1978,4,30,1,59,59],
'1977103009:00:00','1977103001:00:00','1978043009:59:59','1978043001:59:59' ],
],
1978 =>
[
[ [1978,4,30,10,0,0],[1978,4,30,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1978,10,29,8,59,59],[1978,10,29,1,59,59],
'1978043010:00:00','1978043003:00:00','1978102908:59:59','1978102901:59:59' ],
[ [1978,10,29,9,0,0],[1978,10,29,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1979,4,29,9,59,59],[1979,4,29,1,59,59],
'1978102909:00:00','1978102901:00:00','1979042909:59:59','1979042901:59:59' ],
],
1979 =>
[
[ [1979,4,29,10,0,0],[1979,4,29,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1979,10,28,8,59,59],[1979,10,28,1,59,59],
'1979042910:00:00','1979042903:00:00','1979102808:59:59','1979102801:59:59' ],
[ [1979,10,28,9,0,0],[1979,10,28,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1980,4,27,9,59,59],[1980,4,27,1,59,59],
'1979102809:00:00','1979102801:00:00','1980042709:59:59','1980042701:59:59' ],
],
1980 =>
[
[ [1980,4,27,10,0,0],[1980,4,27,2,0,0],'-08:00:00',[-8,0,0],
'YDT',1,[1980,10,26,9,59,59],[1980,10,26,1,59,59],
'1980042710:00:00','1980042702:00:00','1980102609:59:59','1980102601:59:59' ],
[ [1980,10,26,10,0,0],[1980,10,26,2,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1981,4,26,9,59,59],[1981,4,26,1,59,59],
'1980102610:00:00','1980102602:00:00','1981042609:59:59','1981042601:59:59' ],
],
1981 =>
[
[ [1981,4,26,10,0,0],[1981,4,26,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1981,10,25,8,59,59],[1981,10,25,1,59,59],
'1981042610:00:00','1981042603:00:00','1981102508:59:59','1981102501:59:59' ],
[ [1981,10,25,9,0,0],[1981,10,25,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1982,4,25,9,59,59],[1982,4,25,1,59,59],
'1981102509:00:00','1981102501:00:00','1982042509:59:59','1982042501:59:59' ],
],
1982 =>
[
[ [1982,4,25,10,0,0],[1982,4,25,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1982,10,31,8,59,59],[1982,10,31,1,59,59],
'1982042510:00:00','1982042503:00:00','1982103108:59:59','1982103101:59:59' ],
[ [1982,10,31,9,0,0],[1982,10,31,1,0,0],'-08:00:00',[-8,0,0],
'PST',0,[1983,4,24,9,59,59],[1983,4,24,1,59,59],
'1982103109:00:00','1982103101:00:00','1983042409:59:59','1983042401:59:59' ],
],
1983 =>
[
[ [1983,4,24,10,0,0],[1983,4,24,3,0,0],'-07:00:00',[-7,0,0],
'PDT',1,[1983,10,30,8,59,59],[1983,10,30,1,59,59],
'1983042410:00:00','1983042403:00:00','1983103008:59:59','1983103001:59:59' ],
[ [1983,10,30,9,0,0],[1983,10,30,0,0,0],'-09:00:00',[-9,0,0],
'YST',0,[1983,11,30,8,59,59],[1983,11,29,23,59,59],
'1983103009:00:00','1983103000:00:00','1983113008:59:59','1983112923:59:59' ],
[ [1983,11,30,9,0,0],[1983,11,30,0,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1984,4,29,10,59,59],[1984,4,29,1,59,59],
'1983113009:00:00','1983113000:00:00','1984042910:59:59','1984042901:59:59' ],
],
1984 =>
[
[ [1984,4,29,11,0,0],[1984,4,29,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1984,10,28,9,59,59],[1984,10,28,1,59,59],
'1984042911:00:00','1984042903:00:00','1984102809:59:59','1984102801:59:59' ],
[ [1984,10,28,10,0,0],[1984,10,28,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1985,4,28,10,59,59],[1985,4,28,1,59,59],
'1984102810:00:00','1984102801:00:00','1985042810:59:59','1985042801:59:59' ],
],
1985 =>
[
[ [1985,4,28,11,0,0],[1985,4,28,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1985,10,27,9,59,59],[1985,10,27,1,59,59],
'1985042811:00:00','1985042803:00:00','1985102709:59:59','1985102701:59:59' ],
[ [1985,10,27,10,0,0],[1985,10,27,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1986,4,27,10,59,59],[1986,4,27,1,59,59],
'1985102710:00:00','1985102701:00:00','1986042710:59:59','1986042701:59:59' ],
],
1986 =>
[
[ [1986,4,27,11,0,0],[1986,4,27,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1986,10,26,9,59,59],[1986,10,26,1,59,59],
'1986042711:00:00','1986042703:00:00','1986102609:59:59','1986102601:59:59' ],
[ [1986,10,26,10,0,0],[1986,10,26,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1987,4,5,10,59,59],[1987,4,5,1,59,59],
'1986102610:00:00','1986102601:00:00','1987040510:59:59','1987040501:59:59' ],
],
1987 =>
[
[ [1987,4,5,11,0,0],[1987,4,5,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1987,10,25,9,59,59],[1987,10,25,1,59,59],
'1987040511:00:00','1987040503:00:00','1987102509:59:59','1987102501:59:59' ],
[ [1987,10,25,10,0,0],[1987,10,25,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1988,4,3,10,59,59],[1988,4,3,1,59,59],
'1987102510:00:00','1987102501:00:00','1988040310:59:59','1988040301:59:59' ],
],
1988 =>
[
[ [1988,4,3,11,0,0],[1988,4,3,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1988,10,30,9,59,59],[1988,10,30,1,59,59],
'1988040311:00:00','1988040303:00:00','1988103009:59:59','1988103001:59:59' ],
[ [1988,10,30,10,0,0],[1988,10,30,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1989,4,2,10,59,59],[1989,4,2,1,59,59],
'1988103010:00:00','1988103001:00:00','1989040210:59:59','1989040201:59:59' ],
],
1989 =>
[
[ [1989,4,2,11,0,0],[1989,4,2,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1989,10,29,9,59,59],[1989,10,29,1,59,59],
'1989040211:00:00','1989040203:00:00','1989102909:59:59','1989102901:59:59' ],
[ [1989,10,29,10,0,0],[1989,10,29,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1990,4,1,10,59,59],[1990,4,1,1,59,59],
'1989102910:00:00','1989102901:00:00','1990040110:59:59','1990040101:59:59' ],
],
1990 =>
[
[ [1990,4,1,11,0,0],[1990,4,1,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1990,10,28,9,59,59],[1990,10,28,1,59,59],
'1990040111:00:00','1990040103:00:00','1990102809:59:59','1990102801:59:59' ],
[ [1990,10,28,10,0,0],[1990,10,28,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1991,4,7,10,59,59],[1991,4,7,1,59,59],
'1990102810:00:00','1990102801:00:00','1991040710:59:59','1991040701:59:59' ],
],
1991 =>
[
[ [1991,4,7,11,0,0],[1991,4,7,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1991,10,27,9,59,59],[1991,10,27,1,59,59],
'1991040711:00:00','1991040703:00:00','1991102709:59:59','1991102701:59:59' ],
[ [1991,10,27,10,0,0],[1991,10,27,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1992,4,5,10,59,59],[1992,4,5,1,59,59],
'1991102710:00:00','1991102701:00:00','1992040510:59:59','1992040501:59:59' ],
],
1992 =>
[
[ [1992,4,5,11,0,0],[1992,4,5,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1992,10,25,9,59,59],[1992,10,25,1,59,59],
'1992040511:00:00','1992040503:00:00','1992102509:59:59','1992102501:59:59' ],
[ [1992,10,25,10,0,0],[1992,10,25,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1993,4,4,10,59,59],[1993,4,4,1,59,59],
'1992102510:00:00','1992102501:00:00','1993040410:59:59','1993040401:59:59' ],
],
1993 =>
[
[ [1993,4,4,11,0,0],[1993,4,4,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1993,10,31,9,59,59],[1993,10,31,1,59,59],
'1993040411:00:00','1993040403:00:00','1993103109:59:59','1993103101:59:59' ],
[ [1993,10,31,10,0,0],[1993,10,31,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1994,4,3,10,59,59],[1994,4,3,1,59,59],
'1993103110:00:00','1993103101:00:00','1994040310:59:59','1994040301:59:59' ],
],
1994 =>
[
[ [1994,4,3,11,0,0],[1994,4,3,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1994,10,30,9,59,59],[1994,10,30,1,59,59],
'1994040311:00:00','1994040303:00:00','1994103009:59:59','1994103001:59:59' ],
[ [1994,10,30,10,0,0],[1994,10,30,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1995,4,2,10,59,59],[1995,4,2,1,59,59],
'1994103010:00:00','1994103001:00:00','1995040210:59:59','1995040201:59:59' ],
],
1995 =>
[
[ [1995,4,2,11,0,0],[1995,4,2,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1995,10,29,9,59,59],[1995,10,29,1,59,59],
'1995040211:00:00','1995040203:00:00','1995102909:59:59','1995102901:59:59' ],
[ [1995,10,29,10,0,0],[1995,10,29,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1996,4,7,10,59,59],[1996,4,7,1,59,59],
'1995102910:00:00','1995102901:00:00','1996040710:59:59','1996040701:59:59' ],
],
1996 =>
[
[ [1996,4,7,11,0,0],[1996,4,7,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1996,10,27,9,59,59],[1996,10,27,1,59,59],
'1996040711:00:00','1996040703:00:00','1996102709:59:59','1996102701:59:59' ],
[ [1996,10,27,10,0,0],[1996,10,27,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1997,4,6,10,59,59],[1997,4,6,1,59,59],
'1996102710:00:00','1996102701:00:00','1997040610:59:59','1997040601:59:59' ],
],
1997 =>
[
[ [1997,4,6,11,0,0],[1997,4,6,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1997,10,26,9,59,59],[1997,10,26,1,59,59],
'1997040611:00:00','1997040603:00:00','1997102609:59:59','1997102601:59:59' ],
[ [1997,10,26,10,0,0],[1997,10,26,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1998,4,5,10,59,59],[1998,4,5,1,59,59],
'1997102610:00:00','1997102601:00:00','1998040510:59:59','1998040501:59:59' ],
],
1998 =>
[
[ [1998,4,5,11,0,0],[1998,4,5,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1998,10,25,9,59,59],[1998,10,25,1,59,59],
'1998040511:00:00','1998040503:00:00','1998102509:59:59','1998102501:59:59' ],
[ [1998,10,25,10,0,0],[1998,10,25,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[1999,4,4,10,59,59],[1999,4,4,1,59,59],
'1998102510:00:00','1998102501:00:00','1999040410:59:59','1999040401:59:59' ],
],
1999 =>
[
[ [1999,4,4,11,0,0],[1999,4,4,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[1999,10,31,9,59,59],[1999,10,31,1,59,59],
'1999040411:00:00','1999040403:00:00','1999103109:59:59','1999103101:59:59' ],
[ [1999,10,31,10,0,0],[1999,10,31,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2000,4,2,10,59,59],[2000,4,2,1,59,59],
'1999103110:00:00','1999103101:00:00','2000040210:59:59','2000040201:59:59' ],
],
2000 =>
[
[ [2000,4,2,11,0,0],[2000,4,2,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2000,10,29,9,59,59],[2000,10,29,1,59,59],
'2000040211:00:00','2000040203:00:00','2000102909:59:59','2000102901:59:59' ],
[ [2000,10,29,10,0,0],[2000,10,29,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2001,4,1,10,59,59],[2001,4,1,1,59,59],
'2000102910:00:00','2000102901:00:00','2001040110:59:59','2001040101:59:59' ],
],
2001 =>
[
[ [2001,4,1,11,0,0],[2001,4,1,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2001,10,28,9,59,59],[2001,10,28,1,59,59],
'2001040111:00:00','2001040103:00:00','2001102809:59:59','2001102801:59:59' ],
[ [2001,10,28,10,0,0],[2001,10,28,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2002,4,7,10,59,59],[2002,4,7,1,59,59],
'2001102810:00:00','2001102801:00:00','2002040710:59:59','2002040701:59:59' ],
],
2002 =>
[
[ [2002,4,7,11,0,0],[2002,4,7,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2002,10,27,9,59,59],[2002,10,27,1,59,59],
'2002040711:00:00','2002040703:00:00','2002102709:59:59','2002102701:59:59' ],
[ [2002,10,27,10,0,0],[2002,10,27,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2003,4,6,10,59,59],[2003,4,6,1,59,59],
'2002102710:00:00','2002102701:00:00','2003040610:59:59','2003040601:59:59' ],
],
2003 =>
[
[ [2003,4,6,11,0,0],[2003,4,6,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2003,10,26,9,59,59],[2003,10,26,1,59,59],
'2003040611:00:00','2003040603:00:00','2003102609:59:59','2003102601:59:59' ],
[ [2003,10,26,10,0,0],[2003,10,26,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2004,4,4,10,59,59],[2004,4,4,1,59,59],
'2003102610:00:00','2003102601:00:00','2004040410:59:59','2004040401:59:59' ],
],
2004 =>
[
[ [2004,4,4,11,0,0],[2004,4,4,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2004,10,31,9,59,59],[2004,10,31,1,59,59],
'2004040411:00:00','2004040403:00:00','2004103109:59:59','2004103101:59:59' ],
[ [2004,10,31,10,0,0],[2004,10,31,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2005,4,3,10,59,59],[2005,4,3,1,59,59],
'2004103110:00:00','2004103101:00:00','2005040310:59:59','2005040301:59:59' ],
],
2005 =>
[
[ [2005,4,3,11,0,0],[2005,4,3,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2005,10,30,9,59,59],[2005,10,30,1,59,59],
'2005040311:00:00','2005040303:00:00','2005103009:59:59','2005103001:59:59' ],
[ [2005,10,30,10,0,0],[2005,10,30,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2006,4,2,10,59,59],[2006,4,2,1,59,59],
'2005103010:00:00','2005103001:00:00','2006040210:59:59','2006040201:59:59' ],
],
2006 =>
[
[ [2006,4,2,11,0,0],[2006,4,2,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2006,10,29,9,59,59],[2006,10,29,1,59,59],
'2006040211:00:00','2006040203:00:00','2006102909:59:59','2006102901:59:59' ],
[ [2006,10,29,10,0,0],[2006,10,29,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2007,3,11,10,59,59],[2007,3,11,1,59,59],
'2006102910:00:00','2006102901:00:00','2007031110:59:59','2007031101:59:59' ],
],
2007 =>
[
[ [2007,3,11,11,0,0],[2007,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2007,11,4,9,59,59],[2007,11,4,1,59,59],
'2007031111:00:00','2007031103:00:00','2007110409:59:59','2007110401:59:59' ],
[ [2007,11,4,10,0,0],[2007,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2008,3,9,10,59,59],[2008,3,9,1,59,59],
'2007110410:00:00','2007110401:00:00','2008030910:59:59','2008030901:59:59' ],
],
2008 =>
[
[ [2008,3,9,11,0,0],[2008,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2008,11,2,9,59,59],[2008,11,2,1,59,59],
'2008030911:00:00','2008030903:00:00','2008110209:59:59','2008110201:59:59' ],
[ [2008,11,2,10,0,0],[2008,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2009,3,8,10,59,59],[2009,3,8,1,59,59],
'2008110210:00:00','2008110201:00:00','2009030810:59:59','2009030801:59:59' ],
],
2009 =>
[
[ [2009,3,8,11,0,0],[2009,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2009,11,1,9,59,59],[2009,11,1,1,59,59],
'2009030811:00:00','2009030803:00:00','2009110109:59:59','2009110101:59:59' ],
[ [2009,11,1,10,0,0],[2009,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2010,3,14,10,59,59],[2010,3,14,1,59,59],
'2009110110:00:00','2009110101:00:00','2010031410:59:59','2010031401:59:59' ],
],
2010 =>
[
[ [2010,3,14,11,0,0],[2010,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2010,11,7,9,59,59],[2010,11,7,1,59,59],
'2010031411:00:00','2010031403:00:00','2010110709:59:59','2010110701:59:59' ],
[ [2010,11,7,10,0,0],[2010,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2011,3,13,10,59,59],[2011,3,13,1,59,59],
'2010110710:00:00','2010110701:00:00','2011031310:59:59','2011031301:59:59' ],
],
2011 =>
[
[ [2011,3,13,11,0,0],[2011,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2011,11,6,9,59,59],[2011,11,6,1,59,59],
'2011031311:00:00','2011031303:00:00','2011110609:59:59','2011110601:59:59' ],
[ [2011,11,6,10,0,0],[2011,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2012,3,11,10,59,59],[2012,3,11,1,59,59],
'2011110610:00:00','2011110601:00:00','2012031110:59:59','2012031101:59:59' ],
],
2012 =>
[
[ [2012,3,11,11,0,0],[2012,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2012,11,4,9,59,59],[2012,11,4,1,59,59],
'2012031111:00:00','2012031103:00:00','2012110409:59:59','2012110401:59:59' ],
[ [2012,11,4,10,0,0],[2012,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2013,3,10,10,59,59],[2013,3,10,1,59,59],
'2012110410:00:00','2012110401:00:00','2013031010:59:59','2013031001:59:59' ],
],
2013 =>
[
[ [2013,3,10,11,0,0],[2013,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2013,11,3,9,59,59],[2013,11,3,1,59,59],
'2013031011:00:00','2013031003:00:00','2013110309:59:59','2013110301:59:59' ],
[ [2013,11,3,10,0,0],[2013,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2014,3,9,10,59,59],[2014,3,9,1,59,59],
'2013110310:00:00','2013110301:00:00','2014030910:59:59','2014030901:59:59' ],
],
2014 =>
[
[ [2014,3,9,11,0,0],[2014,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2014,11,2,9,59,59],[2014,11,2,1,59,59],
'2014030911:00:00','2014030903:00:00','2014110209:59:59','2014110201:59:59' ],
[ [2014,11,2,10,0,0],[2014,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2015,3,8,10,59,59],[2015,3,8,1,59,59],
'2014110210:00:00','2014110201:00:00','2015030810:59:59','2015030801:59:59' ],
],
2015 =>
[
[ [2015,3,8,11,0,0],[2015,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2015,11,1,9,59,59],[2015,11,1,1,59,59],
'2015030811:00:00','2015030803:00:00','2015110109:59:59','2015110101:59:59' ],
[ [2015,11,1,10,0,0],[2015,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2016,3,13,10,59,59],[2016,3,13,1,59,59],
'2015110110:00:00','2015110101:00:00','2016031310:59:59','2016031301:59:59' ],
],
2016 =>
[
[ [2016,3,13,11,0,0],[2016,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2016,11,6,9,59,59],[2016,11,6,1,59,59],
'2016031311:00:00','2016031303:00:00','2016110609:59:59','2016110601:59:59' ],
[ [2016,11,6,10,0,0],[2016,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2017,3,12,10,59,59],[2017,3,12,1,59,59],
'2016110610:00:00','2016110601:00:00','2017031210:59:59','2017031201:59:59' ],
],
2017 =>
[
[ [2017,3,12,11,0,0],[2017,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2017,11,5,9,59,59],[2017,11,5,1,59,59],
'2017031211:00:00','2017031203:00:00','2017110509:59:59','2017110501:59:59' ],
[ [2017,11,5,10,0,0],[2017,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2018,3,11,10,59,59],[2018,3,11,1,59,59],
'2017110510:00:00','2017110501:00:00','2018031110:59:59','2018031101:59:59' ],
],
2018 =>
[
[ [2018,3,11,11,0,0],[2018,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2018,11,4,9,59,59],[2018,11,4,1,59,59],
'2018031111:00:00','2018031103:00:00','2018110409:59:59','2018110401:59:59' ],
[ [2018,11,4,10,0,0],[2018,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2019,3,10,10,59,59],[2019,3,10,1,59,59],
'2018110410:00:00','2018110401:00:00','2019031010:59:59','2019031001:59:59' ],
],
2019 =>
[
[ [2019,3,10,11,0,0],[2019,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2019,11,3,9,59,59],[2019,11,3,1,59,59],
'2019031011:00:00','2019031003:00:00','2019110309:59:59','2019110301:59:59' ],
[ [2019,11,3,10,0,0],[2019,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2020,3,8,10,59,59],[2020,3,8,1,59,59],
'2019110310:00:00','2019110301:00:00','2020030810:59:59','2020030801:59:59' ],
],
2020 =>
[
[ [2020,3,8,11,0,0],[2020,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2020,11,1,9,59,59],[2020,11,1,1,59,59],
'2020030811:00:00','2020030803:00:00','2020110109:59:59','2020110101:59:59' ],
[ [2020,11,1,10,0,0],[2020,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2021,3,14,10,59,59],[2021,3,14,1,59,59],
'2020110110:00:00','2020110101:00:00','2021031410:59:59','2021031401:59:59' ],
],
2021 =>
[
[ [2021,3,14,11,0,0],[2021,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2021,11,7,9,59,59],[2021,11,7,1,59,59],
'2021031411:00:00','2021031403:00:00','2021110709:59:59','2021110701:59:59' ],
[ [2021,11,7,10,0,0],[2021,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2022,3,13,10,59,59],[2022,3,13,1,59,59],
'2021110710:00:00','2021110701:00:00','2022031310:59:59','2022031301:59:59' ],
],
2022 =>
[
[ [2022,3,13,11,0,0],[2022,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2022,11,6,9,59,59],[2022,11,6,1,59,59],
'2022031311:00:00','2022031303:00:00','2022110609:59:59','2022110601:59:59' ],
[ [2022,11,6,10,0,0],[2022,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2023,3,12,10,59,59],[2023,3,12,1,59,59],
'2022110610:00:00','2022110601:00:00','2023031210:59:59','2023031201:59:59' ],
],
2023 =>
[
[ [2023,3,12,11,0,0],[2023,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2023,11,5,9,59,59],[2023,11,5,1,59,59],
'2023031211:00:00','2023031203:00:00','2023110509:59:59','2023110501:59:59' ],
[ [2023,11,5,10,0,0],[2023,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2024,3,10,10,59,59],[2024,3,10,1,59,59],
'2023110510:00:00','2023110501:00:00','2024031010:59:59','2024031001:59:59' ],
],
2024 =>
[
[ [2024,3,10,11,0,0],[2024,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2024,11,3,9,59,59],[2024,11,3,1,59,59],
'2024031011:00:00','2024031003:00:00','2024110309:59:59','2024110301:59:59' ],
[ [2024,11,3,10,0,0],[2024,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2025,3,9,10,59,59],[2025,3,9,1,59,59],
'2024110310:00:00','2024110301:00:00','2025030910:59:59','2025030901:59:59' ],
],
2025 =>
[
[ [2025,3,9,11,0,0],[2025,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2025,11,2,9,59,59],[2025,11,2,1,59,59],
'2025030911:00:00','2025030903:00:00','2025110209:59:59','2025110201:59:59' ],
[ [2025,11,2,10,0,0],[2025,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2026,3,8,10,59,59],[2026,3,8,1,59,59],
'2025110210:00:00','2025110201:00:00','2026030810:59:59','2026030801:59:59' ],
],
2026 =>
[
[ [2026,3,8,11,0,0],[2026,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2026,11,1,9,59,59],[2026,11,1,1,59,59],
'2026030811:00:00','2026030803:00:00','2026110109:59:59','2026110101:59:59' ],
[ [2026,11,1,10,0,0],[2026,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2027,3,14,10,59,59],[2027,3,14,1,59,59],
'2026110110:00:00','2026110101:00:00','2027031410:59:59','2027031401:59:59' ],
],
2027 =>
[
[ [2027,3,14,11,0,0],[2027,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2027,11,7,9,59,59],[2027,11,7,1,59,59],
'2027031411:00:00','2027031403:00:00','2027110709:59:59','2027110701:59:59' ],
[ [2027,11,7,10,0,0],[2027,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2028,3,12,10,59,59],[2028,3,12,1,59,59],
'2027110710:00:00','2027110701:00:00','2028031210:59:59','2028031201:59:59' ],
],
2028 =>
[
[ [2028,3,12,11,0,0],[2028,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2028,11,5,9,59,59],[2028,11,5,1,59,59],
'2028031211:00:00','2028031203:00:00','2028110509:59:59','2028110501:59:59' ],
[ [2028,11,5,10,0,0],[2028,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2029,3,11,10,59,59],[2029,3,11,1,59,59],
'2028110510:00:00','2028110501:00:00','2029031110:59:59','2029031101:59:59' ],
],
2029 =>
[
[ [2029,3,11,11,0,0],[2029,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2029,11,4,9,59,59],[2029,11,4,1,59,59],
'2029031111:00:00','2029031103:00:00','2029110409:59:59','2029110401:59:59' ],
[ [2029,11,4,10,0,0],[2029,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2030,3,10,10,59,59],[2030,3,10,1,59,59],
'2029110410:00:00','2029110401:00:00','2030031010:59:59','2030031001:59:59' ],
],
2030 =>
[
[ [2030,3,10,11,0,0],[2030,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2030,11,3,9,59,59],[2030,11,3,1,59,59],
'2030031011:00:00','2030031003:00:00','2030110309:59:59','2030110301:59:59' ],
[ [2030,11,3,10,0,0],[2030,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2031,3,9,10,59,59],[2031,3,9,1,59,59],
'2030110310:00:00','2030110301:00:00','2031030910:59:59','2031030901:59:59' ],
],
2031 =>
[
[ [2031,3,9,11,0,0],[2031,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2031,11,2,9,59,59],[2031,11,2,1,59,59],
'2031030911:00:00','2031030903:00:00','2031110209:59:59','2031110201:59:59' ],
[ [2031,11,2,10,0,0],[2031,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2032,3,14,10,59,59],[2032,3,14,1,59,59],
'2031110210:00:00','2031110201:00:00','2032031410:59:59','2032031401:59:59' ],
],
2032 =>
[
[ [2032,3,14,11,0,0],[2032,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2032,11,7,9,59,59],[2032,11,7,1,59,59],
'2032031411:00:00','2032031403:00:00','2032110709:59:59','2032110701:59:59' ],
[ [2032,11,7,10,0,0],[2032,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2033,3,13,10,59,59],[2033,3,13,1,59,59],
'2032110710:00:00','2032110701:00:00','2033031310:59:59','2033031301:59:59' ],
],
2033 =>
[
[ [2033,3,13,11,0,0],[2033,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2033,11,6,9,59,59],[2033,11,6,1,59,59],
'2033031311:00:00','2033031303:00:00','2033110609:59:59','2033110601:59:59' ],
[ [2033,11,6,10,0,0],[2033,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2034,3,12,10,59,59],[2034,3,12,1,59,59],
'2033110610:00:00','2033110601:00:00','2034031210:59:59','2034031201:59:59' ],
],
2034 =>
[
[ [2034,3,12,11,0,0],[2034,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2034,11,5,9,59,59],[2034,11,5,1,59,59],
'2034031211:00:00','2034031203:00:00','2034110509:59:59','2034110501:59:59' ],
[ [2034,11,5,10,0,0],[2034,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2035,3,11,10,59,59],[2035,3,11,1,59,59],
'2034110510:00:00','2034110501:00:00','2035031110:59:59','2035031101:59:59' ],
],
2035 =>
[
[ [2035,3,11,11,0,0],[2035,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2035,11,4,9,59,59],[2035,11,4,1,59,59],
'2035031111:00:00','2035031103:00:00','2035110409:59:59','2035110401:59:59' ],
[ [2035,11,4,10,0,0],[2035,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2036,3,9,10,59,59],[2036,3,9,1,59,59],
'2035110410:00:00','2035110401:00:00','2036030910:59:59','2036030901:59:59' ],
],
2036 =>
[
[ [2036,3,9,11,0,0],[2036,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2036,11,2,9,59,59],[2036,11,2,1,59,59],
'2036030911:00:00','2036030903:00:00','2036110209:59:59','2036110201:59:59' ],
[ [2036,11,2,10,0,0],[2036,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2037,3,8,10,59,59],[2037,3,8,1,59,59],
'2036110210:00:00','2036110201:00:00','2037030810:59:59','2037030801:59:59' ],
],
2037 =>
[
[ [2037,3,8,11,0,0],[2037,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2037,11,1,9,59,59],[2037,11,1,1,59,59],
'2037030811:00:00','2037030803:00:00','2037110109:59:59','2037110101:59:59' ],
[ [2037,11,1,10,0,0],[2037,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2038,3,14,10,59,59],[2038,3,14,1,59,59],
'2037110110:00:00','2037110101:00:00','2038031410:59:59','2038031401:59:59' ],
],
2038 =>
[
[ [2038,3,14,11,0,0],[2038,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2038,11,7,9,59,59],[2038,11,7,1,59,59],
'2038031411:00:00','2038031403:00:00','2038110709:59:59','2038110701:59:59' ],
[ [2038,11,7,10,0,0],[2038,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2039,3,13,10,59,59],[2039,3,13,1,59,59],
'2038110710:00:00','2038110701:00:00','2039031310:59:59','2039031301:59:59' ],
],
2039 =>
[
[ [2039,3,13,11,0,0],[2039,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2039,11,6,9,59,59],[2039,11,6,1,59,59],
'2039031311:00:00','2039031303:00:00','2039110609:59:59','2039110601:59:59' ],
[ [2039,11,6,10,0,0],[2039,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2040,3,11,10,59,59],[2040,3,11,1,59,59],
'2039110610:00:00','2039110601:00:00','2040031110:59:59','2040031101:59:59' ],
],
2040 =>
[
[ [2040,3,11,11,0,0],[2040,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2040,11,4,9,59,59],[2040,11,4,1,59,59],
'2040031111:00:00','2040031103:00:00','2040110409:59:59','2040110401:59:59' ],
[ [2040,11,4,10,0,0],[2040,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2041,3,10,10,59,59],[2041,3,10,1,59,59],
'2040110410:00:00','2040110401:00:00','2041031010:59:59','2041031001:59:59' ],
],
2041 =>
[
[ [2041,3,10,11,0,0],[2041,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2041,11,3,9,59,59],[2041,11,3,1,59,59],
'2041031011:00:00','2041031003:00:00','2041110309:59:59','2041110301:59:59' ],
[ [2041,11,3,10,0,0],[2041,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2042,3,9,10,59,59],[2042,3,9,1,59,59],
'2041110310:00:00','2041110301:00:00','2042030910:59:59','2042030901:59:59' ],
],
2042 =>
[
[ [2042,3,9,11,0,0],[2042,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2042,11,2,9,59,59],[2042,11,2,1,59,59],
'2042030911:00:00','2042030903:00:00','2042110209:59:59','2042110201:59:59' ],
[ [2042,11,2,10,0,0],[2042,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2043,3,8,10,59,59],[2043,3,8,1,59,59],
'2042110210:00:00','2042110201:00:00','2043030810:59:59','2043030801:59:59' ],
],
2043 =>
[
[ [2043,3,8,11,0,0],[2043,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2043,11,1,9,59,59],[2043,11,1,1,59,59],
'2043030811:00:00','2043030803:00:00','2043110109:59:59','2043110101:59:59' ],
[ [2043,11,1,10,0,0],[2043,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2044,3,13,10,59,59],[2044,3,13,1,59,59],
'2043110110:00:00','2043110101:00:00','2044031310:59:59','2044031301:59:59' ],
],
2044 =>
[
[ [2044,3,13,11,0,0],[2044,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2044,11,6,9,59,59],[2044,11,6,1,59,59],
'2044031311:00:00','2044031303:00:00','2044110609:59:59','2044110601:59:59' ],
[ [2044,11,6,10,0,0],[2044,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2045,3,12,10,59,59],[2045,3,12,1,59,59],
'2044110610:00:00','2044110601:00:00','2045031210:59:59','2045031201:59:59' ],
],
2045 =>
[
[ [2045,3,12,11,0,0],[2045,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2045,11,5,9,59,59],[2045,11,5,1,59,59],
'2045031211:00:00','2045031203:00:00','2045110509:59:59','2045110501:59:59' ],
[ [2045,11,5,10,0,0],[2045,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2046,3,11,10,59,59],[2046,3,11,1,59,59],
'2045110510:00:00','2045110501:00:00','2046031110:59:59','2046031101:59:59' ],
],
2046 =>
[
[ [2046,3,11,11,0,0],[2046,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2046,11,4,9,59,59],[2046,11,4,1,59,59],
'2046031111:00:00','2046031103:00:00','2046110409:59:59','2046110401:59:59' ],
[ [2046,11,4,10,0,0],[2046,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2047,3,10,10,59,59],[2047,3,10,1,59,59],
'2046110410:00:00','2046110401:00:00','2047031010:59:59','2047031001:59:59' ],
],
2047 =>
[
[ [2047,3,10,11,0,0],[2047,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2047,11,3,9,59,59],[2047,11,3,1,59,59],
'2047031011:00:00','2047031003:00:00','2047110309:59:59','2047110301:59:59' ],
[ [2047,11,3,10,0,0],[2047,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2048,3,8,10,59,59],[2048,3,8,1,59,59],
'2047110310:00:00','2047110301:00:00','2048030810:59:59','2048030801:59:59' ],
],
2048 =>
[
[ [2048,3,8,11,0,0],[2048,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2048,11,1,9,59,59],[2048,11,1,1,59,59],
'2048030811:00:00','2048030803:00:00','2048110109:59:59','2048110101:59:59' ],
[ [2048,11,1,10,0,0],[2048,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2049,3,14,10,59,59],[2049,3,14,1,59,59],
'2048110110:00:00','2048110101:00:00','2049031410:59:59','2049031401:59:59' ],
],
2049 =>
[
[ [2049,3,14,11,0,0],[2049,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2049,11,7,9,59,59],[2049,11,7,1,59,59],
'2049031411:00:00','2049031403:00:00','2049110709:59:59','2049110701:59:59' ],
[ [2049,11,7,10,0,0],[2049,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2050,3,13,10,59,59],[2050,3,13,1,59,59],
'2049110710:00:00','2049110701:00:00','2050031310:59:59','2050031301:59:59' ],
],
2050 =>
[
[ [2050,3,13,11,0,0],[2050,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2050,11,6,9,59,59],[2050,11,6,1,59,59],
'2050031311:00:00','2050031303:00:00','2050110609:59:59','2050110601:59:59' ],
[ [2050,11,6,10,0,0],[2050,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2051,3,12,10,59,59],[2051,3,12,1,59,59],
'2050110610:00:00','2050110601:00:00','2051031210:59:59','2051031201:59:59' ],
],
2051 =>
[
[ [2051,3,12,11,0,0],[2051,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2051,11,5,9,59,59],[2051,11,5,1,59,59],
'2051031211:00:00','2051031203:00:00','2051110509:59:59','2051110501:59:59' ],
[ [2051,11,5,10,0,0],[2051,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2052,3,10,10,59,59],[2052,3,10,1,59,59],
'2051110510:00:00','2051110501:00:00','2052031010:59:59','2052031001:59:59' ],
],
2052 =>
[
[ [2052,3,10,11,0,0],[2052,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2052,11,3,9,59,59],[2052,11,3,1,59,59],
'2052031011:00:00','2052031003:00:00','2052110309:59:59','2052110301:59:59' ],
[ [2052,11,3,10,0,0],[2052,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2053,3,9,10,59,59],[2053,3,9,1,59,59],
'2052110310:00:00','2052110301:00:00','2053030910:59:59','2053030901:59:59' ],
],
2053 =>
[
[ [2053,3,9,11,0,0],[2053,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2053,11,2,9,59,59],[2053,11,2,1,59,59],
'2053030911:00:00','2053030903:00:00','2053110209:59:59','2053110201:59:59' ],
[ [2053,11,2,10,0,0],[2053,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2054,3,8,10,59,59],[2054,3,8,1,59,59],
'2053110210:00:00','2053110201:00:00','2054030810:59:59','2054030801:59:59' ],
],
2054 =>
[
[ [2054,3,8,11,0,0],[2054,3,8,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2054,11,1,9,59,59],[2054,11,1,1,59,59],
'2054030811:00:00','2054030803:00:00','2054110109:59:59','2054110101:59:59' ],
[ [2054,11,1,10,0,0],[2054,11,1,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2055,3,14,10,59,59],[2055,3,14,1,59,59],
'2054110110:00:00','2054110101:00:00','2055031410:59:59','2055031401:59:59' ],
],
2055 =>
[
[ [2055,3,14,11,0,0],[2055,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2055,11,7,9,59,59],[2055,11,7,1,59,59],
'2055031411:00:00','2055031403:00:00','2055110709:59:59','2055110701:59:59' ],
[ [2055,11,7,10,0,0],[2055,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2056,3,12,10,59,59],[2056,3,12,1,59,59],
'2055110710:00:00','2055110701:00:00','2056031210:59:59','2056031201:59:59' ],
],
2056 =>
[
[ [2056,3,12,11,0,0],[2056,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2056,11,5,9,59,59],[2056,11,5,1,59,59],
'2056031211:00:00','2056031203:00:00','2056110509:59:59','2056110501:59:59' ],
[ [2056,11,5,10,0,0],[2056,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2057,3,11,10,59,59],[2057,3,11,1,59,59],
'2056110510:00:00','2056110501:00:00','2057031110:59:59','2057031101:59:59' ],
],
2057 =>
[
[ [2057,3,11,11,0,0],[2057,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2057,11,4,9,59,59],[2057,11,4,1,59,59],
'2057031111:00:00','2057031103:00:00','2057110409:59:59','2057110401:59:59' ],
[ [2057,11,4,10,0,0],[2057,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2058,3,10,10,59,59],[2058,3,10,1,59,59],
'2057110410:00:00','2057110401:00:00','2058031010:59:59','2058031001:59:59' ],
],
2058 =>
[
[ [2058,3,10,11,0,0],[2058,3,10,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2058,11,3,9,59,59],[2058,11,3,1,59,59],
'2058031011:00:00','2058031003:00:00','2058110309:59:59','2058110301:59:59' ],
[ [2058,11,3,10,0,0],[2058,11,3,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2059,3,9,10,59,59],[2059,3,9,1,59,59],
'2058110310:00:00','2058110301:00:00','2059030910:59:59','2059030901:59:59' ],
],
2059 =>
[
[ [2059,3,9,11,0,0],[2059,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2059,11,2,9,59,59],[2059,11,2,1,59,59],
'2059030911:00:00','2059030903:00:00','2059110209:59:59','2059110201:59:59' ],
[ [2059,11,2,10,0,0],[2059,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2060,3,14,10,59,59],[2060,3,14,1,59,59],
'2059110210:00:00','2059110201:00:00','2060031410:59:59','2060031401:59:59' ],
],
2060 =>
[
[ [2060,3,14,11,0,0],[2060,3,14,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2060,11,7,9,59,59],[2060,11,7,1,59,59],
'2060031411:00:00','2060031403:00:00','2060110709:59:59','2060110701:59:59' ],
[ [2060,11,7,10,0,0],[2060,11,7,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2061,3,13,10,59,59],[2061,3,13,1,59,59],
'2060110710:00:00','2060110701:00:00','2061031310:59:59','2061031301:59:59' ],
],
2061 =>
[
[ [2061,3,13,11,0,0],[2061,3,13,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2061,11,6,9,59,59],[2061,11,6,1,59,59],
'2061031311:00:00','2061031303:00:00','2061110609:59:59','2061110601:59:59' ],
[ [2061,11,6,10,0,0],[2061,11,6,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2062,3,12,10,59,59],[2062,3,12,1,59,59],
'2061110610:00:00','2061110601:00:00','2062031210:59:59','2062031201:59:59' ],
],
2062 =>
[
[ [2062,3,12,11,0,0],[2062,3,12,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2062,11,5,9,59,59],[2062,11,5,1,59,59],
'2062031211:00:00','2062031203:00:00','2062110509:59:59','2062110501:59:59' ],
[ [2062,11,5,10,0,0],[2062,11,5,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2063,3,11,10,59,59],[2063,3,11,1,59,59],
'2062110510:00:00','2062110501:00:00','2063031110:59:59','2063031101:59:59' ],
],
2063 =>
[
[ [2063,3,11,11,0,0],[2063,3,11,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2063,11,4,9,59,59],[2063,11,4,1,59,59],
'2063031111:00:00','2063031103:00:00','2063110409:59:59','2063110401:59:59' ],
[ [2063,11,4,10,0,0],[2063,11,4,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2064,3,9,10,59,59],[2064,3,9,1,59,59],
'2063110410:00:00','2063110401:00:00','2064030910:59:59','2064030901:59:59' ],
],
2064 =>
[
[ [2064,3,9,11,0,0],[2064,3,9,3,0,0],'-08:00:00',[-8,0,0],
'AKDT',1,[2064,11,2,9,59,59],[2064,11,2,1,59,59],
'2064030911:00:00','2064030903:00:00','2064110209:59:59','2064110201:59:59' ],
[ [2064,11,2,10,0,0],[2064,11,2,1,0,0],'-09:00:00',[-9,0,0],
'AKST',0,[2065,3,8,10,59,59],[2065,3,8,1,59,59],
'2064110210:00:00','2064110201:00:00','2065030810:59:59','2065030801:59:59' ],
],
);
%LastRule = (
'zone' => {
'dstoff' => '-08:00:00',
'stdoff' => '-09:00:00',
},
'rules' => {
'03' => {
'flag' => 'ge',
'dow' => '7',
'num' => '8',
'type' => 'w',
'time' => '02:00:00',
'isdst' => '1',
'abb' => 'AKDT',
},
'11' => {
'flag' => 'ge',
'dow' => '7',
'num' => '1',
'type' => 'w',
'time' => '02:00:00',
'isdst' => '0',
'abb' => 'AKST',
},
},
);
1;
| nriley/Pester | Source/Manip/TZ/amjune00.pm | Perl | bsd-2-clause | 47,735 |
# !!!!!!! 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';
0000 10FF
1200 A95F
A97D ABFF
D7A4 D7AF
D7C7 D7CA
D7FC 10FFFF
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Hst/NA.pl | Perl | mit | 485 |
{
"id": "test-container-force-killing",
"containers" : [{
"name": "busybox-with-tty",
"image": "busybox",
"command": ["/bin/sh"]
}],
"resource": {
"vcpu": 1,
"memory": 256
},
"tty": true
}
| gao-feng/hyper-public | hack/pods/busybox-tty.pod | Perl | apache-2.0 | 297 |
#-----------------------------------------------------------
# watp
#
# Change history:
# 20190506 - created
#
# Ref:
#
#
# copyright 2019 QAR,LLC
# Author: H. Carvey, keydet89@yahoo.com
#-----------------------------------------------------------
package watp;
use strict;
my %config = (hive => "Software",
category => "config",
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
osmask => 22,
version => 20190506);
sub getConfig{return %config}
sub getShortDescr {
return "Gets contents of Windows Advanced Threat Protection key";
}
sub getDescr{}
sub getRefs {
}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
sub pluginmain {
my $class = shift;
my $hive = shift;
::rptMsg("Launching watp v.".$VERSION);
::rptMsg("watp v.".$VERSION); # banner
::rptMsg("(".$config{hive}.") ".getShortDescr()."\n"); # banner
my $key_path = ('Microsoft\\Windows Advanced Protection');
my $reg = Parse::Win32Registry->new($hive);
my $root_key = $reg->get_root_key;
my $key;
if ($key = $root_key->get_subkey($key_path)) {
::rptMsg($key_path);
::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
my @vals = $key->get_list_of_values();
foreach my $v (@vals) {
::rptMsg($v->get_name()." ".$v->get_data());
}
}
else {
::rptMsg($key_path." not found.");
}
}
1; | sleuthkit/autopsy | thirdparty/rr-full/plugins/watp.pl | Perl | apache-2.0 | 1,482 |
# This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/rnClxBLdxJ/northamerica. Olson data version 2013a
#
# Do not edit this file directly.
#
package DateTime::TimeZone::America::Nassau;
{
$DateTime::TimeZone::America::Nassau::VERSION = '1.57';
}
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::America::Nassau::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY, # utc_start
60310588170, # utc_end 1912-03-02 05:09:30 (Sat)
DateTime::TimeZone::NEG_INFINITY, # local_start
60310569600, # local_end 1912-03-02 00:00:00 (Sat)
-18570,
0,
'LMT',
],
[
60310588170, # utc_start 1912-03-02 05:09:30 (Sat)
61956342000, # utc_end 1964-04-26 07:00:00 (Sun)
60310570170, # local_start 1912-03-02 00:09:30 (Sat)
61956324000, # local_end 1964-04-26 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
61956342000, # utc_start 1964-04-26 07:00:00 (Sun)
61972063200, # utc_end 1964-10-25 06:00:00 (Sun)
61956327600, # local_start 1964-04-26 03:00:00 (Sun)
61972048800, # local_end 1964-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
61972063200, # utc_start 1964-10-25 06:00:00 (Sun)
61987791600, # utc_end 1965-04-25 07:00:00 (Sun)
61972045200, # local_start 1964-10-25 01:00:00 (Sun)
61987773600, # local_end 1965-04-25 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
61987791600, # utc_start 1965-04-25 07:00:00 (Sun)
62004117600, # utc_end 1965-10-31 06:00:00 (Sun)
61987777200, # local_start 1965-04-25 03:00:00 (Sun)
62004103200, # local_end 1965-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62004117600, # utc_start 1965-10-31 06:00:00 (Sun)
62019241200, # utc_end 1966-04-24 07:00:00 (Sun)
62004099600, # local_start 1965-10-31 01:00:00 (Sun)
62019223200, # local_end 1966-04-24 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62019241200, # utc_start 1966-04-24 07:00:00 (Sun)
62035567200, # utc_end 1966-10-30 06:00:00 (Sun)
62019226800, # local_start 1966-04-24 03:00:00 (Sun)
62035552800, # local_end 1966-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62035567200, # utc_start 1966-10-30 06:00:00 (Sun)
62051295600, # utc_end 1967-04-30 07:00:00 (Sun)
62035549200, # local_start 1966-10-30 01:00:00 (Sun)
62051277600, # local_end 1967-04-30 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62051295600, # utc_start 1967-04-30 07:00:00 (Sun)
62067016800, # utc_end 1967-10-29 06:00:00 (Sun)
62051281200, # local_start 1967-04-30 03:00:00 (Sun)
62067002400, # local_end 1967-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62067016800, # utc_start 1967-10-29 06:00:00 (Sun)
62082745200, # utc_end 1968-04-28 07:00:00 (Sun)
62066998800, # local_start 1967-10-29 01:00:00 (Sun)
62082727200, # local_end 1968-04-28 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62082745200, # utc_start 1968-04-28 07:00:00 (Sun)
62098466400, # utc_end 1968-10-27 06:00:00 (Sun)
62082730800, # local_start 1968-04-28 03:00:00 (Sun)
62098452000, # local_end 1968-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62098466400, # utc_start 1968-10-27 06:00:00 (Sun)
62114194800, # utc_end 1969-04-27 07:00:00 (Sun)
62098448400, # local_start 1968-10-27 01:00:00 (Sun)
62114176800, # local_end 1969-04-27 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62114194800, # utc_start 1969-04-27 07:00:00 (Sun)
62129916000, # utc_end 1969-10-26 06:00:00 (Sun)
62114180400, # local_start 1969-04-27 03:00:00 (Sun)
62129901600, # local_end 1969-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62129916000, # utc_start 1969-10-26 06:00:00 (Sun)
62145644400, # utc_end 1970-04-26 07:00:00 (Sun)
62129898000, # local_start 1969-10-26 01:00:00 (Sun)
62145626400, # local_end 1970-04-26 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62145644400, # utc_start 1970-04-26 07:00:00 (Sun)
62161365600, # utc_end 1970-10-25 06:00:00 (Sun)
62145630000, # local_start 1970-04-26 03:00:00 (Sun)
62161351200, # local_end 1970-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62161365600, # utc_start 1970-10-25 06:00:00 (Sun)
62177094000, # utc_end 1971-04-25 07:00:00 (Sun)
62161347600, # local_start 1970-10-25 01:00:00 (Sun)
62177076000, # local_end 1971-04-25 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62177094000, # utc_start 1971-04-25 07:00:00 (Sun)
62193420000, # utc_end 1971-10-31 06:00:00 (Sun)
62177079600, # local_start 1971-04-25 03:00:00 (Sun)
62193405600, # local_end 1971-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62193420000, # utc_start 1971-10-31 06:00:00 (Sun)
62209148400, # utc_end 1972-04-30 07:00:00 (Sun)
62193402000, # local_start 1971-10-31 01:00:00 (Sun)
62209130400, # local_end 1972-04-30 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62209148400, # utc_start 1972-04-30 07:00:00 (Sun)
62224869600, # utc_end 1972-10-29 06:00:00 (Sun)
62209134000, # local_start 1972-04-30 03:00:00 (Sun)
62224855200, # local_end 1972-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62224869600, # utc_start 1972-10-29 06:00:00 (Sun)
62240598000, # utc_end 1973-04-29 07:00:00 (Sun)
62224851600, # local_start 1972-10-29 01:00:00 (Sun)
62240580000, # local_end 1973-04-29 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62240598000, # utc_start 1973-04-29 07:00:00 (Sun)
62256319200, # utc_end 1973-10-28 06:00:00 (Sun)
62240583600, # local_start 1973-04-29 03:00:00 (Sun)
62256304800, # local_end 1973-10-28 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62256319200, # utc_start 1973-10-28 06:00:00 (Sun)
62272047600, # utc_end 1974-04-28 07:00:00 (Sun)
62256301200, # local_start 1973-10-28 01:00:00 (Sun)
62272029600, # local_end 1974-04-28 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62272047600, # utc_start 1974-04-28 07:00:00 (Sun)
62287768800, # utc_end 1974-10-27 06:00:00 (Sun)
62272033200, # local_start 1974-04-28 03:00:00 (Sun)
62287754400, # local_end 1974-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62287768800, # utc_start 1974-10-27 06:00:00 (Sun)
62303497200, # utc_end 1975-04-27 07:00:00 (Sun)
62287750800, # local_start 1974-10-27 01:00:00 (Sun)
62303479200, # local_end 1975-04-27 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62303497200, # utc_start 1975-04-27 07:00:00 (Sun)
62319218400, # utc_end 1975-10-26 06:00:00 (Sun)
62303482800, # local_start 1975-04-27 03:00:00 (Sun)
62319204000, # local_end 1975-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62319218400, # utc_start 1975-10-26 06:00:00 (Sun)
62325003600, # utc_end 1976-01-01 05:00:00 (Thu)
62319200400, # local_start 1975-10-26 01:00:00 (Sun)
62324985600, # local_end 1976-01-01 00:00:00 (Thu)
-18000,
0,
'EST',
],
[
62325003600, # utc_start 1976-01-01 05:00:00 (Thu)
62334946800, # utc_end 1976-04-25 07:00:00 (Sun)
62324985600, # local_start 1976-01-01 00:00:00 (Thu)
62334928800, # local_end 1976-04-25 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62334946800, # utc_start 1976-04-25 07:00:00 (Sun)
62351272800, # utc_end 1976-10-31 06:00:00 (Sun)
62334932400, # local_start 1976-04-25 03:00:00 (Sun)
62351258400, # local_end 1976-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62351272800, # utc_start 1976-10-31 06:00:00 (Sun)
62366396400, # utc_end 1977-04-24 07:00:00 (Sun)
62351254800, # local_start 1976-10-31 01:00:00 (Sun)
62366378400, # local_end 1977-04-24 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62366396400, # utc_start 1977-04-24 07:00:00 (Sun)
62382722400, # utc_end 1977-10-30 06:00:00 (Sun)
62366382000, # local_start 1977-04-24 03:00:00 (Sun)
62382708000, # local_end 1977-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62382722400, # utc_start 1977-10-30 06:00:00 (Sun)
62398450800, # utc_end 1978-04-30 07:00:00 (Sun)
62382704400, # local_start 1977-10-30 01:00:00 (Sun)
62398432800, # local_end 1978-04-30 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62398450800, # utc_start 1978-04-30 07:00:00 (Sun)
62414172000, # utc_end 1978-10-29 06:00:00 (Sun)
62398436400, # local_start 1978-04-30 03:00:00 (Sun)
62414157600, # local_end 1978-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62414172000, # utc_start 1978-10-29 06:00:00 (Sun)
62429900400, # utc_end 1979-04-29 07:00:00 (Sun)
62414154000, # local_start 1978-10-29 01:00:00 (Sun)
62429882400, # local_end 1979-04-29 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62429900400, # utc_start 1979-04-29 07:00:00 (Sun)
62445621600, # utc_end 1979-10-28 06:00:00 (Sun)
62429886000, # local_start 1979-04-29 03:00:00 (Sun)
62445607200, # local_end 1979-10-28 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62445621600, # utc_start 1979-10-28 06:00:00 (Sun)
62461350000, # utc_end 1980-04-27 07:00:00 (Sun)
62445603600, # local_start 1979-10-28 01:00:00 (Sun)
62461332000, # local_end 1980-04-27 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62461350000, # utc_start 1980-04-27 07:00:00 (Sun)
62477071200, # utc_end 1980-10-26 06:00:00 (Sun)
62461335600, # local_start 1980-04-27 03:00:00 (Sun)
62477056800, # local_end 1980-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62477071200, # utc_start 1980-10-26 06:00:00 (Sun)
62492799600, # utc_end 1981-04-26 07:00:00 (Sun)
62477053200, # local_start 1980-10-26 01:00:00 (Sun)
62492781600, # local_end 1981-04-26 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62492799600, # utc_start 1981-04-26 07:00:00 (Sun)
62508520800, # utc_end 1981-10-25 06:00:00 (Sun)
62492785200, # local_start 1981-04-26 03:00:00 (Sun)
62508506400, # local_end 1981-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62508520800, # utc_start 1981-10-25 06:00:00 (Sun)
62524249200, # utc_end 1982-04-25 07:00:00 (Sun)
62508502800, # local_start 1981-10-25 01:00:00 (Sun)
62524231200, # local_end 1982-04-25 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62524249200, # utc_start 1982-04-25 07:00:00 (Sun)
62540575200, # utc_end 1982-10-31 06:00:00 (Sun)
62524234800, # local_start 1982-04-25 03:00:00 (Sun)
62540560800, # local_end 1982-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62540575200, # utc_start 1982-10-31 06:00:00 (Sun)
62555698800, # utc_end 1983-04-24 07:00:00 (Sun)
62540557200, # local_start 1982-10-31 01:00:00 (Sun)
62555680800, # local_end 1983-04-24 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62555698800, # utc_start 1983-04-24 07:00:00 (Sun)
62572024800, # utc_end 1983-10-30 06:00:00 (Sun)
62555684400, # local_start 1983-04-24 03:00:00 (Sun)
62572010400, # local_end 1983-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62572024800, # utc_start 1983-10-30 06:00:00 (Sun)
62587753200, # utc_end 1984-04-29 07:00:00 (Sun)
62572006800, # local_start 1983-10-30 01:00:00 (Sun)
62587735200, # local_end 1984-04-29 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62587753200, # utc_start 1984-04-29 07:00:00 (Sun)
62603474400, # utc_end 1984-10-28 06:00:00 (Sun)
62587738800, # local_start 1984-04-29 03:00:00 (Sun)
62603460000, # local_end 1984-10-28 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62603474400, # utc_start 1984-10-28 06:00:00 (Sun)
62619202800, # utc_end 1985-04-28 07:00:00 (Sun)
62603456400, # local_start 1984-10-28 01:00:00 (Sun)
62619184800, # local_end 1985-04-28 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62619202800, # utc_start 1985-04-28 07:00:00 (Sun)
62634924000, # utc_end 1985-10-27 06:00:00 (Sun)
62619188400, # local_start 1985-04-28 03:00:00 (Sun)
62634909600, # local_end 1985-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62634924000, # utc_start 1985-10-27 06:00:00 (Sun)
62650652400, # utc_end 1986-04-27 07:00:00 (Sun)
62634906000, # local_start 1985-10-27 01:00:00 (Sun)
62650634400, # local_end 1986-04-27 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62650652400, # utc_start 1986-04-27 07:00:00 (Sun)
62666373600, # utc_end 1986-10-26 06:00:00 (Sun)
62650638000, # local_start 1986-04-27 03:00:00 (Sun)
62666359200, # local_end 1986-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62666373600, # utc_start 1986-10-26 06:00:00 (Sun)
62680287600, # utc_end 1987-04-05 07:00:00 (Sun)
62666355600, # local_start 1986-10-26 01:00:00 (Sun)
62680269600, # local_end 1987-04-05 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62680287600, # utc_start 1987-04-05 07:00:00 (Sun)
62697823200, # utc_end 1987-10-25 06:00:00 (Sun)
62680273200, # local_start 1987-04-05 03:00:00 (Sun)
62697808800, # local_end 1987-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62697823200, # utc_start 1987-10-25 06:00:00 (Sun)
62711737200, # utc_end 1988-04-03 07:00:00 (Sun)
62697805200, # local_start 1987-10-25 01:00:00 (Sun)
62711719200, # local_end 1988-04-03 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62711737200, # utc_start 1988-04-03 07:00:00 (Sun)
62729877600, # utc_end 1988-10-30 06:00:00 (Sun)
62711722800, # local_start 1988-04-03 03:00:00 (Sun)
62729863200, # local_end 1988-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62729877600, # utc_start 1988-10-30 06:00:00 (Sun)
62743186800, # utc_end 1989-04-02 07:00:00 (Sun)
62729859600, # local_start 1988-10-30 01:00:00 (Sun)
62743168800, # local_end 1989-04-02 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62743186800, # utc_start 1989-04-02 07:00:00 (Sun)
62761327200, # utc_end 1989-10-29 06:00:00 (Sun)
62743172400, # local_start 1989-04-02 03:00:00 (Sun)
62761312800, # local_end 1989-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62761327200, # utc_start 1989-10-29 06:00:00 (Sun)
62774636400, # utc_end 1990-04-01 07:00:00 (Sun)
62761309200, # local_start 1989-10-29 01:00:00 (Sun)
62774618400, # local_end 1990-04-01 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62774636400, # utc_start 1990-04-01 07:00:00 (Sun)
62792776800, # utc_end 1990-10-28 06:00:00 (Sun)
62774622000, # local_start 1990-04-01 03:00:00 (Sun)
62792762400, # local_end 1990-10-28 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62792776800, # utc_start 1990-10-28 06:00:00 (Sun)
62806690800, # utc_end 1991-04-07 07:00:00 (Sun)
62792758800, # local_start 1990-10-28 01:00:00 (Sun)
62806672800, # local_end 1991-04-07 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62806690800, # utc_start 1991-04-07 07:00:00 (Sun)
62824226400, # utc_end 1991-10-27 06:00:00 (Sun)
62806676400, # local_start 1991-04-07 03:00:00 (Sun)
62824212000, # local_end 1991-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62824226400, # utc_start 1991-10-27 06:00:00 (Sun)
62838140400, # utc_end 1992-04-05 07:00:00 (Sun)
62824208400, # local_start 1991-10-27 01:00:00 (Sun)
62838122400, # local_end 1992-04-05 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62838140400, # utc_start 1992-04-05 07:00:00 (Sun)
62855676000, # utc_end 1992-10-25 06:00:00 (Sun)
62838126000, # local_start 1992-04-05 03:00:00 (Sun)
62855661600, # local_end 1992-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62855676000, # utc_start 1992-10-25 06:00:00 (Sun)
62869590000, # utc_end 1993-04-04 07:00:00 (Sun)
62855658000, # local_start 1992-10-25 01:00:00 (Sun)
62869572000, # local_end 1993-04-04 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62869590000, # utc_start 1993-04-04 07:00:00 (Sun)
62887730400, # utc_end 1993-10-31 06:00:00 (Sun)
62869575600, # local_start 1993-04-04 03:00:00 (Sun)
62887716000, # local_end 1993-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62887730400, # utc_start 1993-10-31 06:00:00 (Sun)
62901039600, # utc_end 1994-04-03 07:00:00 (Sun)
62887712400, # local_start 1993-10-31 01:00:00 (Sun)
62901021600, # local_end 1994-04-03 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62901039600, # utc_start 1994-04-03 07:00:00 (Sun)
62919180000, # utc_end 1994-10-30 06:00:00 (Sun)
62901025200, # local_start 1994-04-03 03:00:00 (Sun)
62919165600, # local_end 1994-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62919180000, # utc_start 1994-10-30 06:00:00 (Sun)
62932489200, # utc_end 1995-04-02 07:00:00 (Sun)
62919162000, # local_start 1994-10-30 01:00:00 (Sun)
62932471200, # local_end 1995-04-02 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62932489200, # utc_start 1995-04-02 07:00:00 (Sun)
62950629600, # utc_end 1995-10-29 06:00:00 (Sun)
62932474800, # local_start 1995-04-02 03:00:00 (Sun)
62950615200, # local_end 1995-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62950629600, # utc_start 1995-10-29 06:00:00 (Sun)
62964543600, # utc_end 1996-04-07 07:00:00 (Sun)
62950611600, # local_start 1995-10-29 01:00:00 (Sun)
62964525600, # local_end 1996-04-07 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62964543600, # utc_start 1996-04-07 07:00:00 (Sun)
62982079200, # utc_end 1996-10-27 06:00:00 (Sun)
62964529200, # local_start 1996-04-07 03:00:00 (Sun)
62982064800, # local_end 1996-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
62982079200, # utc_start 1996-10-27 06:00:00 (Sun)
62995993200, # utc_end 1997-04-06 07:00:00 (Sun)
62982061200, # local_start 1996-10-27 01:00:00 (Sun)
62995975200, # local_end 1997-04-06 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
62995993200, # utc_start 1997-04-06 07:00:00 (Sun)
63013528800, # utc_end 1997-10-26 06:00:00 (Sun)
62995978800, # local_start 1997-04-06 03:00:00 (Sun)
63013514400, # local_end 1997-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63013528800, # utc_start 1997-10-26 06:00:00 (Sun)
63027442800, # utc_end 1998-04-05 07:00:00 (Sun)
63013510800, # local_start 1997-10-26 01:00:00 (Sun)
63027424800, # local_end 1998-04-05 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63027442800, # utc_start 1998-04-05 07:00:00 (Sun)
63044978400, # utc_end 1998-10-25 06:00:00 (Sun)
63027428400, # local_start 1998-04-05 03:00:00 (Sun)
63044964000, # local_end 1998-10-25 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63044978400, # utc_start 1998-10-25 06:00:00 (Sun)
63058892400, # utc_end 1999-04-04 07:00:00 (Sun)
63044960400, # local_start 1998-10-25 01:00:00 (Sun)
63058874400, # local_end 1999-04-04 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63058892400, # utc_start 1999-04-04 07:00:00 (Sun)
63077032800, # utc_end 1999-10-31 06:00:00 (Sun)
63058878000, # local_start 1999-04-04 03:00:00 (Sun)
63077018400, # local_end 1999-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63077032800, # utc_start 1999-10-31 06:00:00 (Sun)
63090342000, # utc_end 2000-04-02 07:00:00 (Sun)
63077014800, # local_start 1999-10-31 01:00:00 (Sun)
63090324000, # local_end 2000-04-02 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63090342000, # utc_start 2000-04-02 07:00:00 (Sun)
63108482400, # utc_end 2000-10-29 06:00:00 (Sun)
63090327600, # local_start 2000-04-02 03:00:00 (Sun)
63108468000, # local_end 2000-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63108482400, # utc_start 2000-10-29 06:00:00 (Sun)
63121791600, # utc_end 2001-04-01 07:00:00 (Sun)
63108464400, # local_start 2000-10-29 01:00:00 (Sun)
63121773600, # local_end 2001-04-01 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63121791600, # utc_start 2001-04-01 07:00:00 (Sun)
63139932000, # utc_end 2001-10-28 06:00:00 (Sun)
63121777200, # local_start 2001-04-01 03:00:00 (Sun)
63139917600, # local_end 2001-10-28 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63139932000, # utc_start 2001-10-28 06:00:00 (Sun)
63153846000, # utc_end 2002-04-07 07:00:00 (Sun)
63139914000, # local_start 2001-10-28 01:00:00 (Sun)
63153828000, # local_end 2002-04-07 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63153846000, # utc_start 2002-04-07 07:00:00 (Sun)
63171381600, # utc_end 2002-10-27 06:00:00 (Sun)
63153831600, # local_start 2002-04-07 03:00:00 (Sun)
63171367200, # local_end 2002-10-27 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63171381600, # utc_start 2002-10-27 06:00:00 (Sun)
63185295600, # utc_end 2003-04-06 07:00:00 (Sun)
63171363600, # local_start 2002-10-27 01:00:00 (Sun)
63185277600, # local_end 2003-04-06 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63185295600, # utc_start 2003-04-06 07:00:00 (Sun)
63202831200, # utc_end 2003-10-26 06:00:00 (Sun)
63185281200, # local_start 2003-04-06 03:00:00 (Sun)
63202816800, # local_end 2003-10-26 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63202831200, # utc_start 2003-10-26 06:00:00 (Sun)
63216745200, # utc_end 2004-04-04 07:00:00 (Sun)
63202813200, # local_start 2003-10-26 01:00:00 (Sun)
63216727200, # local_end 2004-04-04 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63216745200, # utc_start 2004-04-04 07:00:00 (Sun)
63234885600, # utc_end 2004-10-31 06:00:00 (Sun)
63216730800, # local_start 2004-04-04 03:00:00 (Sun)
63234871200, # local_end 2004-10-31 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63234885600, # utc_start 2004-10-31 06:00:00 (Sun)
63248194800, # utc_end 2005-04-03 07:00:00 (Sun)
63234867600, # local_start 2004-10-31 01:00:00 (Sun)
63248176800, # local_end 2005-04-03 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63248194800, # utc_start 2005-04-03 07:00:00 (Sun)
63266335200, # utc_end 2005-10-30 06:00:00 (Sun)
63248180400, # local_start 2005-04-03 03:00:00 (Sun)
63266320800, # local_end 2005-10-30 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63266335200, # utc_start 2005-10-30 06:00:00 (Sun)
63279644400, # utc_end 2006-04-02 07:00:00 (Sun)
63266317200, # local_start 2005-10-30 01:00:00 (Sun)
63279626400, # local_end 2006-04-02 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63279644400, # utc_start 2006-04-02 07:00:00 (Sun)
63297784800, # utc_end 2006-10-29 06:00:00 (Sun)
63279630000, # local_start 2006-04-02 03:00:00 (Sun)
63297770400, # local_end 2006-10-29 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63297784800, # utc_start 2006-10-29 06:00:00 (Sun)
63309279600, # utc_end 2007-03-11 07:00:00 (Sun)
63297766800, # local_start 2006-10-29 01:00:00 (Sun)
63309261600, # local_end 2007-03-11 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63309279600, # utc_start 2007-03-11 07:00:00 (Sun)
63329839200, # utc_end 2007-11-04 06:00:00 (Sun)
63309265200, # local_start 2007-03-11 03:00:00 (Sun)
63329824800, # local_end 2007-11-04 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63329839200, # utc_start 2007-11-04 06:00:00 (Sun)
63340729200, # utc_end 2008-03-09 07:00:00 (Sun)
63329821200, # local_start 2007-11-04 01:00:00 (Sun)
63340711200, # local_end 2008-03-09 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63340729200, # utc_start 2008-03-09 07:00:00 (Sun)
63361288800, # utc_end 2008-11-02 06:00:00 (Sun)
63340714800, # local_start 2008-03-09 03:00:00 (Sun)
63361274400, # local_end 2008-11-02 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63361288800, # utc_start 2008-11-02 06:00:00 (Sun)
63372178800, # utc_end 2009-03-08 07:00:00 (Sun)
63361270800, # local_start 2008-11-02 01:00:00 (Sun)
63372160800, # local_end 2009-03-08 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63372178800, # utc_start 2009-03-08 07:00:00 (Sun)
63392738400, # utc_end 2009-11-01 06:00:00 (Sun)
63372164400, # local_start 2009-03-08 03:00:00 (Sun)
63392724000, # local_end 2009-11-01 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63392738400, # utc_start 2009-11-01 06:00:00 (Sun)
63404233200, # utc_end 2010-03-14 07:00:00 (Sun)
63392720400, # local_start 2009-11-01 01:00:00 (Sun)
63404215200, # local_end 2010-03-14 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63404233200, # utc_start 2010-03-14 07:00:00 (Sun)
63424792800, # utc_end 2010-11-07 06:00:00 (Sun)
63404218800, # local_start 2010-03-14 03:00:00 (Sun)
63424778400, # local_end 2010-11-07 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63424792800, # utc_start 2010-11-07 06:00:00 (Sun)
63435682800, # utc_end 2011-03-13 07:00:00 (Sun)
63424774800, # local_start 2010-11-07 01:00:00 (Sun)
63435664800, # local_end 2011-03-13 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63435682800, # utc_start 2011-03-13 07:00:00 (Sun)
63456242400, # utc_end 2011-11-06 06:00:00 (Sun)
63435668400, # local_start 2011-03-13 03:00:00 (Sun)
63456228000, # local_end 2011-11-06 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63456242400, # utc_start 2011-11-06 06:00:00 (Sun)
63467132400, # utc_end 2012-03-11 07:00:00 (Sun)
63456224400, # local_start 2011-11-06 01:00:00 (Sun)
63467114400, # local_end 2012-03-11 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63467132400, # utc_start 2012-03-11 07:00:00 (Sun)
63487692000, # utc_end 2012-11-04 06:00:00 (Sun)
63467118000, # local_start 2012-03-11 03:00:00 (Sun)
63487677600, # local_end 2012-11-04 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63487692000, # utc_start 2012-11-04 06:00:00 (Sun)
63498582000, # utc_end 2013-03-10 07:00:00 (Sun)
63487674000, # local_start 2012-11-04 01:00:00 (Sun)
63498564000, # local_end 2013-03-10 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63498582000, # utc_start 2013-03-10 07:00:00 (Sun)
63519141600, # utc_end 2013-11-03 06:00:00 (Sun)
63498567600, # local_start 2013-03-10 03:00:00 (Sun)
63519127200, # local_end 2013-11-03 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63519141600, # utc_start 2013-11-03 06:00:00 (Sun)
63530031600, # utc_end 2014-03-09 07:00:00 (Sun)
63519123600, # local_start 2013-11-03 01:00:00 (Sun)
63530013600, # local_end 2014-03-09 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63530031600, # utc_start 2014-03-09 07:00:00 (Sun)
63550591200, # utc_end 2014-11-02 06:00:00 (Sun)
63530017200, # local_start 2014-03-09 03:00:00 (Sun)
63550576800, # local_end 2014-11-02 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63550591200, # utc_start 2014-11-02 06:00:00 (Sun)
63561481200, # utc_end 2015-03-08 07:00:00 (Sun)
63550573200, # local_start 2014-11-02 01:00:00 (Sun)
63561463200, # local_end 2015-03-08 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63561481200, # utc_start 2015-03-08 07:00:00 (Sun)
63582040800, # utc_end 2015-11-01 06:00:00 (Sun)
63561466800, # local_start 2015-03-08 03:00:00 (Sun)
63582026400, # local_end 2015-11-01 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63582040800, # utc_start 2015-11-01 06:00:00 (Sun)
63593535600, # utc_end 2016-03-13 07:00:00 (Sun)
63582022800, # local_start 2015-11-01 01:00:00 (Sun)
63593517600, # local_end 2016-03-13 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63593535600, # utc_start 2016-03-13 07:00:00 (Sun)
63614095200, # utc_end 2016-11-06 06:00:00 (Sun)
63593521200, # local_start 2016-03-13 03:00:00 (Sun)
63614080800, # local_end 2016-11-06 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63614095200, # utc_start 2016-11-06 06:00:00 (Sun)
63624985200, # utc_end 2017-03-12 07:00:00 (Sun)
63614077200, # local_start 2016-11-06 01:00:00 (Sun)
63624967200, # local_end 2017-03-12 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63624985200, # utc_start 2017-03-12 07:00:00 (Sun)
63645544800, # utc_end 2017-11-05 06:00:00 (Sun)
63624970800, # local_start 2017-03-12 03:00:00 (Sun)
63645530400, # local_end 2017-11-05 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63645544800, # utc_start 2017-11-05 06:00:00 (Sun)
63656434800, # utc_end 2018-03-11 07:00:00 (Sun)
63645526800, # local_start 2017-11-05 01:00:00 (Sun)
63656416800, # local_end 2018-03-11 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63656434800, # utc_start 2018-03-11 07:00:00 (Sun)
63676994400, # utc_end 2018-11-04 06:00:00 (Sun)
63656420400, # local_start 2018-03-11 03:00:00 (Sun)
63676980000, # local_end 2018-11-04 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63676994400, # utc_start 2018-11-04 06:00:00 (Sun)
63687884400, # utc_end 2019-03-10 07:00:00 (Sun)
63676976400, # local_start 2018-11-04 01:00:00 (Sun)
63687866400, # local_end 2019-03-10 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63687884400, # utc_start 2019-03-10 07:00:00 (Sun)
63708444000, # utc_end 2019-11-03 06:00:00 (Sun)
63687870000, # local_start 2019-03-10 03:00:00 (Sun)
63708429600, # local_end 2019-11-03 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63708444000, # utc_start 2019-11-03 06:00:00 (Sun)
63719334000, # utc_end 2020-03-08 07:00:00 (Sun)
63708426000, # local_start 2019-11-03 01:00:00 (Sun)
63719316000, # local_end 2020-03-08 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63719334000, # utc_start 2020-03-08 07:00:00 (Sun)
63739893600, # utc_end 2020-11-01 06:00:00 (Sun)
63719319600, # local_start 2020-03-08 03:00:00 (Sun)
63739879200, # local_end 2020-11-01 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63739893600, # utc_start 2020-11-01 06:00:00 (Sun)
63751388400, # utc_end 2021-03-14 07:00:00 (Sun)
63739875600, # local_start 2020-11-01 01:00:00 (Sun)
63751370400, # local_end 2021-03-14 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63751388400, # utc_start 2021-03-14 07:00:00 (Sun)
63771948000, # utc_end 2021-11-07 06:00:00 (Sun)
63751374000, # local_start 2021-03-14 03:00:00 (Sun)
63771933600, # local_end 2021-11-07 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63771948000, # utc_start 2021-11-07 06:00:00 (Sun)
63782838000, # utc_end 2022-03-13 07:00:00 (Sun)
63771930000, # local_start 2021-11-07 01:00:00 (Sun)
63782820000, # local_end 2022-03-13 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63782838000, # utc_start 2022-03-13 07:00:00 (Sun)
63803397600, # utc_end 2022-11-06 06:00:00 (Sun)
63782823600, # local_start 2022-03-13 03:00:00 (Sun)
63803383200, # local_end 2022-11-06 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63803397600, # utc_start 2022-11-06 06:00:00 (Sun)
63814287600, # utc_end 2023-03-12 07:00:00 (Sun)
63803379600, # local_start 2022-11-06 01:00:00 (Sun)
63814269600, # local_end 2023-03-12 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63814287600, # utc_start 2023-03-12 07:00:00 (Sun)
63834847200, # utc_end 2023-11-05 06:00:00 (Sun)
63814273200, # local_start 2023-03-12 03:00:00 (Sun)
63834832800, # local_end 2023-11-05 02:00:00 (Sun)
-14400,
1,
'EDT',
],
[
63834847200, # utc_start 2023-11-05 06:00:00 (Sun)
63845737200, # utc_end 2024-03-10 07:00:00 (Sun)
63834829200, # local_start 2023-11-05 01:00:00 (Sun)
63845719200, # local_end 2024-03-10 02:00:00 (Sun)
-18000,
0,
'EST',
],
[
63845737200, # utc_start 2024-03-10 07:00:00 (Sun)
63866296800, # utc_end 2024-11-03 06:00:00 (Sun)
63845722800, # local_start 2024-03-10 03:00:00 (Sun)
63866282400, # local_end 2024-11-03 02:00:00 (Sun)
-14400,
1,
'EDT',
],
];
sub olson_version { '2013a' }
sub has_dst_changes { 61 }
sub _max_year { 2023 }
sub _new_instance
{
return shift->_init( @_, spans => $spans );
}
sub _last_offset { -18000 }
my $last_observance = bless( {
'format' => 'E%sT',
'gmtoff' => '-5:00',
'local_start_datetime' => bless( {
'formatter' => undef,
'local_rd_days' => 721354,
'local_rd_secs' => 0,
'offset_modifier' => 0,
'rd_nanosecs' => 0,
'tz' => bless( {
'name' => 'floating',
'offset' => 0
}, 'DateTime::TimeZone::Floating' ),
'utc_rd_days' => 721354,
'utc_rd_secs' => 0,
'utc_year' => 1977
}, 'DateTime' ),
'offset_from_std' => 0,
'offset_from_utc' => -18000,
'until' => [],
'utc_start_datetime' => bless( {
'formatter' => undef,
'local_rd_days' => 721354,
'local_rd_secs' => 18000,
'offset_modifier' => 0,
'rd_nanosecs' => 0,
'tz' => bless( {
'name' => 'floating',
'offset' => 0
}, 'DateTime::TimeZone::Floating' ),
'utc_rd_days' => 721354,
'utc_rd_secs' => 18000,
'utc_year' => 1977
}, 'DateTime' )
}, 'DateTime::TimeZone::OlsonDB::Observance' )
;
sub _last_observance { $last_observance }
my $rules = [
bless( {
'at' => '2:00',
'from' => '2007',
'in' => 'Nov',
'letter' => 'S',
'name' => 'US',
'offset_from_std' => 0,
'on' => 'Sun>=1',
'save' => '0',
'to' => 'max',
'type' => undef
}, 'DateTime::TimeZone::OlsonDB::Rule' ),
bless( {
'at' => '2:00',
'from' => '2007',
'in' => 'Mar',
'letter' => 'D',
'name' => 'US',
'offset_from_std' => 3600,
'on' => 'Sun>=8',
'save' => '1:00',
'to' => 'max',
'type' => undef
}, 'DateTime::TimeZone::OlsonDB::Rule' )
]
;
sub _rules { $rules }
1;
| Dokaponteam/ITF_Project | xampp/perl/vendor/lib/DateTime/TimeZone/America/Nassau.pm | Perl | mit | 33,003 |
package HTTP::AppServer::Plugin::AllRetriever;
# Plugin for HTTP::AppServer that retrieves files from a document root.
# 2010 by Tom Kirchner
#use 5.010000;
use strict;
use warnings;
use IO::File;
use JSON;
use Path::Trim;
use HTTP::AppServer::Plugin;
use base qw(HTTP::AppServer::Plugin);
use File::MimeInfo;
our $VERSION = '0.01';
# document root for file retrieval
my $DocRoot = '/tmp';
my $PathTrimmer = Path::Trim->new();
# called by the server when the plugin is installed
# to determine which routes are handled by the plugin
sub init
{
my ($class, $server, %options) = @_;
$PathTrimmer->set_directory_separator('/');
# analyse options
$DocRoot = $options{'DocRoot'} if exists $options{'DocRoot'};
# install properties in server
$server->set('docroot', $DocRoot);
return (
# handle file (and directory) requests
'^\/(.*)$' => \&_handle_file,
);
}
sub _handle_file
{
my ($server, $cgi, $filename) = @_;
$filename = $server->docroot().'/'.$filename;
$filename = $PathTrimmer->trim_path($filename);
my $answer;
my $mimetype = 'text/html';
my $docroot_regex = quotemeta $server->docroot();
if (!-f $filename) {
$server->errorpage(404);
}
elsif ($filename =~ /^$docroot_regex/) {
$mimetype = mimetype($filename);
my $fh = IO::File->new('< '.$filename);
print "HTTP/1.0 200 Ok\r\n";
print $cgi->header(
-type => $mimetype,
-Content_length => -s $filename
);
print join '', <$fh>;
}
else {
$server->errorpage(404);
}
}
1;
__END__
=head1 NAME
HTTP::AppServer::Plugin::FileRetriever - Plugin for HTTP::AppServer that retrieves files from a document root.
=head1 SYNOPSIS
use HTTP::AppServer;
my $server = HTTP::AppServer->new();
$server->plugin('FileRetriever', DocRoot => '/path/to/docroot');
=head1 DESCRIPTION
Plugin for HTTP::AppServer that retrieves files from a document root.
=head2 Plugin configuration
=head3 DocRoot => I<dir>
Defines the document root directory where the files are retrieved from.
=head2 Installed URL handlers
FileRetriever handles all URLs matching '^\/(.*)$'.
It stops the server from processing any other URL handlers after that
so it is best loaded as the last one.
=head2 Installed server properties
None.
=head2 Installed server methods
None.
=head2 Handled mimetypes
Currently FileRetriever can handle HTML, CSS, JS, PNG, JPG/JPEG
and GIF files. The mimetype is determined by inspecting the
filename extension.
=head1 SEE ALSO
HTTP::AppServer, HTTP::AppServer::Plugin
=head1 AUTHOR
Tom Kirchner, E<lt>tom@tkirchner.comE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2010 by Tom Kirchner
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.
=cut
| btovar/cvmfs | test/mock_services/Services/httpd/HTTP/AppServer/Plugin/AllRetriever.pm | Perl | bsd-3-clause | 2,840 |
package Bot::Deadline;
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
use POSIX qw/ceil/;
sub new {
my ($class, %args) = @_;
return bless \%args, $class;
}
sub leftdays {
my ($self, $date) = @_;
my $event_date = localtime->strptime($date, '%Y-%m-%d');
my $current_date = localtime;
my $days = ceil(($event_date - $current_date) / ONE_DAY);
return $days >= 0 ? $days : -1;
}
1;
| akimacho/UUInfo_Bot | lib/Bot/Deadline.pm | Perl | mit | 402 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.