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 |
|---|---|---|---|---|---|
# $Id: RFC1738.pm,v 2.106 2008/05/23 21:30:10 abigail Exp $
package Regexp::Common::URI::RFC1738;
use strict;
local $^W = 1;
use Regexp::Common qw /pattern clean no_defaults/;
use vars qw /$VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS @ISA/;
use Exporter ();
@ISA = qw /Exporter/;
($VERSION) = q $Revision: 2.106 $ =~ /[\d.]+/g;
my %vars;
BEGIN {
$vars {low} = [qw /$digit $digits $hialpha $lowalpha $alpha $alphadigit
$safe $extra $national $punctuation $unreserved
$unreserved_range $reserved $uchar $uchars $xchar
$xchars $hex $escape/];
$vars {connect} = [qw /$port $hostnumber $toplabel $domainlabel $hostname
$host $hostport $user $password $login/];
$vars {parts} = [qw /$fsegment $fpath $group $article $grouppart
$search $database $wtype $wpath $psegment
$fieldname $fieldvalue $fieldspec $ppath/];
}
use vars map {@$_} values %vars;
@EXPORT = qw /$host/;
@EXPORT_OK = map {@$_} values %vars;
%EXPORT_TAGS = (%vars, ALL => [@EXPORT_OK]);
# RFC 1738, base definitions.
# Lowlevel definitions.
$digit = '[0-9]';
$digits = '[0-9]+';
$hialpha = '[A-Z]';
$lowalpha = '[a-z]';
$alpha = '[a-zA-Z]'; # lowalpha | hialpha
$alphadigit = '[a-zA-Z0-9]'; # alpha | digit
$safe = '[-$_.+]';
$extra = "[!*'(),]";
$national = '[][{}|\\^~`]';
$punctuation = '[<>#%"]';
$unreserved_range = q [-a-zA-Z0-9$_.+!*'(),]; # alphadigit | safe | extra
$unreserved = "[$unreserved_range]";
$reserved = '[;/?:@&=]';
$hex = '[a-fA-F0-9]';
$escape = "(?:%$hex$hex)";
$uchar = "(?:$unreserved|$escape)";
$uchars = "(?:(?:$unreserved+|$escape)*)";
$xchar = "(?:[$unreserved_range;/?:\@&=]|$escape)";
$xchars = "(?:(?:[$unreserved_range;/?:\@&=]+|$escape)*)";
# Connection related stuff.
$port = "(?:$digits)";
$hostnumber = "(?:$digits\[.]$digits\[.]$digits\[.]$digits)";
$toplabel = "(?:$alpha\[-a-zA-Z0-9]*$alphadigit|$alpha)";
$domainlabel = "(?:(?:$alphadigit\[-a-zA-Z0-9]*)?$alphadigit)";
$hostname = "(?:(?:$domainlabel\[.])*$toplabel)";
$host = "(?:$hostname|$hostnumber)";
$hostport = "(?:$host(?::$port)?)";
$user = "(?:(?:[$unreserved_range;?&=]+|$escape)*)";
$password = "(?:(?:[$unreserved_range;?&=]+|$escape)*)";
$login = "(?:(?:$user(?::$password)?\@)?$hostport)";
# Parts (might require more if we add more URIs).
# FTP/file
$fsegment = "(?:(?:[$unreserved_range:\@&=]+|$escape)*)";
$fpath = "(?:$fsegment(?:/$fsegment)*)";
# NNTP/news.
$group = "(?:$alpha\[-A-Za-z0-9.+_]*)";
$article = "(?:(?:[$unreserved_range;/?:&=]+|$escape)+" .
'@' . "$host)";
$grouppart = "(?:[*]|$article|$group)"; # It's important that
# $article goes before
# $group.
# WAIS.
$search = "(?:(?:[$unreserved_range;:\@&=]+|$escape)*)";
$database = $uchars;
$wtype = $uchars;
$wpath = $uchars;
# prospero
$psegment = "(?:(?:[$unreserved_range?:\@&=]+|$escape)*)";
$fieldname = "(?:(?:[$unreserved_range?:\@&]+|$escape)*)";
$fieldvalue = "(?:(?:[$unreserved_range?:\@&]+|$escape)*)";
$fieldspec = "(?:;$fieldname=$fieldvalue)";
$ppath = "(?:$psegment(?:/$psegment)*)";
1;
__END__
=pod
=head1 NAME
Regexp::Common::URI::RFC1738 -- Definitions from RFC1738;
=head1 SYNOPSIS
use Regexp::Common::URI::RFC1738 qw /:ALL/;
=head1 DESCRIPTION
This package exports definitions from RFC1738. It's intended
usage is for Regexp::Common::URI submodules only. Its interface
might change without notice.
=head1 REFERENCES
=over 4
=item B<[RFC 1738]>
Berners-Lee, Tim, Masinter, L., McCahill, M.: I<Uniform Resource
Locators (URL)>. December 1994.
=back
=head1 HISTORY
$Log: RFC1738.pm,v $
Revision 2.106 2008/05/23 21:30:10 abigail
Changed email address
Revision 2.105 2008/05/23 21:28:02 abigail
Changed license
Revision 2.104 2003/03/25 23:09:59 abigail
Prospero definitions
Revision 2.103 2003/03/12 22:29:21 abigail
Small fixes
Revision 2.102 2003/02/21 14:47:48 abigail
Added and WAIS related variables
Revision 2.101 2003/02/11 11:14:50 abigail
Fixed $grouppart
Revision 2.100 2003/02/10 21:03:54 abigail
Definitions of RFC 1738
=head1 AUTHOR
Abigail S<(I<regexp-common@abigail.be>)>.
=head1 BUGS AND IRRITATIONS
Bound to be plenty.
=head1 COPYRIGHT
This software is Copyright (c) 2001 - 2008, Damian Conway and Abigail.
This module is free software, and maybe used under any of the following
licenses:
1) The Perl Artistic License. See the file COPYRIGHT.AL.
2) The Perl Artistic License 2.0. See the file COPYRIGHT.AL2.
3) The BSD Licence. See the file COPYRIGHT.BSD.
4) The MIT Licence. See the file COPYRIGHT.MIT.
=cut
| schwern/Regexp-Common | lib/Regexp/Common/URI/RFC1738.pm | Perl | mit | 5,308 |
=pod
=head1 NAME
RSA_padding_add_PKCS1_type_1, RSA_padding_check_PKCS1_type_1,
RSA_padding_add_PKCS1_type_2, RSA_padding_check_PKCS1_type_2,
RSA_padding_add_PKCS1_OAEP, RSA_padding_check_PKCS1_OAEP,
RSA_padding_add_SSLv23, RSA_padding_check_SSLv23,
RSA_padding_add_none, RSA_padding_check_none - asymmetric encryption
padding
=head1 SYNOPSIS
#include <openssl/rsa.h>
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
unsigned char *f, int fl);
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
unsigned char *f, int fl, unsigned char *p, int pl);
int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen,
unsigned char *f, int fl, int rsa_len, unsigned char *p, int pl);
int RSA_padding_add_SSLv23(unsigned char *to, int tlen,
unsigned char *f, int fl);
int RSA_padding_check_SSLv23(unsigned char *to, int tlen,
unsigned char *f, int fl, int rsa_len);
int RSA_padding_add_none(unsigned char *to, int tlen,
unsigned char *f, int fl);
int RSA_padding_check_none(unsigned char *to, int tlen,
unsigned char *f, int fl, int rsa_len);
=head1 DESCRIPTION
The RSA_padding_xxx_xxx() functions are called from the RSA encrypt,
decrypt, sign and verify functions. Normally they should not be called
from application programs.
However, they can also be called directly to implement padding for other
asymmetric ciphers. RSA_padding_add_PKCS1_OAEP() and
RSA_padding_check_PKCS1_OAEP() may be used in an application combined
with B<RSA_NO_PADDING> in order to implement OAEP with an encoding
parameter.
RSA_padding_add_xxx() encodes B<fl> bytes from B<f> so as to fit into
B<tlen> bytes and stores the result at B<to>. An error occurs if B<fl>
does not meet the size requirements of the encoding method.
The following encoding methods are implemented:
=over 4
=item PKCS1_type_1
PKCS #1 v2.0 EMSA-PKCS1-v1_5 (PKCS #1 v1.5 block type 1); used for signatures
=item PKCS1_type_2
PKCS #1 v2.0 EME-PKCS1-v1_5 (PKCS #1 v1.5 block type 2)
=item PKCS1_OAEP
PKCS #1 v2.0 EME-OAEP
=item SSLv23
PKCS #1 EME-PKCS1-v1_5 with SSL-specific modification
=item none
simply copy the data
=back
The random number generator must be seeded prior to calling
RSA_padding_add_xxx().
RSA_padding_check_xxx() verifies that the B<fl> bytes at B<f> contain
a valid encoding for a B<rsa_len> byte RSA key in the respective
encoding method and stores the recovered data of at most B<tlen> bytes
(for B<RSA_NO_PADDING>: of size B<tlen>)
at B<to>.
For RSA_padding_xxx_OAEP(), B<p> points to the encoding parameter
of length B<pl>. B<p> may be B<NULL> if B<pl> is 0.
=head1 RETURN VALUES
The RSA_padding_add_xxx() functions return 1 on success, 0 on error.
The RSA_padding_check_xxx() functions return the length of the
recovered data, -1 on error. Error codes can be obtained by calling
L<ERR_get_error(3)>.
=head1 WARNING
The RSA_padding_check_PKCS1_type_2() padding check leaks timing
information which can potentially be used to mount a Bleichenbacher
padding oracle attack. This is an inherent weakness in the PKCS #1
v1.5 padding design. Prefer PKCS1_OAEP padding.
=head1 SEE ALSO
L<RSA_public_encrypt(3)>,
L<RSA_private_decrypt(3)>,
L<RSA_sign(3)>, L<RSA_verify(3)>
=head1 COPYRIGHT
Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| google/google-ctf | third_party/edk2/CryptoPkg/Library/OpensslLib/openssl/doc/crypto/RSA_padding_add_PKCS1_type_1.pod | Perl | apache-2.0 | 3,878 |
#
# 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 hardware::server::hp::proliant::snmp::mode::components::daacc;
use strict;
use warnings;
my %map_daacc_status = (
1 => 'other',
2 => 'invalid',
3 => 'enabled',
4 => 'tmpDisabled',
5 => 'permDisabled',
);
my %map_daacc_condition = (
1 => 'other',
2 => 'ok',
3 => 'degraded',
4 => 'failed',
);
my %map_daaccbattery_condition = (
1 => 'other',
2 => 'ok',
3 => 'recharging',
4 => 'failed',
5 => 'degraded',
6 => 'not present',
);
# In 'CPQIDA-MIB.mib'
my $mapping = {
cpqDaAccelStatus => { oid => '.1.3.6.1.4.1.232.3.2.2.2.1.2', map => \%map_daacc_status },
};
my $mapping2 = {
cpqDaAccelBattery => { oid => '.1.3.6.1.4.1.232.3.2.2.2.1.6', map => \%map_daaccbattery_condition },
};
my $mapping3 = {
cpqDaAccelCondition => { oid => '.1.3.6.1.4.1.232.3.2.2.2.1.9', map => \%map_daacc_condition },
};
my $oid_cpqDaAccelStatus = '.1.3.6.1.4.1.232.3.2.2.2.1.2';
my $oid_cpqDaAccelBattery = '.1.3.6.1.4.1.232.3.2.2.2.1.6';
my $oid_cpqDaAccelCondition = '.1.3.6.1.4.1.232.3.2.2.2.1.9';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_cpqDaAccelStatus }, { oid => $oid_cpqDaAccelBattery }, { oid => $oid_cpqDaAccelCondition };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking da accelerator boards");
$self->{components}->{daacc} = {name => 'da accelerator boards', total => 0, skip => 0};
return if ($self->check_filter(section => 'daacc'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_cpqDaAccelCondition}})) {
next if ($oid !~ /^$mapping3->{cpqDaAccelCondition}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_cpqDaAccelStatus}, instance => $instance);
my $result2 = $self->{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$oid_cpqDaAccelBattery}, instance => $instance);
my $result3 = $self->{snmp}->map_instance(mapping => $mapping3, results => $self->{results}->{$oid_cpqDaAccelCondition}, instance => $instance);
next if ($self->check_filter(section => 'daacc', instance => $instance));
$self->{components}->{daacc}->{total}++;
$self->{output}->output_add(long_msg => sprintf("da controller accelerator '%s' [status: %s, battery status: %s] condition is %s.",
$instance, $result->{cpqDaAccelStatus}, $result2->{cpqDaAccelBattery},
$result3->{cpqDaAccelCondition}));
my $exit = $self->get_severity(label => 'default', section => 'daacc', value => $result3->{cpqDaAccelCondition});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("da controller accelerator '%s' is %s",
$instance, $result3->{cpqDaAccelCondition}));
}
$exit = $self->get_severity(section => 'daaccbattery', value => $result2->{cpqDaAccelBattery});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("da controller accelerator '%s' battery is %s",
$instance, $result2->{cpqDaAccelBattery}));
}
}
}
1; | maksimatveev/centreon-plugins | hardware/server/hp/proliant/snmp/mode/components/daacc.pm | Perl | apache-2.0 | 4,333 |
#!/usr/bin/env perl
use strict;
use warnings;
use FindBin;
use lib ("$FindBin::Bin/../PerlLib");
use Gene_obj;
use Gene_obj_indexer;
use GFF3_utils;
use Carp;
$|++;
my $usage = "\n\nusage: $0 gff3_file\n\n";
my $gff3_file = $ARGV[0] or die $usage;
main: {
my $gene_obj_indexer_href = {};
my $asmbl_id_to_gene_list_href = &GFF3_utils::index_GFF3_gene_objs($gff3_file, $gene_obj_indexer_href);
foreach my $asmbl_id (sort keys %$asmbl_id_to_gene_list_href) {
my @gene_ids = @{$asmbl_id_to_gene_list_href->{$asmbl_id}};
#print "ASMBL: $asmbl_id, gene_ids: @gene_ids\n";
my @gene_entries;
foreach my $gene_id (@gene_ids) {
my $gene_obj_ref = $gene_obj_indexer_href->{$gene_id};
my ($lend, $rend) = sort {$a<=>$b} $gene_obj_ref->get_coords();
my $struct = { gene_obj => $gene_obj_ref,
lend => $lend,
rend => $rend,
length => $rend - $lend + 1,
};
push (@gene_entries, $struct);
}
@gene_entries = reverse sort {$a->{length}<=>$b->{length}} @gene_entries;
my @largest_orfs = shift @gene_entries;
while (@gene_entries) {
my $next_gene = shift @gene_entries;
my ($next_lend, $next_rend) = ($next_gene->{lend}, $next_gene->{rend});
my $found_eclipsed = 0;
foreach my $gene (@largest_orfs) {
my ($lend, $rend) = ($gene->{lend}, $gene->{rend});
if ($next_lend > $lend && $next_rend < $rend) {
## eclipsed
$found_eclipsed = 1;
last;
}
}
unless ($found_eclipsed) {
push (@largest_orfs, $next_gene);
}
}
foreach my $struct (@largest_orfs) {
my $gene_obj = $struct->{gene_obj};
print $gene_obj->to_GFF3_format() . "\n";
}
}
exit(0);
}
| shujishigenobu/OkORF | util/remove_eclipsed_ORFs.pl | Perl | mit | 2,317 |
########################################################################
# Bio::KBase::ObjectAPI::KBaseGenomes::Feature - This is the moose object corresponding to the Feature object
# Authors: Christopher Henry, Scott Devoid, Paul Frybarger
# Contact email: chenry@mcs.anl.gov
# Development location: Mathematics and Computer Science Division, Argonne National Lab
# Date of module creation: 2012-03-26T23:22:35
########################################################################
use strict;
use Bio::KBase::ObjectAPI::KBaseGenomes::DB::Feature;
package Bio::KBase::ObjectAPI::KBaseGenomes::Feature;
use Moose;
use namespace::autoclean;
extends 'Bio::KBase::ObjectAPI::KBaseGenomes::DB::Feature';
#***********************************************************************************************************
# ADDITIONAL ATTRIBUTES:
#***********************************************************************************************************
has genomeID => ( is => 'rw',printOrder => 2, isa => 'Str', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildgenomeID' );
has roleList => ( is => 'rw',printOrder => 8, isa => 'Str', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildroleList' );
has compartments => ( is => 'rw',printOrder => -1, isa => 'ArrayRef', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildcompartments' );
has comment => ( is => 'rw',printOrder => 2, isa => 'Str', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildcomment' );
has delimiter => ( is => 'rw',printOrder => 2, isa => 'Str', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_builddelimiter' );
has roles => ( is => 'rw', isa => 'ArrayRef',printOrder => -1, type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildroles' );
has start => ( is => 'rw', isa => 'Str',printOrder => 3, type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildstart' );
has stop => ( is => 'rw', isa => 'Str',printOrder => 4, type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildstop' );
has direction => ( is => 'rw', isa => 'Str',printOrder => 5, type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_builddirection' );
has contig => ( is => 'rw', isa => 'Str',printOrder => 6, type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildcontig' );
#***********************************************************************************************************
# BUILDERS:
#***********************************************************************************************************
sub _buildgenomeID {
my ($self) = @_;
return $self->parent()->id();
}
sub _buildstart {
my ($self) = @_;
return $self->location()->[0]->[1];
}
sub _buildstop {
my ($self) = @_;
if ($self->direction() eq "+") {
return $self->start() + $self->location()->[0]->[3];
}
return $self->start() - $self->location()->[0]->[3];
}
sub _builddirection {
my ($self) = @_;
return $self->location()->[0]->[2];
}
sub _buildcontig {
my ($self) = @_;
return $self->location()->[0]->[0];
}
sub _buildroleList {
my ($self) = @_;
my $roleList = "";
my $roles = $self->roles();
for (my $i=0; $i < @{$roles}; $i++) {
if (length($roleList) > 0) {
$roleList .= ";";
}
$roleList .= $roles->[$i];
}
return $roleList;
}
sub _buildcompartments {
my ($self) = @_;
$self->_functionparse();
return $self->compartments();
}
sub _buildcomment {
my ($self) = @_;
$self->_functionparse();
return $self->comment();
}
sub _builddelimiter {
my ($self) = @_;
$self->_functionparse();
return $self->delimiter();
}
sub _buildroles {
my ($self) = @_;
$self->_functionparse();
return $self->roles();
}
sub _functionparse {
my ($self) = @_;
$self->compartments(["u"]);
$self->roles([]);
$self->delimiter("none");
$self->comment("none");
my $compartmentTranslation = {
"cytosolic" => "c",
"plastidial" => "d",
"mitochondrial" => "m",
"peroxisomal" => "x",
"lysosomal" => "l",
"vacuolar" => "v",
"nuclear" => "n",
"plasma\\smembrane" => "p",
"cell\\swall" => "w",
"golgi\\sapparatus" => "g",
"endoplasmic\\sreticulum" => "r",
extracellular => "e",
cellwall => "w",
periplasm => "p",
cytosol => "c",
golgi => "g",
endoplasm => "r",
lysosome => "l",
nucleus => "n",
chloroplast => "h",
mitochondria => "m",
peroxisome => "x",
vacuole => "v",
plastid => "d",
unknown => "u"
};
if (!defined($self->function()) || length($self->function()) eq 0) {
$self->roles([]);
$self->compartments([]);
$self->delimiter(";");
$self->comment("No annotated function");
return;
}
my $function = $self->function();
my $array = [split(/\#/,$function)];
$function = shift(@{$array});
$function =~ s/\s+$//;
$self->comment(join("#",@{$array}));
my $compHash = {};
if (length($self->comment()) > 0) {
foreach my $comp (keys(%{$compartmentTranslation})) {
if ($self->comment() =~ /$comp/) {
$compHash->{$compartmentTranslation->{$comp}} = 1;
}
}
}
if (keys(%{$compHash}) > 0) {
$self->compartments([keys(%{$compHash})]);
}
if ($function =~ /\s*;\s/) {
$self->delimiter(";");
}
if ($function =~ /s+\@\s+/) {
$self->delimiter("\@");
}
if ($function =~ /s+\/\s+/) {
$self->delimiter("/");
}
$self->roles([split(/\s*;\s+|\s+[\@\/]\s+/,$function)]);
}
#***********************************************************************************************************
# CONSTANTS:
#***********************************************************************************************************
my @aa_1_letter_order = qw( A C D E F G H I K L M N P Q R S T V W Y ); # Alpha by 1 letter
my @aa_3_letter_order = qw( A R N D C Q E G H I L K M F P S T W Y V ); # PAM matrix order
my @aa_n_codon_order = qw( L R S A G P T V I C D E F H K N Q Y M W );
my %genetic_code = (
# DNA version
TTT => 'F', TCT => 'S', TAT => 'Y', TGT => 'C',
TTC => 'F', TCC => 'S', TAC => 'Y', TGC => 'C',
TTA => 'L', TCA => 'S', TAA => '*', TGA => '*',
TTG => 'L', TCG => 'S', TAG => '*', TGG => 'W',
CTT => 'L', CCT => 'P', CAT => 'H', CGT => 'R',
CTC => 'L', CCC => 'P', CAC => 'H', CGC => 'R',
CTA => 'L', CCA => 'P', CAA => 'Q', CGA => 'R',
CTG => 'L', CCG => 'P', CAG => 'Q', CGG => 'R',
ATT => 'I', ACT => 'T', AAT => 'N', AGT => 'S',
ATC => 'I', ACC => 'T', AAC => 'N', AGC => 'S',
ATA => 'I', ACA => 'T', AAA => 'K', AGA => 'R',
ATG => 'M', ACG => 'T', AAG => 'K', AGG => 'R',
GTT => 'V', GCT => 'A', GAT => 'D', GGT => 'G',
GTC => 'V', GCC => 'A', GAC => 'D', GGC => 'G',
GTA => 'V', GCA => 'A', GAA => 'E', GGA => 'G',
GTG => 'V', GCG => 'A', GAG => 'E', GGG => 'G',
# The following ambiguous encodings are not necessary, but
# speed up the processing of some ambiguous triplets:
TTY => 'F', TCY => 'S', TAY => 'Y', TGY => 'C',
TTR => 'L', TCR => 'S', TAR => '*',
TCN => 'S',
CTY => 'L', CCY => 'P', CAY => 'H', CGY => 'R',
CTR => 'L', CCR => 'P', CAR => 'Q', CGR => 'R',
CTN => 'L', CCN => 'P', CGN => 'R',
ATY => 'I', ACY => 'T', AAY => 'N', AGY => 'S',
ACR => 'T', AAR => 'K', AGR => 'R',
ACN => 'T',
GTY => 'V', GCY => 'A', GAY => 'D', GGY => 'G',
GTR => 'V', GCR => 'A', GAR => 'E', GGR => 'G',
GTN => 'V', GCN => 'A', GGN => 'G'
);
# Add RNA by construction:
foreach ( grep { /T/ } keys %genetic_code )
{
my $codon = $_;
$codon =~ s/T/U/g;
$genetic_code{ $codon } = lc $genetic_code{ $_ }
}
# Add lower case by construction:
foreach ( keys %genetic_code )
{
$genetic_code{ lc $_ } = lc $genetic_code{ $_ }
}
# Construct the genetic code with selenocysteine by difference:
my %genetic_code_with_U = %genetic_code;
$genetic_code_with_U{ TGA } = 'U';
$genetic_code_with_U{ tga } = 'u';
$genetic_code_with_U{ UGA } = 'U';
$genetic_code_with_U{ uga } = 'u';
my %amino_acid_codons_DNA = (
L => [ qw( TTA TTG CTA CTG CTT CTC ) ],
R => [ qw( AGA AGG CGA CGG CGT CGC ) ],
S => [ qw( AGT AGC TCA TCG TCT TCC ) ],
A => [ qw( GCA GCG GCT GCC ) ],
G => [ qw( GGA GGG GGT GGC ) ],
P => [ qw( CCA CCG CCT CCC ) ],
T => [ qw( ACA ACG ACT ACC ) ],
V => [ qw( GTA GTG GTT GTC ) ],
I => [ qw( ATA ATT ATC ) ],
C => [ qw( TGT TGC ) ],
D => [ qw( GAT GAC ) ],
E => [ qw( GAA GAG ) ],
F => [ qw( TTT TTC ) ],
H => [ qw( CAT CAC ) ],
K => [ qw( AAA AAG ) ],
N => [ qw( AAT AAC ) ],
Q => [ qw( CAA CAG ) ],
Y => [ qw( TAT TAC ) ],
M => [ qw( ATG ) ],
U => [ qw( TGA ) ],
W => [ qw( TGG ) ],
l => [ qw( tta ttg cta ctg ctt ctc ) ],
r => [ qw( aga agg cga cgg cgt cgc ) ],
s => [ qw( agt agc tca tcg tct tcc ) ],
a => [ qw( gca gcg gct gcc ) ],
g => [ qw( gga ggg ggt ggc ) ],
p => [ qw( cca ccg cct ccc ) ],
t => [ qw( aca acg act acc ) ],
v => [ qw( gta gtg gtt gtc ) ],
i => [ qw( ata att atc ) ],
c => [ qw( tgt tgc ) ],
d => [ qw( gat gac ) ],
e => [ qw( gaa gag ) ],
f => [ qw( ttt ttc ) ],
h => [ qw( cat cac ) ],
k => [ qw( aaa aag ) ],
n => [ qw( aat aac ) ],
q => [ qw( caa cag ) ],
y => [ qw( tat tac ) ],
m => [ qw( atg ) ],
u => [ qw( tga ) ],
w => [ qw( tgg ) ],
'*' => [ qw( TAA TAG TGA ) ]
);
my %amino_acid_codons_RNA = (
L => [ qw( UUA UUG CUA CUG CUU CUC ) ],
R => [ qw( AGA AGG CGA CGG CGU CGC ) ],
S => [ qw( AGU AGC UCA UCG UCU UCC ) ],
A => [ qw( GCA GCG GCU GCC ) ],
G => [ qw( GGA GGG GGU GGC ) ],
P => [ qw( CCA CCG CCU CCC ) ],
T => [ qw( ACA ACG ACU ACC ) ],
V => [ qw( GUA GUG GUU GUC ) ],
B => [ qw( GAU GAC AAU AAC ) ],
Z => [ qw( GAA GAG CAA CAG ) ],
I => [ qw( AUA AUU AUC ) ],
C => [ qw( UGU UGC ) ],
D => [ qw( GAU GAC ) ],
E => [ qw( GAA GAG ) ],
F => [ qw( UUU UUC ) ],
H => [ qw( CAU CAC ) ],
K => [ qw( AAA AAG ) ],
N => [ qw( AAU AAC ) ],
Q => [ qw( CAA CAG ) ],
Y => [ qw( UAU UAC ) ],
M => [ qw( AUG ) ],
U => [ qw( UGA ) ],
W => [ qw( UGG ) ],
l => [ qw( uua uug cua cug cuu cuc ) ],
r => [ qw( aga agg cga cgg cgu cgc ) ],
s => [ qw( agu agc uca ucg ucu ucc ) ],
a => [ qw( gca gcg gcu gcc ) ],
g => [ qw( gga ggg ggu ggc ) ],
p => [ qw( cca ccg ccu ccc ) ],
t => [ qw( aca acg acu acc ) ],
v => [ qw( gua gug guu guc ) ],
b => [ qw( gau gac aau aac ) ],
z => [ qw( gaa gag caa cag ) ],
i => [ qw( aua auu auc ) ],
c => [ qw( ugu ugc ) ],
d => [ qw( gau gac ) ],
e => [ qw( gaa gag ) ],
f => [ qw( uuu uuc ) ],
h => [ qw( cau cac ) ],
k => [ qw( aaa aag ) ],
n => [ qw( aau aac ) ],
q => [ qw( caa cag ) ],
y => [ qw( uau uac ) ],
m => [ qw( aug ) ],
u => [ qw( uga ) ],
w => [ qw( ugg ) ],
'*' => [ qw( UAA UAG UGA ) ]
);
my %n_codon_for_aa = map {
$_ => scalar @{ $amino_acid_codons_DNA{ $_ } }
} keys %amino_acid_codons_DNA;
my %reverse_genetic_code_DNA = (
A => "GCN", a => "gcn",
C => "TGY", c => "tgy",
D => "GAY", d => "gay",
E => "GAR", e => "gar",
F => "TTY", f => "tty",
G => "GGN", g => "ggn",
H => "CAY", h => "cay",
I => "ATH", i => "ath",
K => "AAR", k => "aar",
L => "YTN", l => "ytn",
M => "ATG", m => "atg",
N => "AAY", n => "aay",
P => "CCN", p => "ccn",
Q => "CAR", q => "car",
R => "MGN", r => "mgn",
S => "WSN", s => "wsn",
T => "ACN", t => "acn",
U => "TGA", u => "tga",
V => "GTN", v => "gtn",
W => "TGG", w => "tgg",
X => "NNN", x => "nnn",
Y => "TAY", y => "tay",
'*' => "TRR"
);
my %reverse_genetic_code_RNA = (
A => "GCN", a => "gcn",
C => "UGY", c => "ugy",
D => "GAY", d => "gay",
E => "GAR", e => "gar",
F => "UUY", f => "uuy",
G => "GGN", g => "ggn",
H => "CAY", h => "cay",
I => "AUH", i => "auh",
K => "AAR", k => "aar",
L => "YUN", l => "yun",
M => "AUG", m => "aug",
N => "AAY", n => "aay",
P => "CCN", p => "ccn",
Q => "CAR", q => "car",
R => "MGN", r => "mgn",
S => "WSN", s => "wsn",
T => "ACN", t => "acn",
U => "UGA", u => "uga",
V => "GUN", v => "gun",
W => "UGG", w => "ugg",
X => "NNN", x => "nnn",
Y => "UAY", y => "uay",
'*' => "URR"
);
my %DNA_letter_can_be = (
A => ["A"], a => ["a"],
B => ["C", "G", "T"], b => ["c", "g", "t"],
C => ["C"], c => ["c"],
D => ["A", "G", "T"], d => ["a", "g", "t"],
G => ["G"], g => ["g"],
H => ["A", "C", "T"], h => ["a", "c", "t"],
K => ["G", "T"], k => ["g", "t"],
M => ["A", "C"], m => ["a", "c"],
N => ["A", "C", "G", "T"], n => ["a", "c", "g", "t"],
R => ["A", "G"], r => ["a", "g"],
S => ["C", "G"], s => ["c", "g"],
T => ["T"], t => ["t"],
U => ["T"], u => ["t"],
V => ["A", "C", "G"], v => ["a", "c", "g"],
W => ["A", "T"], w => ["a", "t"],
Y => ["C", "T"], y => ["c", "t"]
);
my %RNA_letter_can_be = (
A => ["A"], a => ["a"],
B => ["C", "G", "U"], b => ["c", "g", "u"],
C => ["C"], c => ["c"],
D => ["A", "G", "U"], d => ["a", "g", "u"],
G => ["G"], g => ["g"],
H => ["A", "C", "U"], h => ["a", "c", "u"],
K => ["G", "U"], k => ["g", "u"],
M => ["A", "C"], m => ["a", "c"],
N => ["A", "C", "G", "U"], n => ["a", "c", "g", "u"],
R => ["A", "G"], r => ["a", "g"],
S => ["C", "G"], s => ["c", "g"],
T => ["U"], t => ["u"],
U => ["U"], u => ["u"],
V => ["A", "C", "G"], v => ["a", "c", "g"],
W => ["A", "U"], w => ["a", "u"],
Y => ["C", "U"], y => ["c", "u"]
);
my %one_letter_to_three_letter_aa = (
A => "Ala", a => "Ala",
B => "Asx", b => "Asx",
C => "Cys", c => "Cys",
D => "Asp", d => "Asp",
E => "Glu", e => "Glu",
F => "Phe", f => "Phe",
G => "Gly", g => "Gly",
H => "His", h => "His",
I => "Ile", i => "Ile",
K => "Lys", k => "Lys",
L => "Leu", l => "Leu",
M => "Met", m => "Met",
N => "Asn", n => "Asn",
P => "Pro", p => "Pro",
Q => "Gln", q => "Gln",
R => "Arg", r => "Arg",
S => "Ser", s => "Ser",
T => "Thr", t => "Thr",
U => "Sec", u => "Sec",
V => "Val", v => "Val",
W => "Trp", w => "Trp",
X => "Xxx", x => "Xxx",
Y => "Tyr", y => "Tyr",
Z => "Glx", z => "Glx",
'*' => "***"
);
my %three_letter_to_one_letter_aa = (
ALA => "A", Ala => "A", ala => "a",
ARG => "R", Arg => "R", arg => "r",
ASN => "N", Asn => "N", asn => "n",
ASP => "D", Asp => "D", asp => "d",
ASX => "B", Asx => "B", asx => "b",
CYS => "C", Cys => "C", cys => "c",
GLN => "Q", Gln => "Q", gln => "q",
GLU => "E", Glu => "E", glu => "e",
GLX => "Z", Glx => "Z", glx => "z",
GLY => "G", Gly => "G", gly => "g",
HIS => "H", His => "H", his => "h",
ILE => "I", Ile => "I", ile => "i",
LEU => "L", Leu => "L", leu => "l",
LYS => "K", Lys => "K", lys => "k",
MET => "M", Met => "M", met => "m",
PHE => "F", Phe => "F", phe => "f",
PRO => "P", Pro => "P", pro => "p",
SEC => "U", Sec => "U", sec => "u",
SER => "S", Ser => "S", ser => "s",
THR => "T", Thr => "T", thr => "t",
TRP => "W", Trp => "W", trp => "w",
TYR => "Y", Tyr => "Y", tyr => "y",
VAL => "V", Val => "V", val => "v",
XAA => "X", Xaa => "X", xaa => "x",
XXX => "X", Xxx => "X", xxx => "x",
'***' => "*"
);
#***********************************************************************************************************
# FUNCTIONS:
#***********************************************************************************************************
=head3 integrate_sequence_from_contigs
Definition:
$self->integrate_sequence_from_contigs(Bio::KBase::ObjectAPI::KBaseGenomes::ContigSet);
Description:
Loads contigs into gene feature data
=cut
sub integrate_contigs {
my($self,$contigobj) = @_;
if (defined($self->location()->[0])) {
my $contig = $contigobj->getObject("contigs",$self->location()->[0]->[0]);
if (defined($contig)) {
my $seq;
if ($self->location()->[0]->[2] eq "-") {
$seq = scalar reverse substr($contig->sequence(),$self->location()->[0]->[1]-$self->location()->[0]->[3],$self->location()->[0]->[3]);
$seq =~ s/A/M/g;
$seq =~ s/a/m/g;
$seq =~ s/T/A/g;
$seq =~ s/t/a/g;
$seq =~ s/M/T/g;
$seq =~ s/m/t/g;
$seq =~ s/G/M/g;
$seq =~ s/g/m/g;
$seq =~ s/C/G/g;
$seq =~ s/c/g/g;
$seq =~ s/M/C/g;
$seq =~ s/m/c/g;
} else {
$seq = substr($contig->sequence(),$self->location()->[0]->[1]-1,$self->location()->[0]->[3]);
}
$self->dna_sequence($seq);
$self->dna_sequence_length(length($self->dna_sequence()));
}
}
my $proteinSeq = $self->translate_seq($self->dna_sequence());
$proteinSeq =~ s/[xX]+$//;
$self->protein_translation($proteinSeq);
$self->protein_translation_length(length($self->protein_translation()));
$self->md5(Digest::MD5::md5_hex($self->protein_translation()));
}
=head3 translate_seq
Definition:
$self->translate_seq(string);
Description:
Translates input DNA sequence into protein sequence
=cut
sub translate_seq {
my($self,$seq) = @_;
$seq =~ tr/-//d; # remove gaps
my @codons = $seq =~ m/(...?)/g; # Will try to translate last 2 nt
# A second argument that is true forces first amino acid to be Met
my @met;
if ( ( shift @_ ) && ( my $codon1 = shift @codons ) )
{
push @met, ( $codon1 =~ /[a-z]/ ? 'm' : 'M' );
}
join( '', @met, map { translate_codon( $_ ) } @codons )
}
sub translate_codon {
my $codon = shift;
$codon =~ tr/Uu/Tt/; # Make it DNA
# Try a simple lookup:
my $aa;
if ( $aa = $genetic_code{ $codon } ) { return $aa }
# Attempt to recover from mixed-case codons:
$codon = ( $codon =~ /[a-z]/ ) ? lc $codon : uc $codon;
if ( $aa = $genetic_code{ $codon } ) { return $aa }
# The code defined above catches simple N, R and Y ambiguities in the
# third position. Other codons (e.g., GG[KMSWBDHV], or even GG) might
# be unambiguously translated by converting the last position to N and
# seeing if this is in the code table:
my $N = ( $codon =~ /[a-z]/ ) ? 'n' : 'N';
if ( $aa = $genetic_code{ substr($codon,0,2) . $N } ) { return $aa }
# Test that codon is valid for an unambiguous aa:
my $X = ( $codon =~ /[a-z]/ ) ? 'x' : 'X';
if ( $codon !~ m/^[ACGTMY][ACGT][ACGTKMRSWYBDHVN]$/i
&& $codon !~ m/^YT[AGR]$/i # Leu YTR
&& $codon !~ m/^MG[AGR]$/i # Arg MGR
)
{
return $X;
}
# Expand all ambiguous nucleotides to see if they all yield same aa.
my @n1 = @{ $DNA_letter_can_be{ substr( $codon, 0, 1 ) } };
my $n2 = substr( $codon, 1, 1 );
my @n3 = @{ $DNA_letter_can_be{ substr( $codon, 2, 1 ) } };
my @triples = map { my $n12 = $_ . $n2; map { $n12 . $_ } @n3 } @n1;
my $triple = shift @triples;
$aa = $genetic_code{ $triple };
$aa or return $X;
foreach $triple ( @triples ) { return $X if $aa ne $genetic_code{$triple} }
return $aa;
}
sub modify {
my($self,$parameters) = @_;
$parameters = Bio::KBase::ObjectAPI::utilities::args([], {
function => undef,
type => undef,
aliases => [],
publications => [],
annotations => [],
protein_translation => undef,
dna_sequence => undef,
locations => undef
}, $parameters );
my $list = ["function","type","protein_translation","dna_sequence","locations"];
foreach my $item (@{$list}) {
if (defined($parameters->{$item})) {
print $item."\t".$parameters->{$item}."\t";
$self->$item($parameters->{$item});
}
}
print $self->function()."\n";
$list = ["aliases","publications","annotations"];
foreach my $item (@{$list}) {
if (defined($parameters->{$item}->[0])) {
push(@{$self->$item()},@{$parameters->{$item}});
}
}
}
__PACKAGE__->meta->make_immutable;
1;
| kbase/KBaseFBAModeling | lib/Bio/KBase/ObjectAPI/KBaseGenomes/Feature.pm | Perl | mit | 21,696 |
+{
locale_version => 0.93,
entry => <<'ENTRY', # for DUCET v6.2.0
00E4 ; [.15EF.0021.0002.00E4][.164C.0021.0002.00E4] # LATIN SMALL LETTER A WITH DIAERESIS
0061 0308 ; [.15EF.0021.0002.00E4][.164C.0021.0002.00E4] # LATIN SMALL LETTER A WITH DIAERESIS
00C4 ; [.15EF.0021.0008.00C4][.164C.0021.0008.00C4] # LATIN CAPITAL LETTER A WITH DIAERESIS
0041 0308 ; [.15EF.0021.0008.00C4][.164C.0021.0008.00C4] # LATIN CAPITAL LETTER A WITH DIAERESIS
01DF ; [.15EF.0021.0002.00E4][.164C.0021.0002.00E4][.0000.005B.0002.0304] # LATIN SMALL LETTER A WITH DIAERESIS AND MACRON
01DE ; [.15EF.0021.0008.00C4][.164C.0021.0008.00C4][.0000.005B.0002.0304] # LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON
00F6 ; [.1771.0021.0002.00F6][.164C.0021.0002.00F6] # LATIN SMALL LETTER O WITH DIAERESIS
006F 0308 ; [.1771.0021.0002.00F6][.164C.0021.0002.00F6] # LATIN SMALL LETTER O WITH DIAERESIS
00D6 ; [.1771.0021.0008.00D6][.164C.0021.0008.00D6] # LATIN CAPITAL LETTER O WITH DIAERESIS
004F 0308 ; [.1771.0021.0008.00D6][.164C.0021.0008.00D6] # LATIN CAPITAL LETTER O WITH DIAERESIS
022B ; [.1771.0021.0002.00F6][.164C.0021.0002.00F6][.0000.005B.0002.0304] # LATIN SMALL LETTER O WITH DIAERESIS AND MACRON
022A ; [.1771.0021.0008.00D6][.164C.0021.0008.00D6][.0000.005B.0002.0304] # LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON
00FC ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC] # LATIN SMALL LETTER U WITH DIAERESIS
0075 0308 ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC] # LATIN SMALL LETTER U WITH DIAERESIS
00DC ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC] # LATIN CAPITAL LETTER U WITH DIAERESIS
0055 0308 ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC] # LATIN CAPITAL LETTER U WITH DIAERESIS
01DC ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC][.0000.0035.0002.0300] # LATIN SMALL LETTER U WITH DIAERESIS AND GRAVE
01DB ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC][.0000.0035.0002.0300] # LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE
01D8 ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC][.0000.0032.0002.0301] # LATIN SMALL LETTER U WITH DIAERESIS AND ACUTE
01D7 ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC][.0000.0032.0002.0301] # LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE
01D6 ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC][.0000.005B.0002.0304] # LATIN SMALL LETTER U WITH DIAERESIS AND MACRON
01D5 ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC][.0000.005B.0002.0304] # LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON
01DA ; [.1836.0021.0002.00FC][.164C.0021.0002.00FC][.0000.0041.0002.030C] # LATIN SMALL LETTER U WITH DIAERESIS AND CARON
01D9 ; [.1836.0021.0008.00DC][.164C.0021.0008.00DC][.0000.0041.0002.030C] # LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON
ENTRY
};
| Dokaponteam/ITF_Project | xampp/perl/lib/Unicode/Collate/Locale/de_phone.pl | Perl | mit | 2,775 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
10B00 10B3F
END
| liuyangning/WX_web | xampp/perl/lib/unicore/lib/Blk/Avestan.pl | Perl | mit | 423 |
#!/usr/bin/perl -w
use strict;
# use of SRCDIR/SUBDIR is required for supporting VPath builds
my $srcdir = $ENV{'SRCDIR'} or die 'SRCDIR environment variable is not set';
my $subdir = $ENV{'SUBDIR'} or die 'SUBDIR environment variable is not set';
my $regress_in = "$srcdir/$subdir/regress.in";
my $expected_out = "$srcdir/$subdir/expected.out";
# the output file should land in the build_dir of VPath, or just in
# the current dir, if VPath isn't used
my $regress_out = "regress.out";
# open input file first, so possible error isn't sent to redirected STDERR
open(REGRESS_IN, "<", $regress_in)
or die "can't open $regress_in for reading: $!";
# save STDOUT/ERR and redirect both to regress.out
open(OLDOUT, ">&", \*STDOUT) or die "can't dup STDOUT: $!";
open(OLDERR, ">&", \*STDERR) or die "can't dup STDERR: $!";
open(STDOUT, ">", $regress_out)
or die "can't open $regress_out for writing: $!";
open(STDERR, ">&", \*STDOUT) or die "can't dup STDOUT: $!";
# read lines from regress.in and run uri-regress on them
while (<REGRESS_IN>)
{
chomp;
print "trying $_\n";
system("./uri-regress \"$_\"");
print "\n";
}
# restore STDOUT/ERR so we can print the outcome to the user
open(STDERR, ">&", \*OLDERR) or die; # can't complain as STDERR is still duped
open(STDOUT, ">&", \*OLDOUT) or die "can't restore STDOUT: $!";
# just in case
close REGRESS_IN;
my $diff_status = system(
"diff -c \"$srcdir/$subdir/expected.out\" regress.out >regress.diff");
print "=" x 70, "\n";
if ($diff_status == 0)
{
print "All tests passed\n";
exit 0;
}
else
{
print <<EOF;
FAILED: the test result differs from the expected output
Review the difference in "$subdir/regress.diff"
EOF
exit 1;
}
| amaliujia/CMUDB-peloton | src/postgres/interfaces/libpq/test/regress.pl | Perl | apache-2.0 | 1,698 |
##
## English tables
##
package Date::Language::Chinese_GB;
use Date::Language ();
use vars qw(@ISA @DoW @DoWs @MoY @MoYs @AMPM @Dsuf %MoY %DoW $VERSION);
@ISA = qw(Date::Language);
$VERSION = "1.01";
@DoW = qw(ÐÇÆÚÈÕ ÐÇÆÚÒ» ÐÇÆÚ¶þ ÐÇÆÚÈý ÐÇÆÚËÄ ÐÇÆÚÎå ÐÇÆÚÁù);
@MoY = qw(Ò»ÔÂ ¶þÔÂ ÈýÔÂ ËÄÔÂ ÎåÔÂ ÁùÔÂ
ÆßÔ °ËÔ ¾ÅÔ ʮÔ ʮһÔ ʮ¶þÔÂ);
@DoWs = map { $_ } @DoW;
@MoYs = map { $_ } @MoY;
@AMPM = qw(ÉÏÎç ÏÂÎç);
@Dsuf = (qw(ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ ÈÕ)) x 3;
@MoY{@MoY} = (0 .. scalar(@MoY));
@MoY{@MoYs} = (0 .. scalar(@MoYs));
@DoW{@DoW} = (0 .. scalar(@DoW));
@DoW{@DoWs} = (0 .. scalar(@DoWs));
# Formatting routines
sub format_a { $DoWs[$_[0]->[6]] }
sub format_A { $DoW[$_[0]->[6]] }
sub format_b { $MoYs[$_[0]->[4]] }
sub format_B { $MoY[$_[0]->[4]] }
sub format_h { $MoYs[$_[0]->[4]] }
sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] }
sub format_o { sprintf("%2d%s",$_[0]->[3],"ÈÕ") }
1;
| Dokaponteam/ITF_Project | xampp/perl/vendor/lib/Date/Language/Chinese_GB.pm | Perl | mit | 918 |
package Chromosome::0Sum;
use v5.10;
use strict;
use warnings;
use Moo::Role;
=head1 NAME
Chromosome::0Sum - Abstract Class for 0 Sum Chromosomes.
=head1 DESCRIPTION
The sum of all weights of a 0 Sum Chromosome must be 0. To ensure that,
each gene can have any weight name as value.
Half of the genes add 1 to it's weight and the other half subtracts 1 from it.
Each implementation must decide the C<size> of the Chromosome.
=cut
with 'Chromosome';
requires '_build_size';
has size => (is => 'lazy');
sub gene_values { shift->weight_keys() }
sub _build_genes {
my $self = shift;
my @possible_values = $self->weight_keys();
my @genes;
for ( 1 .. $self->size ) {
push @genes, $possible_values[ rand @possible_values ];
}
return \@genes;
}
sub _build_weights {
my $self = shift;
my %weights = map { $_ => 0 } $self->weight_keys;
for my $i (0 .. $self->size - 1) {
my $weight = $self->genes->[$i];
$weights{$weight} += $i % 2 == 0 ? 1 : -1;
}
return \%weights;
}
1;
| meis/2048GA | lib/Chromosome/0Sum.pm | Perl | mit | 1,051 |
# http-client-suspect: Watch http clients
if (($lgfile eq $config{CUSTOM7_LOG}) and ($line =~ /^(\S+)\s+-[\s\/[\]:-\d+A-z".]{2,}\s+HTTP\/1.\d"\s\d+\s\d+\s"-"\s"Ruby"$/)) {
return ("Kakashi [sharingan] knocked a bad browser",$1,"kakashi-sharingan-http-client-suspect","30","80,443","0");
}
| gpupo/kakashi | src/sharingan/20-http-client-suspect.pl | Perl | mit | 308 |
package HMF::Pipeline::Realignment;
use FindBin::libs;
use discipline;
use File::Spec::Functions;
use List::MoreUtils qw(uniq);
use HMF::Pipeline::Functions::Bam;
use HMF::Pipeline::Functions::Job qw(fromTemplate);
use HMF::Pipeline::Functions::Sge qw(qsubTemplate);
use HMF::Pipeline::Functions::Config qw(createDirs);
use parent qw(Exporter);
our @EXPORT_OK = qw(run);
sub run {
my ($opt) = @_;
say "\n### SCHEDULING INDEL REALIGNMENT ###";
say "Running single sample indel realignment for the following BAM-files:";
my $known_files = "";
$known_files = join " ", map { "-known $_" } split '\t', $opt->{REALIGNMENT_KNOWN} if $opt->{REALIGNMENT_KNOWN};
foreach my $sample (keys %{$opt->{SAMPLES}}) {
my $original_bam_file = $opt->{BAM_FILES}->{$sample};
HMF::Pipeline::Functions::Bam::operationWithSliceChecks("Realignment", $sample, $known_files, "realigned", "realign", $opt);
# KODU (DEV-440): Cleanup after realignment needs to wait on poststats.
my $dirs = createDirs(catfile($opt->{OUTPUT_DIR}, $sample), mapping => "mapping");
my $original_bam_path = catfile($dirs->{mapping}, $original_bam_file);
my $dependent_jobs = [ uniq @{$opt->{RUNNING_JOBS}->{$sample}}, @{$opt->{RUNNING_JOBS}->{poststats}} ];
my $realign_cleanup_job = fromTemplate(
"RealignmentCleanup",
$sample,
1,
qsubTemplate($opt, "REALIGNMENT_MASTER"),
$dependent_jobs,
$dirs,
$opt,
sample => $sample,
step_name => "RealignmentCleanup_" . $sample,
original_bam_path => $original_bam_path,
# KODU: comment to avoid perltidy putting on one line
);
push @{$opt->{RUNNING_JOBS}->{realigncleanup}}, $realign_cleanup_job;
}
return;
}
1; | hartwigmedical/pipeline | lib/HMF/Pipeline/Realignment.pm | Perl | mit | 1,853 |
require 5;
package Pod::Simple::PullParserEndToken;
use Pod::Simple::PullParserToken ();
use strict;
use vars qw(@ISA $VERSION);
@ISA = ('Pod::Simple::PullParserToken');
$VERSION = '3.23';
sub new { # Class->new(tagname);
my $class = shift;
return bless ['end', @_], ref($class) || $class;
}
# Purely accessors:
sub tagname { (@_ == 2) ? ($_[0][1] = $_[1]) : $_[0][1] }
sub tag { shift->tagname(@_) }
# shortcut:
sub is_tagname { $_[0][1] eq $_[1] }
sub is_tag { shift->is_tagname(@_) }
1;
__END__
=head1 NAME
Pod::Simple::PullParserEndToken -- end-tokens from Pod::Simple::PullParser
=head1 SYNOPSIS
(See L<Pod::Simple::PullParser>)
=head1 DESCRIPTION
When you do $parser->get_token on a L<Pod::Simple::PullParser>, you might
get an object of this class.
This is a subclass of L<Pod::Simple::PullParserToken> and inherits all its methods,
and adds these methods:
=over
=item $token->tagname
This returns the tagname for this end-token object.
For example, parsing a "=head1 ..." line will give you
a start-token with the tagname of "head1", token(s) for its
content, and then an end-token with the tagname of "head1".
=item $token->tagname(I<somestring>)
This changes the tagname for this end-token object.
You probably won't need to do this.
=item $token->tag(...)
A shortcut for $token->tagname(...)
=item $token->is_tag(I<somestring>) or $token->is_tagname(I<somestring>)
These are shortcuts for C<< $token->tag() eq I<somestring> >>
=back
You're unlikely to ever need to construct an object of this class for
yourself, but if you want to, call
C<<
Pod::Simple::PullParserEndToken->new( I<tagname> )
>>
=head1 SEE ALSO
L<Pod::Simple::PullParserToken>, L<Pod::Simple>, L<Pod::Simple::Subclassing>
=head1 SUPPORT
Questions or discussion about POD and Pod::Simple should be sent to the
pod-people@perl.org mail list. Send an empty email to
pod-people-subscribe@perl.org to subscribe.
This module is managed in an open GitHub repository,
L<http://github.com/theory/pod-simple/>. Feel free to fork and contribute, or
to clone L<git://github.com/theory/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to
<bug-pod-simple@rt.cpan.org>.
=head1 COPYRIGHT AND DISCLAIMERS
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.
=head1 AUTHOR
Pod::Simple was created by Sean M. Burke <sburke@cpan.org>.
But don't bother him, he's retired.
Pod::Simple is maintained by:
=over
=item * Allison Randal C<allison@perl.org>
=item * Hans Dieter Pearcey C<hdp@cpan.org>
=item * David E. Wheeler C<dwheeler@cpan.org>
=back
=cut
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/Pod/Simple/PullParserEndToken.pm | Perl | mit | 2,879 |
#!/usr/bin/env perl
use strict;
my %keepid;
my $infa = shift;
my $maxlcfrac = shift;
sub evalseq {
my ($id, $seq) = @_;
if(length($id) > 0 && length($seq) > 0) {
$seq =~ s/[\s\t\r\n]//g;
my $fulllen = length($seq);
$seq =~ s/[ACGTacgt]//g;
my $badlen = length($seq);
if($badlen / $fulllen < $maxlcfrac) {
$keepid{$id} = 1;
}
}
}
###
unless(length($maxlcfrac) > 0) {
$maxlcfrac = 0.5; # Maximum low complexity sequence proportion allowed
}
unless($infa) {
die "Usage: $0 [Nucleotide FASTA file] ([Max. Low Complexity Proportion, default: 0.5])\n";
}
unless(-e $infa) {
die "File not found: $infa\n";
}
open(DUST, "dust $infa 2>/dev/null |");
my $id = "";
my $seq = "";
while(<DUST>) {
chomp;
if(/^>/) {
evalseq($id, $seq);
$id = $_;
$seq = "";
} else {
$seq .= $_;
}
}
evalseq($id, $seq);
my $write = 0;
my $count_all = 0;
my $count_skip = 0;
my $count_new = 0;
open(IN, $infa) or die "Unable to open file $infa\n";
while(<IN>) {
chomp;
if(/^>/) {
$count_all++;
if($keepid{$_}) {
$write = 1;
$count_new++;
} else {
$write = 0;
$count_skip++;
}
}
if($write) {
print $_."\n";
}
}
print STDERR "Sequences before: $count_all, skipped: $count_skip, after: $count_new\n";
| mccrowjp/utilities | fasta_filter_low_complexity.pl | Perl | mit | 1,424 |
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;
use File::Basename qw/fileparse dirname basename/;
use Bio::Perl;
use File::Copy qw/copy move/;
use FindBin qw/$RealBin/;
$0=fileparse $0;
sub logmsg{print STDERR "$0: @_\n";}
exit(main());
sub main{
my $settings={clean=>0};
GetOptions($settings,qw(help reference=s fastq=s bam=s tempdir=s clean! numcpus=i pairedend=i));
for(qw(reference fastq bam)){
die "ERROR: need option $_\n".usage() if(!$$settings{$_});
}
$$settings{numcpus}||=1;
$$settings{tempdir}||="tmp";
$$settings{samtoolsxopts}||="";
$$settings{pairedend}||=0;
mkdir $$settings{tempdir} if(!-d $$settings{tempdir});
logmsg "Temporary directory is $$settings{tempdir}";
my $fastq=$$settings{fastq};
my $bam=$$settings{bam};
my $reference=$$settings{reference};
$$settings{refdir}||=dirname($reference);
logmsg "Cleaning was disabled. I will not clean the reads before mapping" if(!$$settings{clean});
$fastq=cleanReads($fastq,$settings) if($$settings{clean});
mapReads($fastq,$bam,$reference,$settings);
return 0;
}
sub cleanReads{
my($query,$settings)=@_;
logmsg "Trimming, removing duplicate reads, and cleaning";
my $b=fileparse $query;
my $prefix="$$settings{tempdir}/$b";
die if $?;
system("run_assembly_removeDuplicateReads.pl '$query' > '$prefix.nodupes.fastq'");
die if $?;
system("run_assembly_trimClean.pl --numcpus $$settings{numcpus} -i '$prefix.nodupes.fastq' -o '$prefix.cleaned.fastq' --auto");
die if $?;
system("rm -v '$prefix.nodupes.fastq' '$prefix.trimmed.fastq'");
return "$prefix.cleaned.fastq";
}
sub mapReads{
my($query,$bam,$ref,$settings)=@_;
if(-s "$bam"){
logmsg "Found $bam\n I will not re-map.";
return 1;
}
my $b=fileparse $query;
my $prefix="$$settings{tempdir}/$b";
my $tmpOut="$bam.sam";
logmsg "$bam not found. I'm really doing the mapping now!\n Outfile: $tmpOut";
my $snap=`which snap`; chomp($snap);
my $snapxopts="-t $$settings{numcpus} -so -o $tmpOut --b -I -x";
# PE reads or not? Mapping differently for different types.
if(is_fastqPE($query,$settings)){
###########
# PE reads
# #########
# deshuffle the reads
logmsg "Deshuffling to $prefix.1.fastq and $prefix.2.fastq";
system("run_assembly_shuffleReads.pl -d '$query' 1>'$prefix.1.fastq' 2>'$prefix.2.fastq'");
die "Problem with deshuffling reads! I am assuming paired end reads." if $?;
# SNAP has a problem trying to compare filesizes of uncompressed fastq
# files. Therefore, compress them with max speed.
system("gzip -vf1 $prefix.1.fastq $prefix.2.fastq");
die "ERROR with gzip" if $?;
# mapping ###
# SNAP gives weird permissions to the output file. Avoid it by
# creating the file yourself first.
system("touch $tmpOut");
die if $?;
my $snap_command="$snap paired $ref.snap '$prefix.1.fastq.gz' '$prefix.2.fastq.gz' $snapxopts";
my $snapxl_command=$snap_command;
$snapxl_command=~s/snap/snapxl/;
system("$snap_command || $snapxl_command");
die "ERROR: snap failed! $! $snap_command || $snapxl_command" if($?);
system("rm -v '$prefix.1.fastq.gz' '$prefix.2.fastq.gz'"); die if $?;
} else {
##########
# SE reads
##########
system("gunzip -c '$query' > $prefix.SE.fastq");
die "Problem with gunzip" if $?;
system("touch $tmpOut $tmpOut.bai");
die if $?;
my $snap_command="$snap single $ref.snap '$prefix.SE.fastq' $snapxopts";
my $snapxl_command=$snap_command;
$snapxl_command=~s/snap/snapxl/;
system("$snap_command || $snapxl_command");
# try one more time
if($?){
system("$snap_command || $snapxl_command");
}
die "ERROR: snap failed! $! $snap_command || $snapxl_command" if($?);
system("rm -v '$prefix.SE.fastq'"); die if $?;
}
## SNAP includes the entire defline for some reason, but the
## part in the defline after the space needs to be removed for
## compatibility with samtools
#my $seqin=Bio::SeqIO->new(-file=>$ref);
#while(my $seq=$seqin->next_seq){
# my $desc=$seq->desc;
# $desc=~s/\s/_/g;
# logmsg "Removing _$desc from sam file";
# system("sed -i 's/_$desc//' $tmpOut");
# logmsg "WARNING: could not replace a desc from the defline: $!\n The temporary sam file might not be compatible with the rest of the automation." if $?;
#}
# Do some post-mapping filtering
$$settings{samtoolsxopts}.="-F 4 -q 4";
my $regions="$$settings{refdir}/unmaskedRegions.bed";
if(-e $regions && -s $regions > 0){
logmsg "Found bed file of regions to accept and so I am using it! $regions";
$$settings{samtoolsxopts}.="-L $regions ";
}
# Use -q 4 because the author of SNAP says that unambiguous matches happen
# with mapping quality <=3.
# https://groups.google.com/forum/#!topic/snap-user/ppZRDeUkiL0
my $samtoolsView="mv -v $tmpOut $tmpOut.unfiltered && samtools view $$settings{samtoolsxopts} -bSh -T $ref $tmpOut.unfiltered > $tmpOut.bam";
system($samtoolsView);
die "ERROR with samtools view\n $samtoolsView" if $?;
unlink("$tmpOut.unfiltered");
# Sort/index
my $sorted="$bam.sorted.bam";
system("samtools sort -o $bam.sorted.bam $tmpOut.bam"); die "ERROR with samtools sort" if $?;
system("samtools index $sorted"); die "ERROR with samtools index" if $?;
system("rm -v $tmpOut.bam"); die "ERROR could not delete $tmpOut" if $?;
logmsg "Getting the depth at each position in the sorted bam file";
# read the depth, but unfortunately it skips over zero-depth sites
my %depth;
open(BAMDEPTH,"samtools depth $sorted | ") or die "ERROR: could not open the bam file with samtools: $!";
while(<BAMDEPTH>){
chomp;
my @F=split /\t/;
$depth{$F[0]}{$F[1]}=$F[2];
}
close BAMDEPTH;
# get zero-depth information in there too. First find the total length of each contig.
open(FIXEDDEPTH,">","$sorted.depth") or die "ERROR: could not write to $sorted.depth: $!";
my %max;
my $in=Bio::SeqIO->new(-file=>$ref);
while(my $seq=$in->next_seq){
$max{$seq->id}=$seq->length;
}
for my $contig(keys(%max)){
for my $i(1..$max{$contig}){
$depth{$contig}{$i}||=0;
print FIXEDDEPTH join("\t",$contig,$i,$depth{$contig}{$i})."\n";
}
}
close FIXEDDEPTH;
system("mv -v $sorted $bam"); die if $?;
system("mv -v $sorted.bai $bam.bai"); die if $?;
system("mv -v $sorted.depth $bam.depth"); die if $?;
unlink("$bam.depth");
return 1;
}
# Use CGP to determine if a file is PE or not
# settings: checkFirst is an integer to check the first X deflines
sub is_fastqPE($;$){
my($fastq,$settings)=@_;
# If PE was specified, return true for the value 2 (PE)
# and 0 for the value 1 (SE)
if($$settings{pairedend}){
return ($$settings{pairedend}-1);
}
# if checkFirst is undef or 0, this will cause it to check at least the first 50 entries.
# 50 reads is probably enough to make sure that it's shuffled (1/2^25 chance I'm wrong)
$$settings{checkFirst}||=50;
$$settings{checkFirst}=50 if($$settings{checkFirst}<2);
my $is_PE=`run_assembly_isFastqPE.pl '$fastq' --checkfirst $$settings{checkFirst}`;
chomp($is_PE);
return $is_PE;
}
sub usage{
"Maps a read set against a reference genome using snap. Output file will be file.bam and file.bam.depth
Usage: $0 -f file.fastq -b file.bam -t tmp/ -r reference.fasta
-t tmp to set the temporary directory as 'tmp'
--numcpus 1 number of cpus to use
--pairedend <0|1|2> For 'auto', single-end, or paired-end respectively. Default: auto (0).
"
}
| lskatz/lyve-SET | scripts/launch_snap.pl | Perl | mit | 7,579 |
package Prophet::Meta::Types;
{
$Prophet::Meta::Types::VERSION = '0.751';
}
# ABSTRACT: extra types for Prophet
use Any::Moose;
use Any::Moose 'Util::TypeConstraints';
enum 'Prophet::Type::ChangeType' => qw/add_file add_dir update_file delete/;
enum 'Prophet::Type::FileOpConflict' =>
qw/delete_missing_file update_missing_file create_existing_file create_existing_dir/;
__PACKAGE__->meta->make_immutable;
no Any::Moose;
1;
__END__
=pod
=head1 NAME
Prophet::Meta::Types - extra types for Prophet
=head1 VERSION
version 0.751
=head1 TYPES
=head2 Prophet::Type::ChangeType
A single change type: add_file, add_dir, update_file, delete.
=head1 AUTHORS
=over 4
=item *
Jesse Vincent <jesse@bestpractical.com>
=item *
Chia-Liang Kao <clkao@bestpractical.com>
=item *
Christine Spang <christine@spang.cc>
=back
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2009 by Best Practical Solutions.
This is free software, licensed under:
The MIT (X11) License
=head1 BUGS AND LIMITATIONS
You can make new bug reports, and view existing ones, through the
web interface at L<https://rt.cpan.org/Public/Dist/Display.html?Name=Prophet>.
=head1 CONTRIBUTORS
=over 4
=item *
Alex Vandiver <alexmv@bestpractical.com>
=item *
Casey West <casey@geeknest.com>
=item *
Cyril Brulebois <kibi@debian.org>
=item *
Florian Ragwitz <rafl@debian.org>
=item *
Ioan Rogers <ioanr@cpan.org>
=item *
Jonas Smedegaard <dr@jones.dk>
=item *
Kevin Falcone <falcone@bestpractical.com>
=item *
Lance Wicks <lw@judocoach.com>
=item *
Nelson Elhage <nelhage@mit.edu>
=item *
Pedro Melo <melo@simplicidade.org>
=item *
Rob Hoelz <rob@hoelz.ro>
=item *
Ruslan Zakirov <ruz@bestpractical.com>
=item *
Shawn M Moore <sartak@bestpractical.com>
=item *
Simon Wistow <simon@thegestalt.org>
=item *
Stephane Alnet <stephane@shimaore.net>
=item *
Unknown user <nobody@localhost>
=item *
Yanick Champoux <yanick@babyl.dyndns.org>
=item *
franck cuny <franck@lumberjaph.net>
=item *
robertkrimen <robertkrimen@gmail.com>
=item *
sunnavy <sunnavy@bestpractical.com>
=back
=cut
| gitpan/Prophet | lib/Prophet/Meta/Types.pm | Perl | mit | 2,115 |
%neg/2 - służy do znajdowania negacji danego literału.
neg(~X, X) :- !.
neg(X, ~X).
%lit/1 - sprawdza czy X jest literałem.
lit(X) :-
atom(X).
lit(~X) :-
atom(X).
%get_var/2 - zwraca pierwszy literał danej klauzuli.
get_var(C v _, C) :-
lit(C).
%sel_alt/2 - zwraca klauzulę bez pierwszego literału.
sel_alt(C v D, D) :-
lit(C).
%cl2set/2 - zamienia klauzulę na listę zawierającą zbiór jej literałów.
cl2set(X, L) :-
cl2list(X, L1), sort(L1, L).
%cl2list/2 - zamienia klauzulę na listę jej literałów.
cl2list(X, [X]) :-
lit(X), !.
cl2list(X, [H|T]) :-
get_var(X, H), sel_alt(X, X1), cl2list(X1, T).
%list_cl/2 - zamienia listę klauzul na listę list literałów tych klauzul.
get_clauses_list([X], [L]) :-
cl2set(X, L), !.
get_clauses_list([H|T], [H1|T1]) :-
cl2set(H, H1), get_clauses_list(T, T1).
%iter/3 iter(?List, ?ListFirst, ?ListRest) - dla listy List zwraca jej pierwszy element ListFirst oraz resztę elementów ListRest. Możliwość nawrotu
iter([L], L, []) :- !.
iter([H|T], H, T).
iter([_|T], X, Y) :-
iter(T, X, Y).
%find_op/1 powodzi się gdy w liście nie występuje literał i jego zaprzeczenie.
find_op([]) :- !.
find_op([H|T]) :-
neg(H, H1),
\+ member(H1, T),
find_op(T).
prove(Clauses, Proof) :-
get_clauses_list(Clauses, C1), sort(C1, C2), deduce(C2, P1), prep_to_write(P1, Proof).
%deduce/2 - główny silnik programu, za pomocą listy klauzul L wyprowadza dowód sprzeczności w postaci listy Res.
deduce(L, Res) :-
make_axiom_list(L, AxList),
get_axiom_num(AxList, Num),
deduce(L, Res, AxList, Num).
deduce([[]|_], X, X, _) :- !.
deduce([H|T], Res, Acc, Num) :-
iter([H|T], HeadList, TailList),
iter(HeadList, FirstElem, _),
neg(FirstElem, NegElem),
iter(TailList, FirstClause, _),
member(NegElem, FirstClause),
select(FirstElem, HeadList, Resol1),
select(NegElem, FirstClause, Resol2),
clause_append(Resol1, Resol2, NewResol),
find_op(NewResol),
\+ member(NewResol, [H|T]),
NewNum is Num + 1,
get_resol_num(NewResol, HeadList, FirstClause, Acc, NewNum, NewAcc),
deduce([NewResol, H|T], Res, NewAcc, NewNum).
%clause_append/3 - zwraca połączone i posortwoane dwie listy.
clause_append(L1, L2, Res) :-
clause_append(L1, L2, [], Res1), sort(Res1, Res), !.
clause_append([], [], Res, Res) :- !.
clause_append([], [H|T], Acc, Res) :-
clause_append([], T, [H|Acc], Res).
clause_append([H|T], L, Acc, Res) :-
clause_append(T, L, [H|Acc], Res).
%make_axiom_list/2 - dla podanej listy zawierającej listy oznaczające klauzule tworzy listę słóżącą do wypisania wyniku. Element listy ma postać:[[Klauzla], Numer, (axiom)].
make_axiom_list(AxList, Res) :-
make_axiom_list(AxList, 1, Res, []).
make_axiom_list([], _, Res, Res) :- !.
make_axiom_list([H|T], Num, Res, Acc) :-
NewNum is Num + 1,
make_axiom_list(T, NewNum, Res, [[H, Num, (axiom)] | Acc]).
%get_axiom_num/2 zwraca numer ostatniej klauzuli oznaczonej jako axiom.
get_axiom_num([[_,Num,_]|_], Num).
%get_clause_num/3 -znajduje numer Res klauzli Clause umieszczonej w liście NumList
get_clause_num(Clause, NumList, Res) :-
iter(NumList, [Clause, Res, _], _), !.
%get_resol_num/6 - do listy NumList dodaje nowy element będący rezolwentą klauzul Cl1 i Cl2, dodaje mu numer oraz jego pochodzenie, zwraca Res - listę z nowym elementem na poczatku.
get_resol_num(Resol, Cl1, Cl2, NumList, CurrentNum, Res) :-
get_clause_num(Cl1, NumList, Num1),
get_clause_num(Cl2, NumList, Num2),
Res = [[Resol, CurrentNum, (Num1, Num2)] | NumList], !.
%prep_to_write/2 - z trzymanej listy klauzul tworzy listę w postaci umożliwiającej wypisanie wyniku przy pomocy writeProof
prep_to_write(List, Res) :-
prep_to_write(List, Res, []), !.
prep_to_write([], Res, Res) :- !.
prep_to_write(List, Res, Acc) :-
iter(List, [[], _, Origin], Rest),
prep_to_write(Rest, Res, [([], (Origin))|Acc]).
prep_to_write(List, Res, Acc) :-
iter(List, [Clause, _, Origin], Rest),
cl2list(Cl, Clause),
prep_to_write(Rest, Res, [(Cl, (Origin))|Acc]).
| wiatrak2/Metody_programowania | theorem_prover/Wojciech_Pratkowiecki.pl | Perl | mit | 4,153 |
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Shopify;
package WWW::Shopify::Model::Order::LineItem;
use parent "WWW::Shopify::Model::NestedItem";
my $fields; sub fields { return $fields; }
BEGIN { $fields = {
"fulfillment_service" => new WWW::Shopify::Field::String::Enum(["automatic", "manual"]),
"fulfillment_status" => new WWW::Shopify::Field::String(),
"grams" => new WWW::Shopify::Field::Int(1, 2000),
"id" => new WWW::Shopify::Field::Identifier(),
"price" => new WWW::Shopify::Field::Money(),
# These are not always filled out. If a product is deleted, these are null.
"product_id" => new WWW::Shopify::Field::Relation::ReferenceOne('WWW::Shopify::Model::Product', 1),
"variant_id" => new WWW::Shopify::Field::Relation::ReferenceOne('WWW::Shopify::Model::Product::Variant', 1),
#
"gift_card" => new WWW::Shopify::Field::Boolean(),
"quantity" => new WWW::Shopify::Field::Int(1, 20),
"requires_shipping" => new WWW::Shopify::Field::Boolean(),
"product_exists" => new WWW::Shopify::Field::Boolean(),
"sku" => new WWW::Shopify::Field::String(),
"title" => new WWW::Shopify::Field::String::Words(1, 3),
"variant_title" => new WWW::Shopify::Field::String::Words(1,3),
"vendor" => new WWW::Shopify::Field::String(),
"name" => new WWW::Shopify::Field::String::Words(1, 3),
"properties" => new WWW::Shopify::Field::Relation::Many("WWW::Shopify::Model::Order::LineItem::Property"),
"tax_lines" => new WWW::Shopify::Field::Relation::Many("WWW::Shopify::Model::Order::LineItem::TaxLine"),
"taxable" => new WWW::Shopify::Field::Boolean(),
"variant_inventory_management" => new WWW::Shopify::Field::String::Enum(["shopify", "manual"]) };
}
sub creatable { return undef; }
sub updatable { return undef; }
sub deletable { return undef; }
sub singular() { return 'line_item'; }
eval(__PACKAGE__->generate_accessors); die $@ if $@;
1
| gitpan/WWW-Shopify | lib/WWW/Shopify/Model/Order/LineItem.pm | Perl | mit | 1,859 |
#!/usr/bin/perl -w
#use strict;
use Spreadsheet::ParseExcel;
use Encode qw(encode decode);
use Config::General;
use Getopt::Long;
use Time::localtime;
GetOptions (\%o, "help");
#$enc = 'utf-8';
if(exists($o{'help'})){
print <<"::_USAGE0_BLOCK_END_::";
usage: mkConfigOptionsFile.pl [options]
options:
-h, --help Display this help message
The script auto-generates a config options file in folder
defined in calls2xls.cfg
::_USAGE0_BLOCK_END_::
exit 1
}
## Read configs
my $conf = Config::General->new("$ENV{'CALLS2XLS'}/calls2xls.cfg");
my %c = $conf->getall;
$nowdate = &get_nowtime();
$designpath = "$ENV{'CALLS2XLS'}/" . $c{'designAndGeneListsRootPath'};
@designfiles = &get_files($designpath);
$diseasepath = "$ENV{'CALLS2XLS'}/" . $c{'diseaseGeneAssocPath'};
@diseasefiles = &get_files($diseasepath);
#print "@designfiles\n";
#print "@diseasefiles\n";
$outfile = $c{'miseqOptionsFilePath'} . "/" . "config." . $nowdate . ".txt";
open(FH, ">$outfile");
print FH "\nSampleSheet.csv template:\n";
print FH " Design\$Gender\$Disease_hypothesis\$GeneListFile\n\n";
print FH "Design file:\n";
foreach $file (@designfiles){
print FH " $file\n";
}
print FH "Gender:\n";
print FH " male/female\n";
print FH "\nGeneListFiles:\n";
foreach $file (@diseasefiles){
print FH " $file\n";
print FH " ";
open(FH2, "<$diseasepath/$file");
chomp(@ddata = <FH2>);
close(FH2);
foreach $row (@ddata){
if($row =~ /^>(\S+)/){
print FH "$1 "
}
}
print FH "\n\n";
}
close(FH);
sub get_nowtime(){
my $tm = localtime;
return sprintf("%04d.%02d.%02d-%02d.%02d.%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec );
}
sub get_files(){
my $finalpath = shift;
my @files;
opendir(DIR, $finalpath);
@files = grep {/bed$|txt$/} readdir(DIR);
close(DIR);
return sort {$b cmp $a} @files;
}
| parlar/calls2xls | bin/mkConfigOptionsFile.pl | Perl | mit | 1,933 |
#! /usr/bin/perl
#
# Copyright (c) 2001-2008, PostgreSQL Global Development Group
#
# $PostgreSQL: pgsql/src/backend/utils/mb/Unicode/UCS_to_EUC_JP.pl,v 1.10 2008/01/01 19:45:53 momjian Exp $
#
# Generate UTF-8 <--> EUC_JP code conversion tables from
# map files provided by Unicode organization.
# Unfortunately it is prohibited by the organization
# to distribute the map files. So if you try to use this script,
# you have to obtain JIS0201.TXT, JIS0208.TXT, JIS0212.TXT from
# the organization's ftp site.
#
# JIS0201.TXT format:
# JIS0201 code in hex
# UCS-2 code in hex
# # and Unicode name (not used in this script)
#
# JIS0208.TXT format:
# JIS0208 shift-JIS code in hex
# JIS0208 code in hex
# UCS-2 code in hex
# # and Unicode name (not used in this script)
#
# JIS0212.TXT format:
# JIS0212 code in hex
# UCS-2 code in hex
# # and Unicode name (not used in this script)
require "ucs2utf.pl";
# first generate UTF-8 --> EUC_JP table
#
# JIS0201
#
$in_file = "JIS0201.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
reset 'array';
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $utf } ne "" ){
printf STDERR "Warning: duplicate UTF8: %04x\n",$ucs;
next;
}
$count++;
# add single shift 2
$array{ $utf } = ($code | 0x8e00);
}
}
close( FILE );
#
# JIS0208
#
$in_file = "JIS0208.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $s, $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $utf } ne "" ){
printf STDERR "Warning: duplicate UTF8: %04x\n",$ucs;
next;
}
$count++;
$array{ $utf } = ($code | 0x8080);
}
}
close( FILE );
#
# JIS0212
#
$in_file = "JIS0212.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $utf } ne "" ){
printf STDERR "Warning: duplicate UTF8: %04x\n",$ucs;
next;
}
$count++;
$array{ $utf } = ($code | 0x8f8080);
}
}
close( FILE );
#
# first, generate UTF8 --> EUC_JP table
#
$file = "utf8_to_euc_jp.map";
open( FILE, "> $file" ) || die( "cannot open $file" );
print FILE "static pg_utf_to_local ULmapEUC_JP[ $count ] = {\n";
for $index ( sort {$a <=> $b} keys( %array ) ){
$code = $array{ $index };
$count--;
if( $count == 0 ){
printf FILE " {0x%04x, 0x%04x}\n", $index, $code;
} else {
printf FILE " {0x%04x, 0x%04x},\n", $index, $code;
}
}
print FILE "};\n";
close(FILE);
#
# then generate EUC_JP --> UTF8 table
#
#
# JIS0201
#
$in_file = "JIS0201.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
reset 'array';
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $code } ne "" ){
printf STDERR "Warning: duplicate code: %04x\n",$ucs;
next;
}
$count++;
# add single shift 2
$code |= 0x8e00;
$array{ $code } = $utf;
}
}
close( FILE );
#
# JIS0208
#
$in_file = "JIS0208.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $s, $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $code } ne "" ){
printf STDERR "Warning: duplicate code: %04x\n",$ucs;
next;
}
$count++;
$code |= 0x8080;
$array{ $code } = $utf;
}
}
close( FILE );
#
# JIS0212
#
$in_file = "JIS0212.TXT";
open( FILE, $in_file ) || die( "cannot open $in_file" );
while( <FILE> ){
chop;
if( /^#/ ){
next;
}
( $c, $u, $rest ) = split;
$ucs = hex($u);
$code = hex($c);
if( $code >= 0x80 && $ucs >= 0x0080 ){
$utf = &ucs2utf($ucs);
if( $array{ $code } ne "" ){
printf STDERR "Warning: duplicate code: %04x\n",$ucs;
next;
}
$count++;
$code |= 0x8f8080;
$array{ $code } = $utf;
}
}
close( FILE );
$file = "euc_jp_to_utf8.map";
open( FILE, "> $file" ) || die( "cannot open $file" );
print FILE "static pg_local_to_utf LUmapEUC_JP[ $count ] = {\n";
for $index ( sort {$a <=> $b} keys( %array ) ){
$utf = $array{ $index };
$count--;
if( $count == 0 ){
printf FILE " {0x%04x, 0x%04x}\n", $index, $utf;
} else {
printf FILE " {0x%04x, 0x%04x},\n", $index, $utf;
}
}
print FILE "};\n";
close(FILE);
| KMU-embedded/mosbench-ext | postgres/postgresql-8.3.9/src/backend/utils/mb/Unicode/UCS_to_EUC_JP.pl | Perl | mit | 4,669 |
package RebootNow;
use strict;
use warnings;
use utf8;
sub plugin {
MT->component('RebootNow');
}
sub reboot_now {
my ($app) = @_;
return $app->permission_denied()
unless $app->user->is_superuser();
$app->reboot;
$app->redirect(
$app->uri(
'mode' => 'tools',
args => { reboot_complete => 1 }
),
);
}
sub template_param_system_check {
my ( $cb, $app, $param, $tmpl ) = @_;
return 1
unless $app->user->is_superuser();
$param->{reboot_complete} = !!$app->param('reboot_complete');
my $place_holder = $tmpl->getElementById('system_check');
foreach my $t ( @{ plugin()->load_tmpl('system_check.tmpl')->tokens } ) {
$tmpl->insertAfter( $t, $place_holder );
$place_holder = $t;
}
}
1;
| usualoma/mt-plugin-RebootNow | plugins/RebootNow/lib/RebootNow.pm | Perl | mit | 810 |
#!/usr/local/bin/perl
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use strict;
use DBI;
use File::Basename qw(dirname);
use FindBin qw($Bin);
use vars qw($SERVERROOT);
BEGIN {
my $serverroot = "/usr/local/ensembl-live/";
eval{ use lib "/usr/local/ensembl-live/ensembl-webcode/conf"; require SiteDefs };
if ($@){ die "Can't use SiteDefs.pm - $@\n"; }
map{ s/conf//; unshift @INC, $_ } @SiteDefs::ENSEMBL_LIB_DIRS;
}
#exit;
use EnsEMBL::Web::SpeciesDefs;
my $sd = new EnsEMBL::Web::SpeciesDefs;
my $serverroot = "/usr/local/ensembl-live/"; #"$Bin/../../../";
my $hive_db = $sd->multidb->{'DATABASE_WEB_HIVE'};
my $db = $hive_db->{'NAME'};
my $host = $hive_db->{'HOST'};
my $port = $hive_db->{'PORT'};
my $user = $hive_db->{'USER'} || $sd->DATABASE_WRITE_USER;
my $pass = $hive_db->{'PASS'} || $sd->DATABASE_WRITE_PASS;
my $url = "mysql://$user:$pass".'@'."$host:$port/$db";
my $days = 8; # delete jobs older than 8 days
my $command = $serverroot ."ensembl-hive/scripts/hoover_pipeline.pl -url " . $url . " -days_ago " . $days;
my $lib = join ':', @INC;
$ENV{PERL5LIB} = $lib;
warn ("lib = $lib\ncommand=$command\n");
system ($command);
| warelab/gramene-ensembl | gramene/utils/clean_up_hive_db.pl | Perl | mit | 1,823 |
/*
* GIPO COPYRIGHT NOTICE, LICENSE AND DISCLAIMER.
*
* Copyright 2001 - 2003 by R.M.Simpson W.Zhao T.L.McCLuskey D Liu D. Kitchin
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both the copyright notice and this permission notice and warranty
* disclaimer appear in supporting documentation, and that the names of
* the authors or their employers not be used in advertising or publicity
* pertaining to distribution of the software without specific, written
* prior permission.
*
* The authors and their employers disclaim all warranties with regard to
* this software, including all implied warranties of merchantability and
* fitness. In no event shall the authors or their employers be liable
* for any special, indirect or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether in an
* action of contract, negligence or other tortious action, arising out of
* or in connection with the use or performance of this software.
*/
%% Utility to compile the prolog tools
:-set_prolog_flag(redefine_warnings,off).
:-set_prolog_flag(single_var_warnings,off).
:-compile('Forward.pl'),save_program('Forward.sav').
%:-compile('tweak-nlp.pl'),save_program('tweak-nlp.sav').
:-compile('ocl2pddl.pl'),save_program('ocl2pddl.sav').
%:-compile('groundCE.pl'),save_program('groundCE.sav').
:-compile('gentasks.pl'),save_program('gentasks.sav').
%:-compile('FMOL.pl'),save_program('FMOL.sav').
:-compile('hyhtn.pl'),save_program('HyHtn.sav').
:-halt.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_ec/prolog/hyhtn_pddl/ptools/compile.pl | Perl | mit | 1,687 |
package Example;
use strict;
use warnings;
use List::Util 'first';
my @allergens = qw(eggs peanuts shellfish strawberries tomatoes chocolate pollen cats);
sub new {
my ($class, $score) = @_;
my $self = bless {} => $class;
$self->{score} = reverse sprintf "%08b", $score;
return $self;
}
sub allergic_to {
my ($self, $allergen) = @_;
my $index = first { $allergens[$_] eq $allergen } 0..$#allergens;
return substr $self->{score}, $index, 1;
}
sub list { [ grep { $_[0]->allergic_to($_) } @allergens ] }
__PACKAGE__;
| dnmfarrell/xperl5 | allergies/Example.pm | Perl | mit | 555 |
#!/usr/bin/perl
=head1 NAME
generate_r_snp_dist.pl
generate R commads for reading SNP and genome coverage data, and introgression regions.
Output will be R graphs by chromosome , X axis is position , Y axis is SNP frequency, with introgression regions highlighted
You can also mask introgressions using SNPs from another genome, with the -m option.
Second set of graphs can be generated for the genome coverage by chromosome
=cut
=head1 SYPNOSIS
generate_r_snp_dist.pl [-h] -s <base name for R table containing the SNP and coverage data> -i <base name for R table containing the introgression regions> -o <output_file>
=head1 DESCRIPTION
This script reads 2 R table names : SNP/Coverage data (read tab delimited file $V1=chromosome $V2=coordinate $V3=SNP count $V4=Coverage (sum of coverage for $V2 range}
SL2.50ch01 10000 8 181582
SL2.50ch01 20000 2 179344
.
.
.
SL2.50ch12 10000 35 177901
Variable 2 is the introgression data: $V1=introgression number $V2=chromosome $V3=position $V4=SNP count $V5=coverage
1 SL2.50ch01 300000 48 170975
1 SL2.50ch01 310000 40 166692
1 SL2.50ch01 320000 22 17097
'
'
'
Pass a 3rd table with introgressions for masking overlapping regions
1 SL2.50ch01 300000 33 110565
1 SL2.50ch01 310000 34 104331
2 SL2.50ch01 450000 20 259822
2 SL2.50ch01 460000 74 321990
.
.
=head2 I<Flags:>
=over
=item -s | --snps
B<input R Table name> input R table name for SNPs and genome coverage (mandatory)
=item -i | --introg
B<input R table name> input R table name for introgression regions in the genome (optional)
=item -m | --mask
B<input R table name> input R table for introgression regions in a second genome for masking introgressions in genome 1.
=item -o
B<output_file> output file (mandatory)
=item -h
B<help> print this help doc
=back
=head1 AUTHOR
Naama Menda<nm249@cornell.edu>
=cut
use strict;
use warnings;
use File::Slurp;
use Getopt::Long;
use Pod::Usage;
use Carp qw /croak/;
my ( $snps, $introg, $out, $mask, $help);
GetOptions (
"snps|s=s" => \$snps, # string
"introg|i=s" => \$introg,
"out|o=s" => \$out,
"mask|m=s" => \$mask,
"help" => \$help) # flag
or pod2usage(-verbose => 2);
if ($help || !$snps || !$out) { pod2usage(-verbose => 2); }
################################################################################
#first load the data into R. This has to be done before running the commands this script outputs
# $snps <- read.table("bti87.snps.introg.10.tab", as.is=TRUE,header=FALSE, sep="\t")
# $introg <- read.table("8624h.introg.10.tab", as.is=TRUE,header=FALSE, sep="\t")
####################
#assign a variable name for each chromosome
my @chromosomes = qw | 01 02 03 04 05 06 07 08 09 10 11 12| ;
my $chr_var;
my $int_var;
my $mask_var;
foreach my $chr ( @chromosomes) {
$chr_var = $snps . "_ch" . $chr ;
write_file($out, { append =>1 } , $chr_var , " <- " , $snps , "[" , $snps , '$V1==\'SL2.50ch' , $chr , "',]" ,"\n\n" );
$int_var = $introg . "_ch" . $chr ;
$mask_var = $mask . "_ch" . $chr ;
if ( $introg ) {
write_file($out, { append =>1 } , $int_var , " <- " , $introg , "[" , $introg , '$V2==\'SL2.50ch' , $chr , "',]" ,"\n\n" );
}
if ( $mask ) {
write_file($out, {append =>1 } , $mask_var , " <- " , $mask, "[" , $mask , '$V2==\'SL2.50ch' , $chr , "',]" , "\n\n" );
}
#generate the coverage plot
write_file($out , { append => 1 } , "pdf(file =", '"' , $chr_var , 'cov.pdf", width = 10, height = 4, )' , "\n\n" ,
"plot((" , $chr_var , '$V2)/1000000,' , $chr_var , '$V4/10000, type="h", ylim=rev(c(1,50)), col="black" , ylab="Coverage", xlab="coordinate (Mb)")' , "\n" ,
"dev.off()\n\n" );
# generate the SNP plot with the introgression highlighted (if -i is used )
write_file($out, {append =>1 } , 'pdf(file = "' , $chr_var, 'SNP_introg.pdf", width=10,height=6)' , "\n\n" ,
"plot((" , $chr_var , '$V2)/1000000,' , $chr_var , '$V3, type="h", ylim=c(1,100), col="black" , ylab="SNP Frequency", xlab="coordinate (Mb)",main = "Chromosome ' , $chr , '")' , "\n");
if ( $introg) {
write_file($out, {append => 1 } , "lines((" , $int_var , '$V3)/1000000,' , $int_var , '$V4, type="h", col="red")' , "\n" );
}
if ( $mask ) {
write_file( $out , {append => 1 } , "lines((" , $mask_var , '$V3)/1000000,' , $mask_var , '$V4, type="h", col="yellow")' , "\n" );
}
write_file($out, {append => 1 } , "dev.off()" , "\n\n" );
}
| nmenda/GenomeTools | generate_r_snp_dist.pl | Perl | mit | 4,826 |
use strict;
use warnings;
use Bio::EnsEMBL::Registry;
my $registry = 'Bio::EnsEMBL::Registry';
$registry->load_registry_from_db(
-host => 'mysql-ens-sta-1',
-user => 'ensro',
-port => 4519,
);
#$registry->load_registry_from_db(
# -host => 'ensembldb.ensembl.org',
# -user => 'anonymous',
# -DB_VERSION => 97,
#);
my $vdba = $registry->get_DBAdaptor('cat', 'variation');
my $cdba = $registry->get_DBAdaptor('cat', 'core');
my $ga = $cdba->get_GeneAdaptor;
my $gene = $ga->fetch_by_stable_id('ENSFCAG00000026758');
#my $gene_name = $gene->display_xref->display_id;
#print $gene_name, "\n";
my $symbol = 'PITX3';
my $genes = $ga->fetch_all_by_external_name('PITX3');
foreach my $gene (@$genes) {
print $gene->stable_id, "\n";
}
| at7/work | api/cat_xrefs.pl | Perl | apache-2.0 | 749 |
# 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::CustomerClientService;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);
sub get {
my $self = shift;
my $request_body = shift;
my $http_method = 'GET';
my $request_path = 'v8/{+resourceName}';
my $response_type = 'Google::Ads::GoogleAds::V8::Resources::CustomerClient';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Services/CustomerClientService.pm | Perl | apache-2.0 | 1,043 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::Job::VEP;
use strict;
use warnings;
use EnsEMBL::Web::VEPConstants qw(REST_DISPATCHER_FILESIZE_LIMIT);
use parent qw(EnsEMBL::Web::Job);
sub prepare_to_dispatch {
## @override
my $self = shift;
my $rose_object = $self->rose_object;
my $job_data = $rose_object->job_data;
my $species = $job_data->{'species'};
my $sp_details = $self->_species_details($species);
my $sd = $self->hub->species_defs;
my $vep_configs = {};
$vep_configs->{'species'} = lc $species;
# select transcript set
$vep_configs->{'refseq'} = 'yes' if $sp_details->{'refseq'} && ($job_data->{'core_type'} // '') eq 'refseq';
$vep_configs->{'merged'} = 'yes' if $sp_details->{'refseq'} && ($job_data->{'core_type'} // '') eq 'merged';
$vep_configs->{'gencode_basic'} = 'yes' if ($job_data->{'core_type'} // '') eq 'gencode_basic';
# filters
my $frequency_filtering = $job_data->{'frequency'};
if ($species eq 'Homo_sapiens') {
if ($frequency_filtering eq 'common') {
$vep_configs->{'filter_common'} = 'yes';
} elsif($frequency_filtering eq 'advanced') {
$vep_configs->{'check_frequency'} = 'yes';
$vep_configs->{$_} = $job_data->{$_} || 0 for qw(freq_pop freq_freq freq_gt_lt freq_filter);
}
}
my $summary = $job_data->{'summary'};
if ($summary ne 'no') {
$vep_configs->{$summary} = 'yes';
}
for (grep $sp_details->{$_}, qw(regulatory sift polyphen)) {
my $value = $job_data->{$_ . ($_ eq 'regulatory' ? "_$species" : '')};
$vep_configs->{$_} = $value if $value && $value ne 'no';
}
# regulatory
if($sp_details->{'regulatory'} && $vep_configs->{'regulatory'}) {
# cell types
if($vep_configs->{'regulatory'} eq 'cell') {
my @cell_types = grep { length $_ } ref $job_data->{"cell_type_$species"} ? @{$job_data->{"cell_type_$species"}} : $job_data->{"cell_type_$species"};
$vep_configs->{'cell_type'} = join ",", @cell_types if scalar @cell_types;
}
$vep_configs->{'regulatory'} = 'yes';
}
# check existing
my $check_ex = $job_data->{'check_existing'};
if ($check_ex && $check_ex ne 'no') {
if($check_ex eq 'yes') {
$vep_configs->{'check_existing'} = 'yes';
} elsif ($check_ex eq 'no_allele') {
$vep_configs->{'check_existing'} = 'yes';
$vep_configs->{'no_check_alleles'} = 'yes';
}
# MAFs in human
if ($species eq 'Homo_sapiens') {
($job_data->{'af'} // '') eq 'yes' and $vep_configs->{$_} = 'yes' for qw(af af_1kg af_esp af_gnomad);
$vep_configs->{'pubmed'} = $job_data->{'pubmed'} if $job_data->{'pubmed'};
}
}
# i/o files
$vep_configs->{'input_file'} = $job_data->{'input_file'};
$vep_configs->{'output_file'} = 'output.vcf';
$vep_configs->{'stats_file'} = 'stats.txt';
# extra and identifiers
$job_data->{$_} and $vep_configs->{$_} = $job_data->{$_} for qw(numbers canonical domains biotype symbol ccds protein uniprot hgvs coding_only all_refseq tsl appris failed distance);
$vep_configs->{distance} = 0 if($job_data->{distance} eq '0' || $job_data->{distance} eq "");
# check for incompatibilities
if ($vep_configs->{'most_severe'} || $vep_configs->{'summary'}) {
delete $vep_configs->{$_} for(qw(coding_only protein symbol sift polyphen ccds canonical numbers domains biotype tsl appris));
}
# plugins
$vep_configs->{plugin} = $self->_configure_plugins($job_data);
return { 'species' => $vep_configs->{'species'}, 'work_dir' => $rose_object->job_dir, 'config' => $vep_configs };
}
sub _configure_plugins {
my $self = shift;
my $job_data = shift;
# get plugin config into a hash keyed on key
my $pl = $self->hub->species_defs->multi_val('ENSEMBL_VEP_PLUGIN_CONFIG');
return [] unless $pl;
my %plugin_config = map {$_->{key} => $_} @{$pl->{plugins} || []};
my @active_plugins = ();
foreach my $pl_key(grep {$_ =~ /^plugin\_/ && $job_data->{$_} eq $_} keys %$job_data) {
$pl_key =~ s/^plugin\_//;
my $plugin = $plugin_config{$pl_key};
next unless $plugin;
my @params;
foreach my $param(@{$plugin->{params}}) {
# links to something in the form
if($param =~ /^\@/) {
$param =~ s/^\@//;
my @matched = ();
# fuzzy match?
if($param =~ /\*/) {
$param =~ s/\*/\.\*/;
@matched = grep {$_->{name} =~ /$param/} @{$plugin->{form}};
}
else {
@matched = grep {$_->{name} eq $param} @{$plugin->{form}};
}
foreach my $el(@matched) {
my $val = $job_data->{'plugin_'.$pl_key.'_'.$el->{name}};
$val = join(',', @$val) if $val && ref($val) eq 'ARRAY';
# remove any spaces
$val =~ s/,\s+/,/g if $val && $val =~ /,/;
if(defined($val) && $val ne '' && $val ne 'no') {
push @params, $val;
}
}
}
# otherwise just plain text
else {
push @params, $param;
}
}
push @active_plugins, join(",", ($pl_key, @params));
}
return \@active_plugins;
}
sub get_dispatcher_class {
## For smaller VEP jobs, we use the VEP REST API dispatcher, otherwise whatever is configured in SiteDefs.
my ($self, $data) = @_;
my $filesize = -s join '/', $data->{'work_dir'}, $data->{'config'}->{'input_file'};
my $limit = REST_DISPATCHER_FILESIZE_LIMIT || 0;
return $limit > $filesize ? 'VEPRest' : undef;
}
sub _species_details {
## @private
my ($self, $species) = @_;
my $sd = $self->hub->species_defs;
my $db_config = $sd->get_config($species, 'databases');
return {
'sift' => $db_config->{'DATABASE_VARIATION'}{'SIFT'},
'polyphen' => $db_config->{'DATABASE_VARIATION'}{'POLYPHEN'},
'regulatory' => $sd->get_config($species, 'REGULATORY_BUILD'),
'refseq' => $db_config->{'DATABASE_OTHERFEATURES'} && $sd->get_config($species, 'VEP_REFSEQ')
};
}
1;
| muffato/public-plugins | tools/modules/EnsEMBL/Web/Job/VEP.pm | Perl | apache-2.0 | 6,699 |
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::bluemind::local::mode::webserver;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use bigint;
sub prefix_webserver_output {
my ($self, %options) = @_;
return 'Web application server ';
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'bm_webserver', type => 0, cb_prefix_output => 'prefix_webserver_output' },
];
$self->{maps_counters}->{bm_webserver} = [
{ label => 'requests-time-total', nlabel => 'webserver.requests.time.milliseconds', display_ok => 0, set => {
key_values => [ { name => 'requests_time_total', diff => 1 } ],
output_template => 'total requests time: %s ms',
perfdatas => [
{ value => 'requests_time_total', template => '%s', min => 0, unit => 'ms' }
]
}
},
{ label => 'requests-time-mean', nlabel => 'webserver.requests.time.mean.milliseconds', set => {
key_values => [ { name => 'requests_time_mean' } ],
output_template => 'mean requests time: %s ms',
perfdatas => [
{ value => 'requests_time_mean', template => '%s', min => 0, unit => 'ms' }
]
}
},
{ label => 'requests-total', nlabel => 'webserver.requests.total.count', set => {
key_values => [ { name => 'requests', diff => 1 } ],
output_template => 'total requests: %s',
perfdatas => [
{ value => 'requests', template => '%s', min => 0 }
]
}
},
{ label => 'requests-status-200', nlabel => 'webserver.requests.status.200.count', display_ok => 0, set => {
key_values => [ { name => 'requests_200', diff => 1 } ],
output_template => 'total 200 requests: %s',
perfdatas => [
{ value => 'requests_200', template => '%s', min => 0 }
]
}
},
{ label => 'requests-status-304', nlabel => 'webserver.requests.status.304.count', display_ok => 0, set => {
key_values => [ { name => 'requests_304', diff => 1 } ],
output_template => 'total 304 requests: %s',
perfdatas => [
{ value => 'requests_304', template => '%s', min => 0 }
]
}
}
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
});
return $self;
}
sub manage_selection {
my ($self, %options) = @_;
# bm-webserver.appCache.requestTime,meterType=Timer count=91005,totalTime=46688008481,mean=513026
# bm-webserver.appCache.requests,meterType=Counter count=8552
# bm-webserver.staticFile.requests,status=200,meterType=Counter count=318881
# bm-webserver.staticFile.requests,status=304,meterType=Counter count=3485778
my $result = $options{custom}->execute_command(
command => 'curl --unix-socket /var/run/bm-metrics/metrics-bm-webserver.sock http://127.0.0.1/metrics',
filter => 'appCache|staticFile\.requests'
);
$self->{bm_webserver} = {};
foreach (keys %$result) {
$self->{bm_webserver}->{'requests_' . $1} = $result->{$_}->{count} if (/bm-webserver\.staticFile\.requests.*,status=(200|304)/);
$self->{bm_webserver}->{requests} = $result->{$_}->{count} if (/bm-webserver\.appCache\.requests/);
if (/bm-webserver\.appCache\.requestTime/) {
$self->{bm_webserver}->{requests_time_total} = $result->{$_}->{totalTime} / 100000;
$self->{bm_webserver}->{requests_time_mean} = $result->{$_}->{mean} / 100000;
}
}
$self->{cache_name} = 'bluemind_' . $self->{mode} . '_' . $options{custom}->get_hostname() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check web application server.
=over 8
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='requests-time-mean'
=item B<--filter-upstream>
Filter upstream name (can be a regexp).
=item B<--warning-*> B<--critical-*>
Thresholds.
Can be: 'requests-time-total', 'requests-time-mean', 'requests-total',
'requests-status-200', 'requests-status-304'.
=back
=cut
| centreon/centreon-plugins | apps/bluemind/local/mode/webserver.pm | Perl | apache-2.0 | 5,415 |
#
# 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::printers::standard::rfc3805::mode::papertray;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use centreon::plugins::misc;
my %unit_managed = (
8 => 1, # sheets(8)
);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"warning:s" => { name => 'warning' },
"critical:s" => { name => 'critical' },
"filter-tray:s" => { name => 'filter_tray' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
$self->{output}->option_exit();
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
my $oid_prtInputCurrentLevel = '.1.3.6.1.2.1.43.8.2.1.10';
my $oid_prtInputMaxCapacity = '.1.3.6.1.2.1.43.8.2.1.9';
my $oid_prtInputCapacityUnit = '.1.3.6.1.2.1.43.8.2.1.8';
my $oid_prtInputDescription = '.1.3.6.1.2.1.43.8.2.1.18';
my $result = $self->{snmp}->get_table(oid => $oid_prtInputCurrentLevel, nothing_quit => 1);
$self->{snmp}->load(oids => [$oid_prtInputMaxCapacity, $oid_prtInputCapacityUnit,
$oid_prtInputDescription],
instances => [keys %$result], instance_regexp => '(\d+\.\d+)$');
$self->{output}->output_add(severity => 'OK',
short_msg => "Paper tray usages are ok.");
my $result2 = $self->{snmp}->get_leef();
foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) {
$key =~ /(\d+).(\d+)$/;
my ($hrDeviceIndex, $prtInputIndex) = ($1, $2);
my $instance = $hrDeviceIndex . '.' . $prtInputIndex;
my $unit = $result2->{$oid_prtInputCapacityUnit . '.' . $instance};
my $descr = centreon::plugins::misc::trim($result2->{$oid_prtInputDescription . '.' . $instance});
my $current_value = $result->{$key};
my $max_value = $result2->{$oid_prtInputMaxCapacity . '.' . $instance};
if (!defined($descr) || $descr eq '') {
$descr = $hrDeviceIndex . '#' . $prtInputIndex;
}
if (defined($self->{option_results}->{filter_tray}) && $self->{option_results}->{filter_tray} ne '' &&
$descr !~ /$self->{option_results}->{filter_tray}/) {
$self->{output}->output_add(long_msg => "Skipping tray '$descr': not matching filter.");
next;
}
if (!defined($unit_managed{$unit})) {
$self->{output}->output_add(long_msg => "Skipping input '$descr': unit not managed.");
next;
}
if ($current_value == -1) {
$self->{output}->output_add(long_msg => "Skipping tray '$descr': no level.");
next;
} elsif ($current_value == -2) {
$self->{output}->output_add(long_msg => "Skippinp tray '$descr': level unknown.");
next;
} elsif ($current_value == -3) {
$self->{output}->output_add(long_msg => "Tray '$descr': no level but some space remaining.");
next;
}
my $prct_value = $current_value * 100 / $max_value;
my $exit = $self->{perfdata}->threshold_check(value => $prct_value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
$self->{output}->output_add(long_msg => sprintf("Paper tray '%s': %.2f %%", $descr, $prct_value));
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Paper tray '%s': %.2f %%", $descr, $prct_value));
}
my $label = 'tray_' . $descr;
$self->{output}->perfdata_add(label => $label, unit => '%',
value => sprintf("%.2f", $prct_value),
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'),
min => 0, max => 100);
}
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check paper trays usages.
=over 8
=item B<--warning>
Threshold warning in percent.
=item B<--critical>
Threshold critical in percent.
=item B<--filter-tray>
Filter tray to check (can use a regexp).
=back
=cut
| Sims24/centreon-plugins | hardware/printers/standard/rfc3805/mode/papertray.pm | Perl | apache-2.0 | 6,120 |
#!/usr/bin/env perl
# 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.
BEGIN {
$ENV{CATALYST_SCRIPT_GEN} = 40;
use FindBin qw/$Bin/;
use lib "$Bin/lib";
$ENV{CATALYST_CONFIG} = "$Bin/../ensembl_rest_testing.conf";
# $ENV{ENS_REST_LOG4PERL} = "$Bin/../log4perl_testing.conf";
$ENV{RUNTESTS_HARNESS} = 1;
}
use Catalyst::ScriptRunner;
Catalyst::ScriptRunner->run('EnsEMBL::REST', 'EnsemblTest');
1;
=head1 NAME
ensembl_rest_test_server.pl - Ensembl REST Test Server
=head1 WARNING
THIS SCRIPT DOES *NOT* CLEANUP TEST DATABASES. YOU MUST RUN
t/CLEAN.t MANUALLY.
=head1 SYNOPSIS
ensembl_rest_server.pl [options]
-d --debug force debug mode
-f --fork handle each request in a new process
(defaults to false)
-? --help display this help and exits
-h --host host (defaults to all)
-p --port port (defaults to 3000)
-k --keepalive enable keep-alive connections
-r --restart restart when files get modified
(defaults to false)
-rd --restart_delay delay between file checks
(ignored if you have Linux::Inotify2 installed)
-rr --restart_regex regex match files that trigger
a restart when modified
(defaults to '\.yml$|\.yaml$|\.conf|\.pm$')
--restart_directory the directory to search for
modified files, can be set multiple times
(defaults to '[SCRIPT_DIR]/..')
--follow_symlinks follow symlinks in search directories
(defaults to false. this is a no-op on Win32)
--background run the process in the background
--pidfile specify filename for pid file
See also:
perldoc Catalyst::Manual
perldoc Catalyst::Manual::Intro
=head1 DESCRIPTION
Run a Catalyst Testserver for this application.
=head1 AUTHORS
Catalyst Contributors, see Catalyst.pm
=head1 COPYRIGHT
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
| willmclaren/ensembl-rest | script/ensembl_rest_test_server.pl | Perl | apache-2.0 | 2,794 |
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Users::Command::Account::Details::RemoveLogin;
### Command module to remove a login object linked to the user
### @author hr5
use strict;
use warnings;
use EnsEMBL::Users::Messages qw(MESSAGE_CANT_DELETE_LOGIN);
use base qw(EnsEMBL::Users::Command::Account);
sub process {
my $self = shift;
my $hub = $self->hub;
my $user = $hub->user;
my $logins = { map {$_->login_id => $_} @{$user->rose_object->logins} };
my $login = delete $logins->{$hub->param('id') || 0};
if ($login) {
# can not delete the only login account attached to the user, or any login of type other than openid or local
return $self->redirect_message(MESSAGE_CANT_DELETE_LOGIN) unless keys %$logins && $login->type =~ /^(openid|local)$/;
$login->delete;
}
return $self->ajax_redirect($hub->PREFERENCES_PAGE);
}
1; | andrewyatz/public-plugins | users/modules/EnsEMBL/Users/Command/Account/Details/RemoveLogin.pm | Perl | apache-2.0 | 1,499 |
=head1 LICENSE
Copyright 2010, The WormBase Consortium. 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 WORMBASE CONSORTIUM ``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 <COPYRIGHT HOLDER> 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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of The WormBase Consortium.
=head1 CONTACT
Please email comments or questions to the public WormBase
help list at <help@wormbase.org>.
=cut
package Bio::EnsEMBL::IdMapping::StableIdGenerator::PristionchusPacificus;
# Class to generate WormBase conform Pristionchus IDs to be injected into the mapper
use strict;
use warnings;
use base qw(Bio::EnsEMBL::IdMapping::StableIdGenerator::EnsemblGeneric);
# PPAxxxxx
# ups the id by one
sub increment_stable_id {
my ( $self, $lastId ) = @_;
throw("invalid stable ID: $lastId.") unless ($lastId=~/PPA/);
$lastId =~ /^PPA(\d+)/;
my $number = $1+1;
my $stable_id = sprintf("PPA%05d",$number);
return $stable_id;
}
# just in case it is actually used somewhere
sub is_valid {
my ( $self, $stableId ) = @_;
if ( defined($stableId) && $stableId =~ /^PPA\d+/)
{return 1} else {return undef}
}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl/modules/Bio/EnsEMBL/IdMapping/StableIdGenerator/PristionchusPacificus.pm | Perl | apache-2.0 | 2,415 |
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
# POD documentation - main docs before the code
=pod
=head1 NAME
Bio::EnsEMBL::Compara::RunnableDB::PairwiseSynteny
=cut
=head1 SYNOPSIS
my $db = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $pairwisesynteny = Bio::EnsEMBL::Compara::RunnableDB::PairwiseSynteny->new
(
-db => $db,
-input_id => $input_id,
-analysis => $analysis
);
$pairwisesynteny->fetch_input(); #reads from DB
$pairwisesynteny->run();
$pairwisesynteny->write_output(); #writes to DB
=cut
=head1 DESCRIPTION
This Analysis will take the sequences from a cluster, the cm from
nc_profile and run a profiled alignment, storing the results as
cigar_lines for each sequence.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
package Bio::EnsEMBL::Compara::RunnableDB::PairwiseSynteny;
use strict;
use Time::HiRes qw(time gettimeofday tv_interval);
use base('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
=head2 fetch_input
Title : fetch_input
Usage : $self->fetch_input
Function: Fetches input data from the database
Returns : none
Args : none
=cut
sub fetch_input {
my( $self) = @_;
$self->fetch_pairwise_blasts;
$self->fetch_coordinates;
}
=head2 run
Title : run
Usage : $self->run
Function: runs something
Returns : none
Args : none
=cut
sub run {
my $self = shift;
$self->run_pairwise_synteny;
}
=head2 write_output
Title : write_output
Usage : $self->write_output
Function: stores something
Returns : none
Args : none
=cut
sub write_output {
my $self = shift;
}
##########################################
#
# internal methods
#
##########################################
1;
sub run_pairwise_synteny {
my $self = shift;
return 1;
}
sub fetch_pairwise_blasts {
my $self = shift;
my $gdba = $self->compara_dba->get_GenomeDBAdaptor;
my @genome_dbs = @{ $self->param('gdbs') };
my $genome_db1 = $gdba->fetch_by_dbID($genome_dbs[0]);
my $genome_db2 = $gdba->fetch_by_dbID($genome_dbs[1]);
my $tmp = $self->worker_temp_directory;
unlink </tmp/*.blasts>;
$self->fetch_cross_distances($genome_db1,$genome_db2,1);
$self->fetch_cross_distances($genome_db2,$genome_db1,2);
return 1;
}
sub fetch_cross_distances {
my $self = shift;
my $gdb = shift;
my $gdb2 = shift;
my $filename_prefix = shift;
my $starttime = time();
my $gdb_id = $gdb->dbID;
my $species_name = lc($gdb->name);
$species_name =~ s/\ /\_/g;
my $tbl_name = 'peptide_align_feature_'.$gdb_id;
my $gdb_id2 = $gdb2->dbID;
my $sql = "SELECT ".
"concat(qmember_id,' ',hmember_id,' ',score) ".
"FROM $tbl_name where hgenome_db_id=$gdb_id2";
print("$sql\n");
my $sth = $self->dbc->prepare($sql);
$sth->execute();
printf("%1.3f secs to execute\n", (time()-$starttime));
print(" done with fetch\n");
my $gdb_filename = $gdb_id if (1 == $filename_prefix);
$gdb_filename = $gdb_id2 if (2 == $filename_prefix);
my $filename = $self->worker_temp_directory . "$gdb_filename.blasts";
# We append all blasts in one file
open FILE, ">>$filename" or die $!;
while ( my $row = $sth->fetchrow ) {
print FILE "$row\n";
}
$sth->finish;
close FILE;
printf("%1.3f secs to process\n", (time()-$starttime));
return 1;
}
sub fetch_coordinates {
my $self = shift;
my $starttime = time();
foreach my $genome_db_id (@{ $self->param('gdbs') }) {
my $sql = "SELECT ".
"concat(m2.member_id,' ',m1.chr_name,' ',m1.chr_start,' ',m1.chr_end,' ',if(m1.chr_strand=1,'-','+')) ".
"FROM member m1, member m2 ".
"WHERE m2.member_id=m1.canonical_member_id and ".
"m1.genome_db_id=$genome_db_id";
print("$sql\n");
my $sth = $self->dbc->prepare($sql);
$sth->execute();
printf("%1.3f secs to execute\n", (time()-$starttime));
print(" done with fetch\n");
my $filename = $self->worker_temp_directory . "/" . "$genome_db_id.coordinates";
# We append all blasts in one file
open FILE, ">$filename" or die $!;
while ( my $row = $sth->fetchrow ) {
print FILE "$row\n";
}
$sth->finish;
close FILE;
printf("%1.3f secs to process\n", (time()-$starttime));
}
$DB::single=1;1;
return 1;
}
| dbolser-ebi/ensembl-compara | modules/Bio/EnsEMBL/Compara/RunnableDB/PairwiseSynteny.pm | Perl | apache-2.0 | 5,311 |
#! /usr/bin/perl
eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
& eval 'exec perl -w -S $0 $argv:q'
if 0;
# ******************************************************************
# Author: Chad Elliott
# Date: 4/8/2004
# $Id: clone_build_tree.pl 2092 2012-03-07 21:32:25Z johnsonb $
# Description: Clone a build tree into an alternate location.
# This script is a rewrite of create_ace_build.pl and
# does not restrict the user to place the build
# in any particular location or that it be used with
# ACE_wrappers. Some of the functions were barrowed
# from create_ace_build.pl, but were modified quite a
# bit.
# ******************************************************************
# ******************************************************************
# Pragma Section
# ******************************************************************
use strict;
use Cwd;
use FileHandle;
use File::Copy;
use File::Find;
use File::Path;
use File::stat;
use File::Basename;
# ******************************************************************
# Data Section
# ******************************************************************
my $exclude;
my @foundFiles;
my $verbose = 0;
my $lbuildf = 0;
my $lnonbuildf = 0;
my $version = '1.16';
eval 'symlink("", "");';
my $hasSymlink = ($@ eq '');
# ******************************************************************
# Subroutine Section
# ******************************************************************
sub findCallback {
my $matches = !(/^CVS\z/s && ($File::Find::prune = 1) ||
/^\.svn\z/s && ($File::Find::prune = 1) ||
defined $exclude &&
/^$exclude\z/s && ($File::Find::prune = 1) ||
/^\.cvsignore\z/s && ($File::Find::prune = 1) ||
/^\..*obj\z/s && ($File::Find::prune = 1) ||
/^Templates\.DB\z/s && ($File::Find::prune = 1) ||
/^Debug\z/s && ($File::Find::prune = 1) ||
/^Release\z/s && ($File::Find::prune = 1) ||
/^Static_Debug\z/s && ($File::Find::prune = 1) ||
/^Static_Release\z/s && ($File::Find::prune = 1)
);
if ($matches) {
if(!$lnonbuildf) {
$matches &&= (! -l $_ &&
! ( -f $_ && /^core\z/s) &&
! /^.*\.rej\z/s &&
! /^.*\.state\z/s &&
! /^.*\.so\z/s &&
! /^.*\.[oa]\z/s &&
! /^.*\.dll\z/s &&
! /^.*\.lib\z/s &&
! /^.*\.obj\z/s &&
! /^.*~\z/s &&
! /^\.\z/s &&
! /^\.#.*\z/s &&
! /^.*\.ncb\z/s &&
! /^.*\.opt\z/s &&
! /^.*\.bak\z/s &&
! /^.*\.suo\z/s &&
! /^.*\.ilk\z/s &&
! /^.*\.pdb\z/s &&
! /^.*\.pch\z/s &&
! /^.*\.log\z/s &&
! ( -f $_ && /^.*\.d\z/s )
);
}
if ($matches) {
if (!$lbuildf) {
$matches = (! /^.*\.dsp\z/s &&
! /^.*\.dsw\z/s &&
! /^.*\.vcproj\z/s &&
! /^.*\.sln\z/s &&
! /^Makefile.*\z/s &&
! /^GNUmakefile.*\z/s &&
! /^.*\.am\z/s &&
! /^\.depend\..*\z/s &&
! /^.*\.vcn\z/s &&
! /^.*\.vcp\z/s &&
! /^.*\.vcw\z/s &&
! /^.*\.vpj\z/s &&
! /^.*\.vpw\z/s &&
! /^.*\.cbx\z/s &&
! /^.*\.bpgr\z/s &&
! /^.*\.bmak\z/s &&
! /^.*\.bmake\z/s &&
! /^.*\.mak\z/s &&
! /^.*\.nmake\z/s &&
! /^.*\.bld\z/s &&
! /^.*\.icc\z/s &&
! /^.*\.icp\z/s &&
! /^.*\.project\z/s &&
! /^.*\.wrproject\z/s &&
! /^.*\.wrmakefile\z/s &&
! /^.*\.vxtest\z/s
);
}
if ($matches) {
## Remove the beginning dot slash as we save the file
push(@foundFiles, $File::Find::name);
$foundFiles[$#foundFiles] =~ s/^\.[\\\/]+//;
}
}
}
}
sub getFileList {
File::Find::find({wanted => \&findCallback}, '.');
return \@foundFiles;
}
sub backupAndMoveModified {
my($realpath, $linkpath) = @_;
my $mltime = -M $linkpath;
my $mrtime = -M $realpath;
my $status = 1;
## -M returns the number of days since modification. Therefore,
## a smaller time means that it has been modified more recently.
## This is different than what stat() returns.
## If the hard linked file is newer than the original file, that means
## the link has been broken by something and needs to be "fixed". We
## will back up the original file and move the modified file into it's
## place.
if ($mltime < $mrtime) {
$status = 0;
## Move the real file to a backup
unlink("$realpath.bak");
if (rename($realpath, "$realpath.bak")) {
## Move the linked file to the real file name
if (move($linkpath, $realpath)) {
$status = 1;
}
else {
## The move failed, so we will attempt to put
## the original file back.
unlink($realpath);
rename("$realpath.bak", $realpath);
}
}
}
elsif ($mltime != $mrtime || -s $linkpath != -s $realpath) {
## The two files are different in some way, we need to make a backup
## so that we don't cause a loss of data/work.
$status = 0;
}
if (!$status) {
## We were not able to properly deal with this file. We will
## attempt to preserve the modified file.
unlink("$linkpath.bak");
rename($linkpath, "$linkpath.bak");
}
}
sub hardlink {
my($realpath, $linkpath) = @_;
if ($^O eq 'MSWin32' && ! -e $realpath) {
## If the real file "doesn't exist", then we need to
## look up the short file name.
my $short = Win32::GetShortPathName($realpath);
## If we were able to find the short file name, then we need to
## try again.
if (defined $short) {
$realpath = $short;
}
else {
## This should never happen, but there appears to be a bug
## with the underlying Win32 APIs on Windows Server 2003.
## Long paths will cause an error which perl will ignore.
## Unicode versions of the APIs seem to work fine.
## To experiment try Win32 _fullpath() and CreateHardLink with
## long paths.
print "WARNING: Skipping $realpath.\n";
return 1;
}
}
return link($realpath, $linkpath);
}
sub symlinkFiles {
my($files, $fullbuild, $dmode, $startdir, $absolute) = @_;
my $sdlength = length($startdir) + 1;
my $partial = ($absolute ? undef :
substr($fullbuild, $sdlength,
length($fullbuild) - $sdlength));
foreach my $file (@$files) {
my $fullpath = "$fullbuild/$file";
if (-e $fullpath) {
## We need to make sure that we're not attempting to mix hardlinks
## and softlinks.
if (! -d $fullpath && ! -l $fullpath) {
my $stat = stat($fullpath);
if ($stat->nlink() > 1) {
print STDERR "ERROR: Attempting to mix softlinks ",
"with a hardlink build.\n",
"$fullpath has ", $stat->nlink(), " links.\n";
return 1;
}
}
}
else {
if (-d $file) {
if ($verbose) {
print "Creating $fullpath\n";
}
if (!mkpath($fullpath, 0, $dmode)) {
print STDERR "ERROR: Unable to create $fullpath\n";
return 1;
}
}
else {
if ($absolute) {
if ($verbose) {
print "symlink $startdir/$file $fullpath\n";
}
if (!symlink("$startdir/$file", $fullpath)) {
print STDERR "ERROR: Unable to symlink $fullpath\n";
return 1;
}
}
else {
my $buildfile = "$partial/$file";
my $slashcount = ($buildfile =~ tr/\///);
my $real = ($slashcount == 0 ? './' : ('../' x $slashcount)) .
$file;
print "symlink $real $fullpath\n" if ($verbose);
if (!symlink($real, $fullpath)) {
print STDERR "ERROR: Unable to symlink $fullpath\n";
return 1;
}
}
}
}
}
## Remove links that point to non-existant files. The subroutine is
## now anonymous to avoid the "will not stay shared" warning for %dirs.
my %dirs;
File::Find::find({wanted => sub {
if (-l $_ && ! -e $_) {
unlink($_);
$dirs{$File::Find::dir} = 1;
if ($verbose) {
print "Removing $File::Find::dir/$_\n";
}
}
}
}, $fullbuild);
foreach my $key (keys %dirs) {
rmdir($key);
}
return 0;
}
sub hardlinkFiles {
my($files, $fullbuild, $dmode, $startdir) = @_;
my @hardlinks;
foreach my $file (@$files) {
my $fullpath = "$fullbuild/$file";
if (-d $file) {
if (! -e $fullpath) {
if ($verbose) {
print "Creating $fullpath\n";
}
if (!mkpath($fullpath, 0, $dmode)) {
print STDERR "ERROR: Unable to create $fullpath\n";
return 1;
}
}
}
else {
if (-e $fullpath) {
## We need to make sure that we're not attempting to mix hardlinks
## and softlinks.
if (-l $fullpath) {
print STDERR "ERROR: Attempting to mix hardlinks ",
"with a softlink build.\n",
"$fullpath is a softlink.\n";
return 1;
}
backupAndMoveModified($file, $fullpath);
}
if (! -e $fullpath) {
if ($verbose) {
print "hardlink $file $fullpath\n";
}
if (!hardlink($file, $fullpath)) {
print STDERR "ERROR: Unable to link $fullpath\n";
return 1;
}
}
## If we successfully linked the file or it already exists,
## we need to keep track of it.
push(@hardlinks, $file);
}
}
## Remove links that point to non-existant files
my $lfh = new FileHandle();
my $txt = "$fullbuild/clone_build_tree.links";
if (open($lfh, $txt)) {
my %dirs;
while(<$lfh>) {
my $line = $_;
$line =~ s/\s+$//;
if (! -e $line) {
my $full = "$fullbuild/$line";
unlink($full);
$dirs{dirname($full)} = 1;
print "Removing $full\n" if ($verbose);
}
}
close($lfh);
foreach my $key (keys %dirs) {
rmdir($key);
}
}
## Rewrite the link file.
unlink($txt);
if (open($lfh, ">$txt")) {
foreach my $file (@hardlinks) {
print $lfh "$file\n";
}
close($lfh);
}
return 0;
}
sub linkFiles {
my($absolute, $dmode, $hardlink, $builddir, $builds) = @_;
my $status = 0;
my $starttime = time();
my $startdir = getcwd();
## Ensure that the build directory exists and is writable
mkpath($builddir, 0, $dmode);
if (! -d $builddir || ! -w $builddir) {
print STDERR "ERROR: Unable to create or write to $builddir\n";
return 1;
}
## Search for the clonable files
print "Searching $startdir for files...\n";
my $files = getFileList();
my $findtime = time() - $starttime;
print 'Found ', scalar(@$files), ' files and directories in ',
$findtime, ' second', ($findtime == 1 ? '' : 's'), ".\n";
foreach my $build (@$builds) {
my $fullbuild = "$builddir/$build";
## Create all of the links for this build
if (-d $fullbuild) {
print "Updating $fullbuild\n";
}
else {
print "Creating $fullbuild\n";
mkpath($fullbuild, 0, $dmode);
}
if ($hardlink) {
$status += hardlinkFiles($files, $fullbuild, $dmode, $startdir);
}
else {
$status += symlinkFiles($files, $fullbuild,
$dmode, $startdir, $absolute);
}
print "Finished in $fullbuild\n";
}
print 'Total time: ', time() - $starttime, " seconds.\n" if ($status == 0);
return $status;
}
sub usageAndExit {
my $msg = shift;
print STDERR "$msg\n" if (defined $msg);
my $base = basename($0);
my $spc = ' ' x (length($base) + 8);
print STDERR "$base v$version\n\n",
"Create a tree identical in layout to the current directory\n",
"with the use of ", ($hasSymlink ? "symbolic links or " : ''),
"hard links.\n\n",
"Usage: $base [-b <builddir>] [-d <dmode>] [-f] [-n]",
($hasSymlink ? "[-a] [-l] " : ''),
"[-v]\n",
$spc, "[build names...]\n\n",
($hasSymlink ?
"-a Use absolute paths when creating soft links.\n" .
"-l Use hard links instead of soft links.\n" : ''),
"-b Set the build directory. It defaults to the ",
"<current directory>/build.\n",
"-d Set the directory permissions mode.\n",
"-f Link build files (Makefile, .dsw, .sln, .etc).\n",
"-n Link non-build files normally avoided (.o,.so, etc.).\n",
"-s Set the start directory. It defaults to the ",
"<current directory>.\n",
"-v Enable verbose mode.\n";
exit(0);
}
# ******************************************************************
# Main Section
# ******************************************************************
my $dmode = 0777;
my $absolute = 0;
my $hardlink = !$hasSymlink;
my $builddir;
my @builds;
my $startdir;
for(my $i = 0; $i <= $#ARGV; ++$i) {
if ($ARGV[$i] eq '-a') {
$absolute = 1;
}
elsif ($ARGV[$i] eq '-b') {
++$i;
if (defined $ARGV[$i]) {
$builddir = $ARGV[$i];
## Convert backslashes to slashes
$builddir =~ s/\\/\//g;
## Remove trailing slashes
$builddir =~ s/\/+$//;
## Remove duplicate slashes
while($builddir =~ s/\/\//\//g) {
}
}
else {
usageAndExit('-b requires an argument');
}
}
elsif ($ARGV[$i] eq '-d') {
++$i;
if (defined $ARGV[$i]) {
$dmode = $ARGV[$i];
}
else {
usageAndExit('-d requires an argument');
}
}
elsif ($ARGV[$i] eq '-f') {
$lbuildf = 1;
}
elsif ($ARGV[$i] eq '-l') {
$hardlink = 1;
}
elsif ($ARGV[$i] eq '-n') {
$lnonbuildf = 1;
}
elsif ($ARGV[$i] eq '-v') {
$verbose = 1;
}
elsif ($ARGV[$i] eq '-s') {
++$i;
if (defined $ARGV[$i]) {
$startdir = $ARGV[$i];
}
else {
usageAndExit('-s requires an argument');
}
}
elsif ($ARGV[$i] =~ /^-/) {
usageAndExit('Unknown option: ' . $ARGV[$i]);
}
else {
push(@builds, $ARGV[$i]);
}
}
if (defined $startdir && !chdir($startdir)) {
print "ERROR: Unable to change directory to $startdir\n";
exit(1);
}
$builddir = getcwd() . '/build' if (!defined $builddir);
if (index($builddir, getcwd()) == 0) {
$exclude = substr($builddir, length(getcwd()) + 1);
$exclude =~ s/([\+\-\\\$\[\]\(\)\.])/\\$1/g;
$exclude =~ s/.*?([^\/]+)$/$1/;
}
else {
$absolute = 1;
}
if (!defined $builds[0]) {
my $cwd = getcwd();
if (chdir($builddir)) {
@builds = glob('*');
chdir($cwd);
}
else {
usageAndExit('There are no builds to update.');
}
}
exit(linkFiles($absolute, $dmode, $hardlink, $builddir, \@builds));
| batmancn/TinySDNController | ACE_wrappers/MPC/clone_build_tree.pl | Perl | apache-2.0 | 16,290 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::azure::database::cosmosdb::mode::availability;
use base qw(cloud::azure::custom::mode);
use strict;
use warnings;
sub get_metrics_mapping {
my ($self, %options) = @_;
my $metrics_mapping = {
'serviceavailability' => {
'output' => 'Service Availability',
'label' => 'service-availability-percentage',
'nlabel' => 'cosmosdb.account.service.availability.percentage',
'unit' => '%',
'min' => '0',
'max' => '100'
}
};
return $metrics_mapping;
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'filter-metric:s' => { name => 'filter_metric' },
'resource:s' => { name => 'resource' },
'resource-group:s' => { name => 'resource_group' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') {
$self->{output}->add_option_msg(short_msg => 'Need to specify either --resource <name> with --resource-group option or --resource <id>.');
$self->{output}->option_exit();
}
my $resource = $self->{option_results}->{resource};
my $resource_group = defined($self->{option_results}->{resource_group}) ? $self->{option_results}->{resource_group} : '';
if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.DocumentDB\/databaseAccounts\/(.*)$/) {
$resource_group = $1;
$resource = $2;
}
$self->{az_resource} = $resource;
$self->{az_resource_group} = $resource_group;
$self->{az_resource_type} = 'databaseAccounts';
$self->{az_resource_namespace} = 'Microsoft.DocumentDB';
$self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 3600;
$self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : 'PT1H';
$self->{az_aggregations} = ['Average'];
if (defined($self->{option_results}->{aggregation})) {
$self->{az_aggregations} = [];
foreach my $stat (@{$self->{option_results}->{aggregation}}) {
if ($stat ne '') {
push @{$self->{az_aggregations}}, ucfirst(lc($stat));
}
}
}
foreach my $metric (keys %{$self->{metrics_mapping}}) {
next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne ''
&& $metric !~ /$self->{option_results}->{filter_metric}/);
push @{$self->{az_metrics}}, $metric;
}
}
1;
__END__
=head1 MODE
Check Azure Cosmos DB Accounts availability statistics.
Example:
Using resource name :
perl centreon_plugins.pl --plugin=cloud::azure::database::cosmosdb::plugin --mode=availability --custommode=api
--resource=<cosmosdbaccount_id> --resource-group=<resourcegroup_id> --aggregation='average'
--warning-service-availability-percentage='90:' --critical-service-availability-percentage='80:'
Using resource id :
perl centreon_plugins.pl --plugin=cloud::azure::database::cosmosdb::plugin --mode=availability --custommode=api
--resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.DocumentDB/databaseAccounts/<cosmosdbaccount_id>'
--aggregation='average' --warning-service-availability-percentage='90:' --critical-service-availability-percentage='80:'
Default aggregation: 'average' / 'total', 'minimum' and 'maximum' are valid.
=over 8
=item B<--resource>
Set resource name or id (Required).
=item B<--resource-group>
Set resource group (Required if resource's name is used).
=item B<--warning-service-availability-percentage>
Warning threshold.
=item B<--critical-service-availability-percentage>
Critical threshold.
=back
=cut
| Tpo76/centreon-plugins | cloud/azure/database/cosmosdb/mode/availability.pm | Perl | apache-2.0 | 4,810 |
#
# 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 network::sophos::es::snmp::mode::health;
use base qw(centreon::plugins::templates::hardware);
use strict;
use warnings;
sub set_system {
my ($self, %options) = @_;
$self->{cb_hook2} = 'snmp_execute';
$self->{thresholds} = {
default => [
['unknown', 'OK'],
['disabled', 'OK'],
['ok', 'OK'],
['warn', 'WARNING'],
['error', 'CRITICAL']
]
};
$self->{components_path} = 'network::sophos::es::snmp::mode::components';
$self->{components_module} = ['component', 'system'];
}
sub snmp_execute {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request});
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_absent => 1, no_performance => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
});
return $self;
}
1;
__END__
=head1 MODE
Check health status.
=over 8
=item B<--component>
Which component to check (Default: '.*').
Can be: 'component', 'system'.
=item B<--filter>
Exclude some parts (comma seperated list)
Can also exclude specific instance: --filter=system,MailDiskUsage
=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='component,UNKNOWN,unknown'
=back
=cut
| centreon/centreon-plugins | network/sophos/es/snmp/mode/health.pm | Perl | apache-2.0 | 2,450 |
package AnyJob::Worker::Context::Base;
###############################################################################
# Convenient base class which all specific worker context modules should extend.
#
# Author: LightStar
# Created: 05.03.2018
# Last update: 07.03.2018
#
use strict;
use warnings;
use utf8;
###############################################################################
# Construct new AnyJob::Worker::Context::Base object.
#
# Arguments:
# parent - parent component which is usually AnyJob::Worker object.
# Returns:
# AnyJob::Worker::Context::Base object.
#
sub new {
my $class = shift;
my %args = @_;
my $self = bless \%args, $class;
unless (defined($self->{parent})) {
require Carp;
Carp::confess('No parent provided');
}
return $self;
}
###############################################################################
# Returns:
# parent component which is usually AnyJob::Worker object.
#
sub parent {
my $self = shift;
return $self->{parent};
}
###############################################################################
# Returns:
# string current node name.
#
sub node {
my $self = shift;
return $self->{parent}->node;
}
###############################################################################
# Write debug message to log.
#
# Arguments:
# message - string debug message.
#
sub debug {
my $self = shift;
my $message = shift;
$self->{parent}->debug($message);
}
###############################################################################
# Write error message to log.
#
# Arguments:
# message - string error message.
#
sub error {
my $self = shift;
my $message = shift;
$self->{parent}->error($message);
}
###############################################################################
# Called by worker component after finishing all processing. You can override it to clean any resources.
#
sub stop {
my $self = shift;
}
1;
| lightstar/anyjob | lib/AnyJob/Worker/Context/Base.pm | Perl | apache-2.0 | 1,999 |
#!/usr/bin/env perl
use strict;
use Bio::EnsEMBL::Registry;
use File::Spec;
use Bio::EnsEMBL::Funcgen::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Hive::DBSQL::DBConnection;
use Getopt::Long;
my $registry;
my $species;
my $gff_file;
my $bed_file;
my $min_id;
my $max_id;
my $feature_set_id;
GetOptions (
'registry=s' => \$registry,
'species=s' => \$species,
'gff_file=s' => \$gff_file,
'bed_file=s' => \$bed_file,
'min_id=s' => \$min_id,
'max_id=s' => \$max_id,
'feature_set_id=s' => \$feature_set_id,
);
Bio::EnsEMBL::Registry->load_all($registry);
use Bio::EnsEMBL::Utils::Logger;
my $logger = Bio::EnsEMBL::Utils::Logger->new();
use Bio::EnsEMBL::Funcgen::Utils::FtpUtils qw( create_file_handle );
my $ontology_term_adaptor = Bio::EnsEMBL::Registry->get_adaptor( 'Multi', 'Ontology', 'OntologyTerm' );
my $gff_fh = create_file_handle($gff_file);
use Bio::EnsEMBL::Utils::IO::GFFSerializer;
my $gff_serializer = Bio::EnsEMBL::Utils::IO::GFFSerializer->new(
$ontology_term_adaptor,
$gff_fh
);
my $bed_fh = create_file_handle($bed_file);
use Bio::EnsEMBL::Utils::IO::BEDSerializer;
my $bed_serializer = Bio::EnsEMBL::Utils::IO::BEDSerializer->new(
$bed_fh
);
my @batch_constraint_list;
if ($min_id) {
push @batch_constraint_list, qq(annotated_feature_id>=$min_id);
}
if ($max_id) {
push @batch_constraint_list, qq(annotated_feature_id<=$max_id);
}
if ($feature_set_id) {
push @batch_constraint_list, qq(feature_set_id=$feature_set_id);
}
my $batch_constraint = join ' and ', @batch_constraint_list;
my $annotated_feature_adaptor = Bio::EnsEMBL::Registry->get_adaptor( $species, 'Funcgen', 'AnnotatedFeature' );
my $funcgen_adaptor = Bio::EnsEMBL::Registry->get_DBAdaptor( $species, 'Funcgen' );
my $helper = Bio::EnsEMBL::Utils::SqlHelper->new(
-DB_CONNECTION => $funcgen_adaptor->dbc
);
my $number_of_annotated_features = $helper->execute_simple(
-SQL => "select count(annotated_feature_id) from annotated_feature where $batch_constraint",
)->[0];
$logger->info("About to export " . $number_of_annotated_features ." annotated features\n");
my $progressbar_id = $logger->init_progress($number_of_annotated_features, 100);
my $i=0;
my $last_id = 0;
my $exported_something = 1;
my $batch_size = 1000;
while ($exported_something) {
$exported_something = undef;
$helper->execute_no_return(
-SQL => "select annotated_feature_id from annotated_feature where annotated_feature_id > ? and $batch_constraint order by annotated_feature_id limit ?",
-PARAMS => [ $last_id, $batch_size ],
-CALLBACK => sub {
my @row = @{ shift @_ };
my $annotated_feature_id = $row[0];
my $annotated_feature = $annotated_feature_adaptor->fetch_by_dbID($annotated_feature_id);
eval {
$gff_serializer->print_feature($annotated_feature);
$bed_serializer->print_feature($annotated_feature);
};
if ($@) {
use Carp;
confess(
"Unable to serialise feature! dbid:"
. $annotated_feature->dbID
);
}
# This prevents memory leaks.
undef %$annotated_feature;
$exported_something = 1;
$last_id = $annotated_feature_id;
return;
},
);
$i+=$batch_size;
$logger->log_progressbar($progressbar_id, $i);
}
$logger->info("Export done.\n");
$gff_fh->close;
$bed_fh->close;
# Make sure that empty files exist so subsequent analyses don't fail.
# The gff serialiser might not be creating a file,
#
if (-z $gff_file) {
`touch $gff_file`;
}
if (-z $bed_file) {
`touch $bed_file`;
}
| Ensembl/ensembl-funcgen | scripts/export/export_alignments.pl | Perl | apache-2.0 | 3,510 |
# perfd.pl - PerfStat Daemon
use warnings;
use IO::Socket qw(:DEFAULT :crlf);
use CGI::Carp qw(carpout);
use IO::File;
use File::Copy;
use Mail::Sendmail;
use POSIX qw(:sys_wait_h :errno_h sys_wait_h);
use Fcntl qw(:DEFAULT);
use Storable qw(lock_retrieve lock_store freeze thaw);
use Host;
use Service;
use Metric;
use Graph;
use User;
use NotifyRules;
use vars qw($pid $host $IP $port $buffer $os $service $data @data $found $alert $event $event_time $msg);
my $ppid=$$;
my $quit = 0;
# Set umask
umask(0007);
# Slurp in path to Perfhome
my $perfhome=&PATH;
$perfhome =~ s/\/bin//;
# Slurp in Configuration
my %conf = ();
&GetConfiguration(\%conf);
# Set Environment Variables from %conf
foreach $key (keys %conf) {
$ENV{$key}="$conf{$key}";
}
# Save PID in file
open(PID, "> $perfhome/tmp/perfd.pid")
or die "ERROR: Couldn't open file $perfhome/tmp/perfd.pid: $!\n";
print PID "$ppid\n";
close (PID);
# Log start time
my $time=time;
open(TIME, "> $perfhome/tmp/perfd.time")
or die "ERROR: Couldn't open file $perfhome/tmp/perfd.time: $!\n";
print TIME "$time\n";
close (TIME);
# Log all alerts and warnings to the below logfile
my $logfile = "$perfhome/var/logs/perfd.log";
open(LOGFILE, ">> $logfile")
or die "ERROR: Unable to append to $logfile: $!\n";
carpout(*LOGFILE);
# Define Signal Handling
$SIG{INT} = $SIG{TERM} = sub { $quit++ };
$SIG{CHLD} = sub { while ( waitpid(-1, WNOHANG)>0 ) { } };
# Open Socket
my $socket = IO::Socket::INET->new( Proto => "tcp",
LocalAddr => "$ENV{'SERVERIP'}:$ENV{'SERVERPORT'}",
Type => SOCK_STREAM,
Reuse => 1,
Listen => SOMAXCONN,
Timeout => 30)
or die "ERROR: Couldn't open Socket on IP: $ENV{'SERVERIP'} Port: $ENV{'SERVERPORT'} : $@\n";
# Main body of program
while (!$quit) {
# Accept socket connection
next unless my $session = $socket->accept;
# Get the Hostname/IP of the client
$host = gethostbyaddr($session->peeraddr,AF_INET) || $session->peerhost;
$IP = $session->peerhost;
my $port = $session->peerport;
warn "DEBUG: Connection from [$host,$port] Established\n" if ($ENV{'DEBUG'});
# Fork off new child process for every connection
$pid = fork();
die "ERROR: Cannot Fork: $!" unless (defined $pid);
warn "DEBUG: Child PID is $pid\n" if ($ENV{'DEBUG'});
if ($pid == 0) {
# Close Child porcesses copy of socket connection
$socket->close;
# Load host/service data and populate hostIndex
#&LoadHostData; # Load hosts updated host data into hostIndex
#&LoadHostServiceData; # Load hosts updated service data into hostIndex
# Process incomming data from client
$buffer = <$session>;
if (! defined $buffer) {
warn "WARNING: Connection from $host established, but 0 bytes sent\n";
exit (1);
}
&MaxBytes; # Determine if max allowable bytes were sent
# Get OS for use in SetHostDefaults
$buffer =~ m/(\S+)\s+/;
$preOS=$1;
&VERIFY_HOST; # Ensure client is allowed to connect
&CREATE_DIRS; # Create host based directories if needed
&HOST_STATUS; # Create timestamp for host
# Exit if unexpected data is sent
if ($buffer !~ m/data|info/) {
warn "ERROR: Invalid data sent from $host\n";
exit(1);
}
&SetHostDefaults; # Create default serialized host data for host
# Remove any newlines from buffer
$buffer =~ s/\n//g;
warn "DEBUG: Buffer contains - $buffer\n" if ($ENV{'DEBUG'});
# Split data into array for parsing
my @allData=split(":", $buffer);
# Handle communication from client or FE
foreach my $line (@allData) {
if ($line =~ m/^$preOS\s+data/) {
&DATA($line); # Handle data sent from clients
warn "DEBUG: Connection from [$host,$port] finished\n" if ($ENV{'DEBUG'});
} elsif ($line =~ m/^$preOS\s+info/) {
&INFO($line); # Handle info sent from clients
warn "DEBUG: Connection from [$host,$port] finished\n" if ($ENV{'DEBUG'});
}
}
# All processing complete exit from Child process
exit(0);
}
# Close socket connection from parent process and wait for new connection
$session->close;
}
# Handle data sent from clients
sub DATA {
# Slurp in DATA
my $line=shift;
# Get current time in epoch
my $time=time;
$line =~ m/(\S+)\s+\S+\s+(\S+)\s+(\d*.*)/gi;
#exit(1) if ($3 eq "" || ! $3 =~ m/\d.*/ || $line eq "\015\012");
# Assign the recieved data to some scalars to be referenced later
$os = "$1"; $service = "$2"; $data = "$3";
# Check OS
if ($os !~ m/Linux|SunOS|WindowsNT/) {
warn "ERROR: $os not supported at this time!\n";
exit(1);
}
if ($data =~ m/^[A-Za-z\/]/ || $data =~ m/^[1-9]/ && $data =~ m/[A-Za-z\/]/) {
# Parse device and data since a device is present
$data =~ m/(\S*)\s+(\d*.*)/;
$device="$1";
$data="$2";
# Get rid of wild characters for device
$device =~ s/[\!\@\#\$\%\^\&\(\)\_\=\+\-\/\*]//g;
}
# RRDs don't need the sub-service
$NoSubService="$service";
# Check to ensure only numeric characters exist in data
if ($data =~ m/[A-Za-z]/) {
warn "ERROR: Data contains non-numeric character! $host $service data: $data\n";
exit(1);
}
# Include sub-service in service name if defined
if (defined $device) {
$service="$service.$device";
}
# Check to ensure sub-service isn't null
if ($service =~ m/\.$/) {
warn "ERROR: Sub-service is null for service $NoSubService!\n";
exit(1);
}
@data=split(" ", $data);
# Debugging output if set
warn "DEBUG: $os:$service:$data\n" if ($ENV{'DEBUG'});
&SetServiceDefaults; # Create default serialized service data for host
# Serialize service lastUpdate to hostIndex
if (defined $hostIndex->{$host}->{serviceIndex}->{$service}) {
$hostIndex->{$host}->{serviceIndex}->{$service}->setLastUpdate($time);
}
#&SetHostDefaults; # Create default serialized host data for host
&RRD; # Take parsed data and store in RRD
&EVENT_PARSE; # Log Event Thresholds/Notification
if (defined $device) {
undef $device;
}
}
# Update configuration for host
sub INFO {
# Slurp in DATA
my $line=shift;
$line =~ m/(\S+)\s+\S+\s+(.*)/gi;
$os="$1";
$info="$2";
# Debugging output if set
warn "DEBUG: INFO for $host sent\n" if ($ENV{'DEBUG'});
# Split info into array for parsing
my @allInfo=split(" ", $info);
# Organize host info
my $cpuNum=$allInfo[0];
my $cpuModel=$allInfo[1];
my $cpuSpeed=$allInfo[2];
my $memTotal=$allInfo[3];
#my $swapTotal=$allInfo[4];
my $osVer=$allInfo[4];
my $kernelVer=$allInfo[5];
my $patches=$allInfo[6];
my @patchesArray=split(",", $patches);
my $patchesArrayRef=\@patchesArray;
#warn "INFO: CPU Num: $cpuNum Model: $cpuModel Speed: $cpuSpeed Mem Total: $memTotal OsVer: $osVer Kernel Ver: $kernelVer @patchesArray\n";
# Update host info
my %hostUpdate=();
$hostUpdate=&HOST_UPDATE;
$hostUpdate->{$host}->setCpuNum($cpuNum);
$hostUpdate->{$host}->setCpuModel($cpuModel);
$hostUpdate->{$host}->setCpuSpeed($cpuSpeed);
$hostUpdate->{$host}->setMemTotal($memTotal);
#$hostUpdate->{$host}->setSwapTotal($swapTotal);
$hostUpdate->{$host}->setOsVer($osVer);
$hostUpdate->{$host}->setKernelVer($kernelVer);
$hostUpdate->{$host}->{patchesArray}=$patchesArrayRef;
# Serialize host data
$hostUpdate->{$host}->lock_store("$perfhome/var/db/hosts/$host/$host.ser")
or die "ERROR: Can't store $perfhome/var/db/hosts/$host/$host.ser\n";
}
# Determine Max bytes allowed
sub MaxBytes {
# Determine if data exceeds max number of bytes
my $bytes_in += length($buffer);
if ($bytes_in >= $ENV{'MAXBYTES'}) {
warn "ERROR: $host sent $bytes_in bytes, the maximum bytes allowed is $ENV{'MAXBYTES'} bytes\n";
exit(1)
}
warn "DEBUG: $host sent $bytes_in bytes\n" if ($ENV{'DEBUG'});
}
# Get time in Epoch format to check hosts status
sub HOST_STATUS {
# Get current time in epoch
my $time=time;
# Serialize host lastUpdate to hostIndex
if (defined $hostIndex->{$host}{lastUpdate}) {
$hostIndex->{$host}->setLastUpdate($time);
# Set last update
my %hostUpdate=();
$hostUpdate=&HOST_UPDATE;
$hostUpdate->{$host}->setLastUpdate($time);
# Serialize host data
$hostUpdate->{$host}->lock_store("$perfhome/var/db/hosts/$host/$host.ser")
or die "ERROR: Can't store $perfhome/var/db/hosts/$host/$host.ser\n";
}
}
# Update host information (Serialize)
sub HOST_UPDATE {
# Get current host settings
my $time=time;
my $OS=$hostIndex->{$host}->getOS();
my $IP=$hostIndex->{$host}->getIP();
my $owner=$hostIndex->{$host}->getOwner();
my $cpuNum=$hostIndex->{$host}->getCpuNum();
my $cpuModel=$hostIndex->{$host}->getCpuModel();
my $cpuSpeed=$hostIndex->{$host}->getCpuSpeed();
my $memTotal=$hostIndex->{$host}->getMemTotal();
#my $swapTotal=$hostIndex->{$host}->getSwapTotal();
my $osVer=$hostIndex->{$host}->getOsVer();
my $kernelVer=$hostIndex->{$host}->getKernelVer();
#warn "TEST: @{$hostIndex->{$host}->{patchesArray}}\n";
#warn "UPDATE: $OS $IP $owner $cpuNum $cpuModel $cpuSpeed $memTotal $osVer $kernelVer @{$hostIndex->{$host}->{patchesArray}}\n";
# Create data structure to use for serializing host data (host.ser)
my %hostObject=();
my $hostUpdate=();
$hostObject = Host->new( OS => "$OS",
lastUpdate => "$time",
IP => "$IP",
Owner => "$owner",
cpuNum => "$cpuNum",
cpuModel => "$cpuModel",
cpuSpeed => "$cpuSpeed",
memTotal => "$memTotal",
#swapTotal => "$swapTotal",
osVer => "$osVer",
kernelVer => "$kernelVer",
patchesArray => "$hostIndex->{$host}->{patchesArray}",
);
$hostUpdate->{$host} = $hostObject;
return $hostUpdate;
}
# Determine if host exists in etc/perf-hosts file. If not exit.
sub VERIFY_HOST {
# Verify if host data is found and load host/service data
if (! -f "$perfhome/var/db/hosts/$host/$host.ser") {
if ($ENV{'AUTO_DETECT'} =~ m/y|Y/) {
&AUTO_DETECT;
# Load host/service data for newly detected hosts
&LoadHostData; # Load hosts updated host data into hostIndex
&LoadHostServiceData; # Load hosts updated service data into hostIndex
} else {
warn "ERROR: $host does not exist in configuration!\n";
exit(1);
}
} else {
# Load host/service data for existing hosts
&LoadHostData; # Load hosts updated host data into hostIndex
&LoadHostServiceData; # Load hosts updated service data into hostIndex
}
# Exit if host data not defined in hostIndex
if (! defined $hostIndex->{$host}{IP}) {
warn "ERROR: Host data not found for $host in hostIndex!\n";
exit(1);
}
# Get saved IP address
my $savedIP=$hostIndex->{$host}->getIP();
if ($IP !~ m/$savedIP/) {
warn "ERROR: IP $IP does not match for $host!\n";
exit(1);
}
}
# Automatically add host into configuration if it isn't detected
sub AUTO_DETECT {
# Check to ensure user exists and is admin
if (! -f "$perfhome/var/db/users/$ENV{'ADMIN_NAME'}/$ENV{'ADMIN_NAME'}.ser") {
warn "ERROR: auto detect failed for $host, user $ENV{'ADMIN_NAME'} is not a valid user!\n";
exit(1);
}
my $userIndex = lock_retrieve("$perfhome/var/db/users//$ENV{'ADMIN_NAME'}/$ENV{'ADMIN_NAME'}.ser") or die("Could not lock_retrieve from $perfhome/var/db/users/$ENV{'ADMIN_NAME'}/$ENV{'ADMIN_NAME'}.ser");
if ($userIndex->{role} !~ m/admin/) {
warn "ERROR: auto detect failed for $host, user $ENV{'ADMIN_NAME'} is not an admin user!\n";
exit(1);
}
warn "INFO: Auto Detect enabled, adding $host/$IP to configuration!\n";
# Create host object
my $hostObject = Host->new( OS => $preOS,
IP => $IP,
Owner => $ENV{'ADMIN_NAME'});
# Create host directory
if ( ! -d "$perfhome/var/db/hosts/$host" ) {
mkdir("$perfhome/var/db/hosts/$host", 0770) or die "ERROR: Cannot mkdir $perfhome/var/db/hosts/$host: $!\n";
}
# Serialize host data to disk (host.ser)
$hostObject->lock_store("$perfhome/var/db/hosts/$host/$host.ser") or die "ERROR: Can't store $perfhome/var/db/hosts/$host/$host.ser\n";
# Create services directory
if ( ! -d "$perfhome/var/db/hosts/$host/services" ) {
mkdir("$perfhome/var/db/hosts/$host/services", 0770) or die "ERROR: Cannot mkdir $perfhome/var/db/hosts/$host/services: $!\n";
}
# Copy default ping serialized file to conn.ping serialized file
if (! -f "$perfhome/var/db/hosts/$host/services/conn.ping.ser") {
copy("$perfhome/etc/configs/$preOS/conn.ping.ser","$perfhome/var/db/hosts/$host/services/conn.ping.ser")
or die "ERROR: Couldn't serialize default conn.ping data for $host: $!\n";
}
# Update admin2Host Index
my $admin2Host = lock_retrieve("$perfhome/var/db/mappings/admin2Host.ser") or die("Could not lock_retrieve from $perfhome/var/db/mappings/admin2Host.ser");
$admin2Host->{$ENV{'ADMIN_NAME'}}->{$host} = $preOS;
lock_store($admin2Host, "$perfhome/var/db/mappings/admin2Host.ser") or die("Can't store admin2Host in $perfhome/var/db/mappings/admin2Host.ser\n");
# Add Blank Changelog
my $changeLog = {};
$changeLog->{'sequence'} = 0;
$changeLog->{'index'} = {};
lock_store($changeLog, "$perfhome/var/logs/changelogs/$host.ser") or die("Can't store changeLog in $perfhome/var/logs/changelogs/$host.ser\n");
warn "INFO: $host/$IP successfully added to configuration!\n";
}
# Create host based directories
sub CREATE_DIRS {
# Create RRD Dir if it doesn't exist
if ( ! -d "$perfhome/rrd/$host" ) {
mkdir("$perfhome/rrd/$host",0770)
or die "ERROR: Cannot mkdir $perfhome/rrd/$host: $!\n";
warn "INFO: Did not find Directory: $perfhome/rrd/$host. DIR Created\n";
}
# Create Status Dir if it doesn't exist
if ( ! -d "$perfhome/var/status/$host" ) {
mkdir("$perfhome/var/status/$host",0770)
or die "ERROR: Cannot mkdir $perfhome/var/status/$host: $!\n";
warn "INFO: Did not find Directory: $perfhome/var/status/$host. DIR Created\n";
}
# Create Event Log Dir if it doesn't exist
if ( ! -d "$perfhome/var/events/$host" ) {
mkdir("$perfhome/var/events/$host",0770)
or die "ERROR: Cannot mkdir $perfhome/var/events/$host: $!\n";
warn "INFO: Did not find Directory: $perfhome/var/events/$host. DIR Created\n";
}
# Create State Dir if it doesn't exist
if ( ! -d "$perfhome/var/db/hosts/$host" ) {
mkdir("$perfhome/var/db/hosts/$host",0770)
or die "ERROR: Cannot mkdir $perfhome/var/db/hosts/$host: $!\n";
warn "INFO: Did not find Directory: $perfhome/var/db/hosts/$host. DIR Created\n";
}
# Create services Dir if it doesn't exist
if ( ! -d "$perfhome/var/db/hosts/$host/services" ) {
mkdir("$perfhome/var/db/hosts/$host/services",0770)
or die "ERROR: Cannot mkdir $perfhome/var/db/hosts/$host/services: $!\n";
warn "INFO: Did not find Directory: $perfhome/var/db/hosts/$host/services. DIR Created\n";
}
# Create Alert Dir if it doesn't exist
if (! -d "$perfhome/var/alerts/$host") {
mkdir("$perfhome/var/alerts/$host",0770)
or die "ERROR: Cannot mkdir $perfhome/var/alerts/$host: $!\n";
warn "INFO: Did not find Directory: $perfhome/var/alerts/$host. DIR Created\n";
}
}
# Create RRD Databases from client data
sub RRD {
use RRDs;
my $RRD="$perfhome/rrd/$host/$host.$service.rrd";
# Create hash of rrd index and metric name for given host/service
$rrd_index_h=$hostIndex->{$host}->{serviceIndex}->{$service}->getRRDIndexes();
# Determine if correct number of data points were sent
&RRD_CHECK;
warn "DEBUG: RRD File $RRD\n" if ($ENV{'DEBUG'});
# If RRD doesn't exist then create one
if ( ! -f "$RRD" ) {
# Get RRD Configuration to build new RRD from
my $RRA=$hostIndex->{$host}->{serviceIndex}->{$service}->getRRA();
my $rrdStep=$hostIndex->{$host}->{serviceIndex}->{$service}->getRRDStep();
my $data_ref=\@data;
# Get Metric settings
my $i=();
foreach ($i=0; $i <= $#$data_ref; $i++) {
my $metric=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getMetricName();
my $rrdDST=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getRRDDST();
my $rrdHeartbeat=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getRRDHeartbeat();
my $rrdMin=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getRRDMin();
my $rrdMax=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getRRDMax();
# Add all metric settings to data source array
push @ds, "DS:$metric:$rrdDST:$rrdHeartbeat:$rrdMin:$rrdMax";
}
# Create new RRD via rrdAPI
my $rrdAPI=`$perfhome/bin/rrdAPI new,$host,$service,$rrdStep,@ds,$RRA`;
#my @rras = split " ",$RRA;
#RRDs::create($RRD,"--step",$rrdStep,@ds,@rras);
#my $ERROR=RRDs::error;
#if($ERROR) {
# warn "ERROR: creating $RRD: $ERROR\n";
# exit(1);
#}
#warn "INFO: did not find $RRD, RRD Created\n";
} else {
# Update already existing RRD with current time
my $rrdtime="N";
my $rrdupdate="$rrdtime";
# Data needs to be in semi-colon delimited format
$dataUpdate=join(":", @data);
# Update RRD via rrdAPI
my $rrdAPI=`$perfhome/bin/rrdAPI update,$host,$service,$dataUpdate`;
#$rrdupdate = "$rrdupdate:$dataUpdate";
#warn "DEBUG: rrdupdate = $rrdupdate\n" if ($ENV{'DEBUG'});
# If RRD already exists, update it with new data
#RRDs::update("$RRD","$rrdupdate");
#my $ERROR=RRDs::error;
#if($ERROR) {
# warn "ERROR: updating $RRD: $ERROR\n";
#}
}
# Undefine Data Source Info
undef @ds;
}
# Ensure data sent matches RRD Configuration
sub RRD_CHECK {
my $metric=();
my $data_ref=\@data;
my $rrd_count=$#$data_ref + 1;
my $sent_count=0;
# Calculate how many data points a given service has
foreach $metric (sort keys %$rrd_index_h) {
$sent_count++
}
# Exit and warn if incorrect number of data points were sent
if ($sent_count ne $rrd_count) {
warn "WARNING: $rrd_count data points sent, RRD configuration expected $sent_count for Host: $host Service: $NoSubService\n";
exit(1);
}
}
# Parse Events
sub EVENT_PARSE {
exit(0) unless ($ENV{'EVENTLOG'} =~ m/y|Y/);
my $event_disable=&EVENT_DISABLE; # List of events to disable from EVENT_DISABLE sub
exit(0) if ($event_disable eq "*");
my $data_ref=\@data;
# Map data value to name
my $i=();
foreach ($i=0; $i <= $#$data_ref; $i++) {
# Figure out if event values are set
$hasEvents=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getHasEvents();
# Update metricValue
$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->setMetricValue($data_ref->[$i]);
# Skip if events are not set/configured
next if ($hasEvents != "1");
next if ($event_disable =~ m/$service/);
next if ($event_disable =~ m/all|ALL/);
# Get event configuration for host/service
$warn=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getWarnThreshold();
$crit=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getCritThreshold();
$metricName=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getMetricName();
$friendlyName=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getFriendlyName();
$thresholdUnit=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getThresholdUnit();
$status=$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->getStatus();
if ( $data_ref->[$i] >= $warn && $data_ref->[$i] < $crit) {
$alert="WARN";
$event="$metricName";
$msg="$alert $friendlyName Value: $data_ref->[$i] Boundary: $warn Unit: $thresholdUnit";
# Set Global Environment SNMP Variables
if (defined $ENV{'TRAP_SCRIPT'}) {
$ENV{'ALERT'}="$alert";
$ENV{'EVENT'}="$service.$metricName";
$ENV{'NAME'}="$friendlyName";
$ENV{'VALUE'}="$data_ref->[$i]";
$ENV{'BOUNDARY'}="$warn";
$ENV{'THRESHOLD'}="$thresholdUnit";
}
# If metric status has changed process event
if ($alert !~ m/$status/) {
# Only notify if status ne to nostatus
if ($status !~ m/nostatus/) {
&CREATE_EVENT_LOGS;
&NOTIFY_RULES;
}
# Serialize event states to hostIndex
$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->setStatus($alert);
}
} elsif ($data_ref->[$i] >= $crit) {
$alert="CRIT";
$event="$metricName";
$msg="$alert $friendlyName Value: $data_ref->[$i] Boundary: $crit Unit: $thresholdUnit";
# Set Global Environment SNMP Variables
if (defined $ENV{'TRAP_SCRIPT'}) {
$ENV{'ALERT'}="$alert";
$ENV{'EVENT'}="$service.$metricName";
$ENV{'NAME'}="$friendlyName";
$ENV{'VALUE'}="$data_ref->[$i]";
$ENV{'BOUNDARY'}="$crit";
$ENV{'THRESHOLD'}="$thresholdUnit";
}
# If metric status has changed process event
if ($alert !~ m/$status/) {
# Only notify if status ne to nostatus
if ($status !~ m/nostatus/) {
&CREATE_EVENT_LOGS;
&NOTIFY_RULES;
}
# Serialize event states to hostIndex
$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->setStatus($alert);
}
} else {
$alert="OK";
$event="$metricName";
$msg="$alert $friendlyName Value: $data_ref->[$i] Boundary: $warn Unit: $thresholdUnit";
# Set Global Environment SNMP Variables
if (defined $ENV{'TRAP_SCRIPT'}) {
$ENV{'ALERT'}="$alert";
$ENV{'EVENT'}="$service.$metricName";
$ENV{'NAME'}="$friendlyName";
$ENV{'VALUE'}="$data_ref->[$i]";
$ENV{'BOUNDARY'}="$warn";
$ENV{'THRESHOLD'}="$thresholdUnit";
}
# If metric status has changed process event
if ($alert !~ m/$status/) {
# Only notify if status ne to nostatus
if ($status !~ m/nostatus/) {
&CREATE_EVENT_LOGS;
&NOTIFY_RULES;
}
# Serialize event states to hostIndex
$hostIndex->{$host}->{serviceIndex}->{$service}->{metricArray}->[$i]->setStatus($alert);
}
}
}
# Serialize all services to disk (service.ser)
$hostIndex->{$host}->{serviceIndex}->{$service}->lock_store("$perfhome/var/db/hosts/$host/services/$service.ser")
or die "ERROR: Can't store $perfhome/var/db/hosts/$host/services/$service.ser\n";
}
# Disable Events if configured in event-disable (optional)
sub EVENT_DISABLE {
$input = IO::File->new("< /$perfhome/etc/events-disable")
or die "ERROR: Couldn't open $perfhome/etc/events-disable for reading: $!\n";
while (defined($line = $input->getline())) {
if ($line =~ m/$host/) {
$line =~ m/$host:(\S*)/;
$match="$1";
}
}
$input->close();
if (defined $match) {
my @event_disable=split(/:/, $match);
my $event_disable="@event_disable";
return $event_disable;
}
}
# Create and Track historical event logs
sub CREATE_EVENT_LOGS {
$event_time=localtime;
my $count="0";
my $address=();
my $crit_filename="$perfhome/var/status/$host/$service.$event.crit";
my $warn_filename="$perfhome/var/status/$host/$service.$event.warn";
my $nostatus_filename="$perfhome/var/status/$host/$service.$event.nostatus";
my $event_filename="$perfhome/var/events/$host/$service.log";
if ($alert =~ m/CRIT/) {
if (-f "$warn_filename") {
unlink "$warn_filename";
}
if (-f "$nostatus_filename") {
unlink "$nostatus_filename";
}
my $crit_fh = new IO::File $crit_filename, "w", 0660
or die "ERROR: Cannot Open $crit_filename for writing: $!\n";
$crit_fh->close();
} elsif ($alert =~ m/WARN/) {
if (-f "$crit_filename") {
unlink "$crit_filename";
}
if (-f "$nostatus_filename") {
unlink "$nostatus_filename";
}
my $warn_fh = new IO::File $warn_filename, "w", 0660
or die "ERROR: Cannot Open $warn_filename for writing: $!\n";
$warn_fh->close();
} else {
if (-f "$crit_filename") {
unlink "$crit_filename";
}
if (-f "$warn_filename") {
unlink "$warn_filename";
}
if (-f "$nostatus_filename") {
unlink "$nostatus_filename";
}
}
# Determinie how many lines the log contains
if (-f $event_filename) {
my $count_fh = new IO::File $event_filename, "r", 0660
or die "ERROR: Cannot Open $event_filename for writing: $!\n";
while (<$count_fh>) {
next if $_ =~ m/^\s+/;
$count++;
}
$count_fh->close();
# Save Current Log
my $logfile_fh = new IO::File $event_filename, "r", 0660
or die "ERROR: Cannot Open $event_filename for writing: $!\n";
@event_log=<$logfile_fh>;
$logfile_fh->close();
}
# Write new log containing current log and new line
my $event_fh = new IO::File $event_filename, "w", 0660
or die "ERROR: Cannot Open $event_filename for writing: $!\n";
print $event_fh "$event_time $msg\n";
if (-f $event_filename) {
foreach $line (@event_log) {
print $event_fh "$line";
}
}
$event_fh->close();
# If the event log exceeds the log size limit truncate the last line
if (-f $event_filename) {
if ($count >= $ENV{'LOGSIZE'}) {
my $truncate_fh = new IO::File $event_filename, "r+", 0660
or die "ERROR: Cannot Open $event_filename for writing: $!\n";
while (<$truncate_fh>) {
$address = tell($truncate_fh) unless eof($truncate_fh);
}
truncate($truncate_fh, $address)
or die "ERROR: Couldn't Truncate $address Log: $!\n";
$truncate_fh->close();
}
}
}
# Determine who will recieve notification if it is enabled
sub NOTIFY_RULES {
# Determine wether to send smtp alerts
if ($ENV{'EMAIL'} =~ m/y|Y/) {
if ($ENV{'ALERT_ALL'} =~ m/y|Y/) {
&PARSE_RULES;
}
if ($ENV{'ALERT_CRIT'} =~ m/y|Y/ && $alert =~ m/CRIT/ && $ENV{'ALERT_ALL'} !~ m/y|Y/) {
&PARSE_RULES;
}
if ($ENV{'ALERT_WARN'} =~ m/y|Y/ && $alert =~ m/WARN/ && $ENV{'ALERT_ALL'} !~ m/y|Y/) {
&PARSE_RULES;
}
}
# Determine wether to send alerts based on trap script
if (defined $ENV{'TRAP_SCRIPT'}) {
if ($ENV{'ALERT_ALL'} =~ m/y|Y/) {
&PARSE_RULES;
}
if ($ENV{'ALERT_CRIT'} =~ m/y|Y/ && $alert =~ m/CRIT/ && $ENV{'ALERT_ALL'} !~ m/y|Y/) {
&PARSE_RULES;
}
if ($ENV{'ALERT_WARN'} =~ m/y|Y/ && $alert =~ m/WARN/ && $ENV{'ALERT_ALL'} !~ m/y|Y/) {
&PARSE_RULES;
}
}
}
# Parse notify-rules
sub PARSE_RULES {
# Skip if no rules are found
if (-f "$perfhome/var/db/hosts/$host/notifyRules.ser") {
use Time::localtime;
$tm=localtime;
($hour, $day) = ($tm->hour, $tm->mday);
# Create notifyRules object by deserialization
my $notifyRulesObject = lock_retrieve("$perfhome/var/db/hosts/$host/notifyRules.ser");
die("ERROR: can't retrieve $perfhome/var/db/hosts/$host/notifyRules.ser\n") unless defined($notifyRulesObject);
#warn "NOTIFY RULE: @{$notifyRulesObject->{notifyRulesArray}}\n";
foreach my $rule (@{$notifyRulesObject->{notifyRulesArray}}) {
no warnings;
$int_hour_{${$int}}=();
$int_day_{${$int}}=();
$rule =~ m/(\S*):(\S*):(\S*):(\S*)/;
$allow_hours=$1; $allow_days=$2; $allow_mets=$3; $email_list=$4;
if ($allow_hours eq "*") {
$rule_hour="OK";
} else {
@hours=split(/[-,]/, $allow_hours);
# Reference the array values for hours
$hours_ref=\@hours;
# Find out how many pairs we are dealing with for hours
$hours_pairs=(($#$hours_ref + 1) / 2);
# Determine hour ranges and if the actual hour fits into range
foreach ($int=0; $odd_hour <= $hours_pairs; $int++) {
$second_field=$int + 1;
$int_hour_{${$int}}=$hours[$second_field] - $hours[$int];
$hour_total=$hours[$int] + $int_hour_{${$int}};
foreach ($count=$hours[$int]; $count <= $hour_total; $count++) {
next if (! defined $count);
if ($hour eq $count) {
$rule_hour="OK";
last;
}
}
$odd_hour=$odd_hour + 1;
$int=$int + 1;
}
}
if ($allow_days eq "*") {
$rule_day="OK";
} else {
@days=split(/[-,]/, $allow_days);
# Reference the array values for days
$days_ref=\@days;
# Find out how many pairs we are dealing with for days
$days_pairs=(($#$days_ref + 1) / 2);
# Determine hour ranges and if the actual hour fits into range
foreach ($int=0; $odd_day <= $days_pairs; $int++) {
$second_field=$int + 1;
$int_day_{${$int}}=$days[$second_field] - $days[$int];
$day_total=$days[$int] + $int_day_{${$int}};
foreach ($count=$days[$int]; $count <= $day_total; $count++) {
next if (! defined $count);
if ($day eq $count) {
$rule_day="OK";
last;
}
}
$odd_day=$odd_day + 1;
$int=$int + 1;
}
}
# Determine what metrics alerts can be sent for
if ($allow_mets eq "*") {
$rule_met="OK";
} else {
@mets=split(/,/, $allow_mets);
foreach $met (@mets) {
if ($met =~ m/$service/) {
$rule_met="OK";
}
}
}
if (defined $rule_hour && defined $rule_day && defined $rule_met) {
&SEND_ALERT;
}
}
}
}
# Send alerts to email or pager via smtp
sub SEND_ALERT {
# Send smtp alert if email is enabled
if ($ENV{'EMAIL'} =~ m/y|Y/) {
open(ALERT, "> $perfhome/var/alerts/$host/$service.$event.$alert")
or die "ERROR: Couldn't open file $perfhome/var/alerts/$host/$service.$event.$alert: $!\n";
print ALERT "$email_list\n$event_time $service:$event $msg";
close(ALERT);
}
# Send Trap if traps are enabled
if (defined $ENV{'TRAP_SCRIPT'}) {
&ParseTrapScript;
warn "DEBUG: $ENV{'TRAP_SCRIPT'}\n" if ($ENV{'DEBUG'});
#warn "TRAP: $ENV{'TRAP_SCRIPT'}\n";
}
}
# Setup host Defaults for host data
sub SetHostDefaults {
# Copy default host serialized file to unique hostname serialized file
if (! -f "$perfhome/var/db/hosts/$host/$host.ser") {
copy("$perfhome/etc/configs/$preOS/host.ser","$perfhome/var/db/hosts/$host/$host.ser")
or die "ERROR: Couldn't serialize default host data for $host: $!\n";
}
# Copy default ping serialized file to conn.ping serialized file
if (! -f "$perfhome/var/db/hosts/$host/services/conn.ping.ser") {
copy("$perfhome/etc/configs/$preOS/conn.ping.ser","$perfhome/var/db/hosts/$host/services/conn.ping.ser")
or die "ERROR: Couldn't serialize default conn data for $host: $!\n";
}
# If service data doesn't exist, load it
if (! defined $hostIndex->{$host}{OS}) {
&LoadHostData;
warn "INFO: Loaded new host data for $host\n";
}
}
# Setup host Defaults for service data
sub SetServiceDefaults {
# Copy default service serialized file to unique sub-service serialized file
if (! -f "$perfhome/var/db/hosts/$host/services/$service.ser") {
copy("$perfhome/etc/configs/$os/$NoSubService.ser","$perfhome/var/db/hosts/$host/services/$service.ser")
or die "ERROR: Couldn't serialize default service data for $host:$service: $!\n";
}
# If service data doesn't exist, load it
if (! defined $hostIndex->{$host}->{serviceIndex}->{$service}) {
&LoadHostServiceData;
warn "INFO: Loaded new service: $service for $host\n";
}
}
# Load single hosts host configuration data (de-serialize)
sub LoadHostData {
#create an empty serviceHash
$serviceHash = {};
### Check to ensure host exists ###
if (! -f "$perfhome/var/db/hosts/$host/$host.ser") {
warn "ERROR: $host does not exist in configuration!\n";
exit(1);
}
### Populate each host key with a host object ###
opendir(HOSTDIR, "$perfhome/var/db/hosts/$host")
or die("ERROR: Couldn't open dir $perfhome/var/db/hosts/$host: $!\n");
while ($fileName = readdir(HOSTDIR)) {
# Skip if file starts with a . and all service.ser
next if ($fileName =~ m/^\.\.?$/);
next if ($fileName !~ m/$host\.ser/);
if ($fileName =~ /$host\.ser/) {
#create host object by deserialization
$hostObject = lock_retrieve("$perfhome/var/db/hosts/$host/$fileName")
or die "ERROR: can't retrieve $perfhome/var/db/hosts/$host/$fileName: $!\n";
die("ERROR: can't retrieve $perfhome/var/db/hosts/$host/$fileName, hostObject not defined\n") unless defined($hostObject);
#assign host object to hostIndex
$hostIndex->{$host} = $hostObject;
} else {
warn "ERROR: Serialized host data not found for $host:$fileName while loading host data\n";
exit(1);
}
}
closedir(HOSTDIR);
}
# Load single hosts service configuration data (de-serialize)
sub LoadHostServiceData {
#create an empty serviceHash
$serviceHash = {};
### Populate empty serviceHash with service objects ###
opendir(SERVICESDIR, "$perfhome/var/db/hosts/$host/services")
or die("ERROR: Couldn't open dir $perfhome/var/db/hosts/$host/services: $!\n");
while ($serviceName = readdir(SERVICESDIR)) {
# Skip if file starts with a . and the host.ser
next if ($serviceName =~ m/^\.\.?$/);
#next if ($serviceName =~ m/$host\.ser/);
if ($serviceName =~ /^([\S]+)\.ser$/) {
#create service object by deserialization
$serviceObject = lock_retrieve("$perfhome/var/db/hosts/$host/services/$serviceName");
die("ERROR: can't retriewe $perfhome/var/db/hosts/$host/services/$serviceName\n") unless defined($serviceObject);
#assign service object to service hash
$serviceHash->{$1} = $serviceObject;
} else {
warn "ERROR: Serialized data not found for $host:$serviceName while loading host data\n";
exit(1);
}
}
closedir(SERVICESDIR);
#assign serviceHash to hostIndex for given host only
$hostIndex->{$host}->{serviceIndex} = $serviceHash;
}
# Parse trap script and convert dynamic variables
sub ParseTrapScript {
my $configfile="$perfhome/etc/perf-conf";
open(FILE, $configfile)
or die "ERROR: Couldn't open FileHandle for $configfile: $!\n";
my @data=<FILE>;
foreach $line (@data) {
# Skip line if commented out
next unless ($line =~ m/^TRAP_SCRIPT/);
$line =~ m/(\w+)=(.+)/;
my $key=$1;
my $value=$2;
# Dereference any variables that were set in conf file using the % flag
if ($value =~ m/\%/) {
my @value=split(' ',$value);
foreach my $var (@value) {
next if ($var !~ m/%/);
$var =~ m/\%(\S+)/;
my $var="$1";
$value =~ s/\%$var/$ENV{$var}/;
}
}
$ENV{$key}=$value;
}
close(FILE);
}
# Get configuration dynamically from perf-conf
sub GetConfiguration {
my $configfile="$perfhome/etc/perf-conf";
my $hashref = shift;
open(FILE, $configfile)
or die "ERROR: Couldn't open FileHandle for $configfile: $!\n";
my @data=<FILE>;
foreach $line (@data) {
# Skip line if commented out
next if ($line =~ m/^#/);
next if ($line =~ m/^\s+/);
$line =~ m/(\w+)=(.+)/;
my $key=$1;
my $value=$2;
$hashref->{$key}=$value;
}
close(FILE);
}
# Get path to perfctl executable
sub PATH {
my $path = PerlApp::exe();
$path =~ s/\/\w*$//;
return $path;
}
#$socket->close;
| ktenzer/perfstat | server/unix/build/1.52/src/perfd.pl | Perl | apache-2.0 | 36,178 |
% This file is part of the Attempto Parsing Engine (APE).
% Copyright 2008-2013, Attempto Group, University of Zurich (see http://attempto.ifi.uzh.ch).
%
% The Attempto Parsing Engine (APE) is free software: you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later version.
%
% The Attempto Parsing Engine (APE) is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
% PURPOSE. See the GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License along with the Attempto
% Parsing Engine (APE). If not, see http://www.gnu.org/licenses/.
%:- module(functionwords, [
% functionword/1,
% variable/1,
% rawnumber_number/2,
% propername_prefix/2,
% noun_prefix/2,
% verb_prefix/1,
% modif_prefix/1
% ]).
/** <module> Function Words
This module stores the different kinds of function words.
@author Kaarel Kaljurand
@author Tobias Kuhn
@version 2008-06-26
*/
%% functionword(?FunctionWord) is det.
%
functionword(whose).
functionword(for).
functionword('There').
functionword(there).
functionword(and).
functionword(or).
functionword(not).
functionword(that).
functionword(than).
functionword(of).
functionword(s).
%modification
functionword('''').
functionword('"').
functionword('/').
functionword('\\').
functionword('-').
functionword('+').
functionword('&').
functionword('*').
functionword('(').
functionword(')').
functionword('[').
functionword(']').
functionword('}').
functionword('{').
functionword('<').
functionword('=').
functionword('>').
functionword('.').
functionword('?').
functionword('!').
functionword(',').
functionword(':').
functionword('If').
functionword(if).
functionword(then).
functionword('such').
functionword('be').
functionword('isn').
functionword('aren').
functionword('doesn').
functionword('don').
functionword('provably').
functionword(more).
functionword(most).
functionword(least).
functionword(less).
functionword(but).
functionword(true).
functionword(false).
functionword(possible).
functionword(necessary).
functionword(recommended).
functionword(admissible).
functionword('-thing').
functionword('-body').
functionword('-one').
functionword('something').
functionword('somebody').
functionword('someone').
functionword('nothing').
functionword('nobody').
functionword('noone').
functionword('everything').
functionword('everybody').
functionword('everyone').
functionword('one').
functionword('A').
functionword('All').
functionword('An').
functionword('Are').
functionword('Can').
functionword('Do').
functionword('Does').
functionword('Each').
functionword('Every').
functionword('Exactly').
functionword('He').
functionword('Her').
functionword('His').
functionword('How').
functionword('Is').
functionword('It').
functionword('Its').
functionword('May').
functionword('Must').
functionword('No').
functionword('She').
functionword('Should').
functionword('Some').
functionword('The').
functionword('Their').
functionword('They').
functionword('What').
functionword('When').
functionword('Where').
functionword('Which').
functionword('Who').
functionword('Whose').
functionword(a).
functionword(all).
functionword(an).
functionword(are).
functionword(can).
functionword(do).
functionword(does).
functionword(each).
functionword(every).
functionword(exactly).
functionword(he).
functionword(her).
functionword(herself).
functionword(him).
functionword(himself).
functionword(his).
functionword(how).
functionword(is).
functionword(it).
functionword(its).
functionword(itself).
functionword(may).
functionword(must).
functionword(no).
functionword(she).
functionword(should).
functionword(some).
functionword(the).
functionword(their).
functionword(them).
functionword(themselves).
functionword(they).
functionword(what).
functionword(when).
functionword(where).
functionword(which).
functionword(who).
functionword(at).
functionword(by).
functionword(^). % used interally to mark the beginning of a sentence
functionword('For').
functionword('At').
functionword('Less').
functionword('More').
functionword(you).
functionword('You').
functionword(your).
functionword('Your').
functionword(yourself).
functionword(yourselves).
functionword(to). % e.g. "wants to"
functionword(own). % e.g. "his own"
functionword(many). % e.g. "how many"
functionword(much). % e.g. "how much"
%% variable(+Word) is det.
%
variable(Word) :-
atom(Word),
atom_codes(Word, [First|Rest]),
65 =< First,
First =< 90,
digits(Rest).
%% digits(+String) is det.
%
digits([]).
digits([D|Rest]) :-
48 =< D,
D =< 57,
digits(Rest).
%% rawnumber_number(+RawNumber:term, -Number:integer) is det.
%
% @param RawNumber is either an integer or an English word denoting a small positive integer
% @param Number is an integer
%
% Only integers 0-12 are supported as words.
rawnumber_number(RawNumber, RawNumber) :-
number(RawNumber).
rawnumber_number(null, 0).
rawnumber_number(zero, 0).
rawnumber_number(one, 1).
rawnumber_number(two, 2).
rawnumber_number(three, 3).
rawnumber_number(four, 4).
rawnumber_number(five, 5).
rawnumber_number(six, 6).
rawnumber_number(seven, 7).
rawnumber_number(eight, 8).
rawnumber_number(nine, 9).
rawnumber_number(ten, 10).
rawnumber_number(eleven, 11).
rawnumber_number(twelve, 12).
rawnumber_number(dozen, 12).
% Capitalized versions of the number words
% as numbers can also be used at the beginning of
% the sentences, e.g. 'Four men wait.'
rawnumber_number('Null', 0).
rawnumber_number('Zero', 0).
rawnumber_number('One', 1).
rawnumber_number('Two', 2).
rawnumber_number('Three', 3).
rawnumber_number('Four', 4).
rawnumber_number('Five', 5).
rawnumber_number('Six', 6).
rawnumber_number('Seven', 7).
rawnumber_number('Eight', 8).
rawnumber_number('Nine', 9).
rawnumber_number('Ten', 10).
rawnumber_number('Eleven', 11).
rawnumber_number('Twelve', 12).
rawnumber_number('Dozen', 12).
%% propername_prefix(+Prefix:atom, +Gender:atom, +Type:atom) is det.
%% noun_prefix(+Prefix:atom, +Gender:atom, +Type:atom) is det.
%% verb_prefix(+Prefix:atom, +Type:atom) is det.
%% modif_prefix(+Prefix:atom) is det.
%
% Definition of prefixes.
% Support for words which are not in the lexicon.
% Undefined words have to start with a prefix (e.g. `n' or `v'), e.g.
% ==
% A man v:backs-up the n:web-page of the n:pizza-delivery-service.
% ==
%
% Notes:
% * syntax disambiguates (and not morphology):
% the n:blah runs. AND the n:blah run. get different readings (singular vs plural respectively)
% the n:blah v:qwerty. (gets only singular reading, since this is arrived at first)
%
propername_prefix(pn, neutr).
propername_prefix(human, human).
propername_prefix(masc, masc).
propername_prefix(fem, fem).
propername_prefix(p, neutr).
propername_prefix(h, human).
propername_prefix(m, masc).
propername_prefix(f, fem).
propername_prefix(unknowncat, neutr).
propername_prefix(unknowncat, human).
propername_prefix(unknowncat, masc).
propername_prefix(unknowncat, fem).
noun_prefix(noun, neutr).
noun_prefix(human, human).
noun_prefix(masc, masc).
noun_prefix(fem, fem).
noun_prefix(n, neutr).
noun_prefix(h, human).
noun_prefix(m, masc).
noun_prefix(f, fem).
noun_prefix(unknowncat, neutr).
noun_prefix(unknowncat, human).
noun_prefix(unknowncat, masc).
noun_prefix(unknowncat, fem).
verb_prefix(verb).
verb_prefix(v).
verb_prefix(unknowncat).
modif_prefix(a).
modif_prefix(unknowncat).
| tiantiangao7/kalm | scripts/prolog/ape/lexicon/functionwords.pl | Perl | bsd-3-clause | 7,578 |
package VCP::Dest::data_dump ;
=head1 NAME
VCP::Dest::data_dump - developement output
=head1 DESCRIPTION
Dump all data structures. Requires the module BFD, which is not installed
automatically.
Not a supported module, API and behavior may change without warning.
=cut
$VERSION = 0.1 ;
@ISA = qw( VCP::Dest );
use strict ;
use VCP::Dest;
#use base qw( VCP::Dest );
sub handle_header {
warn "\n";
require BFD; ## load lazily so as to not force all users to install BFD
BFD::d( $_[1] );
}
sub handle_rev {
warn "\n";
BFD::d( $_[1]->as_hash );
}
sub handle_footer {
warn "\n";
BFD::d( $_[1] );
}
=head1 AUTHOR
Barrie Slaymaker <barries@slaysys.com>
=head1 COPYRIGHT
Copyright (c) 2000, 2001, 2002 Perforce Software, Inc.
All rights reserved.
See L<VCP::License|VCP::License> (C<vcp help license>) for the terms of use.
=cut
1
| gitpan/VCP-autrijus-snapshot | lib/VCP/Dest/data_dump.pm | Perl | bsd-3-clause | 866 |
#!/usr/bin/perl
# Sweetie Belle is best pony!
use strict;
use warnings;
use POE qw(Component::IRC Component::IRC::Plugin::BotCommand Component::IRC::Plugin::Connector);
use AuraIRC::IRC;
use IRC::Utils qw(parse_user lc_irc);
my $nickname = "Aura";
my $ircname = "Aura";
my $server = "2tuhbv75pl4ilp27.onion";
my @channels = ("#openponies");
my $irc = AuraIRC::IRC->spawn(
nick => $nickname,
ircname => $ircname,
sasl_username => "Aura",
sasl_password => "",
server => $server,
socks_proxy => '127.0.0.1',
socks_port => 9050
) or die "It didn't work out...";
POE::Session->create(
package_states => [
main => [ qw(
_default
_start
irc_botcmd_knowledge
irc_001
irc_public
) ],
],
heap => { irc => $irc },
);
$poe_kernel->run();
sub _start {
my $heap = $_[HEAP];
# retrieve our component's object from the heap where we stashed it
my $irc = $heap->{irc};
$heap->{connector} = POE::Component::IRC::Plugin::Connector->new();
$irc->plugin_add('BotCommand', POE::Component::IRC::Plugin::BotCommand->new(
Addressed => 0,
Prefix => '@',
Commands => {
knowledge => 'Wisdom flows with the wind.'
}
));
$irc->plugin_add( 'Connector' => $heap->{connector} );
$irc->yield( register => 'all' );
$irc->yield( connect => { } );
return;
}
sub irc_001 {
my $sender = $_[SENDER];
# Since this is an irc_* event, we can get the component's object by
# accessing the heap of the sender. Then we register and connect to the
# specified server.
my $irc = $sender->get_heap();
print "Connected to ", $irc->server_name(), "\n";
# we join our channels
$irc->yield( join => $_ ) for @channels;
return;
}
sub irc_public {
my ($sender, $who, $where, $what) = @_[SENDER, ARG0 .. ARG2];
my $nick = ( split /!/, $who )[0];
my $channel = $where->[0];
return;
}
# We registered for all events, this will produce some debug info.
sub _default {
my ($event, $args) = @_[ARG0 .. $#_];
my @output = ( "$event: " );
for my $arg (@$args) {
if ( ref $arg eq 'ARRAY' ) {
push( @output, '[' . join(', ', @$arg ) . ']' );
}
else {
push ( @output, "'$arg'" );
}
}
print join ' ', @output, "\n";
return;
}
sub irc_botcmd_knowledge {
my ($heap, $nick, $channel, $target) = @_[HEAP, ARG0..$#_];
$nick = parse_user($nick);
my $irc = $heap->{irc};
$irc->yield(privmsg => $channel, "$nick: openponies is a community-owned pony franchise.");
}
| Openponies/Aura | aurairc.pl | Perl | bsd-3-clause | 2,693 |
#!/usr/bin/perl
use 5.010;
use warnings;
use strict;
my $exit = 0;
my $sample = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAG"
. "AGTGTCTGATAGCAGC";
my $out = `echo $sample | ./rosalind-dna`;
$exit++ if ($out ne "20 12 17 21\n");
$exit++ unless (system("echo 0 | ./rosalind-dna"));
exit $exit;
| mikeyhc/rosalind | dna/t/01_default.pl | Perl | bsd-3-clause | 310 |
package Games::Lacuna::Client::Buildings::Capitol;
use 5.0080000;
use strict;
use Carp 'croak';
use warnings;
use Games::Lacuna::Client;
use Games::Lacuna::Client::Buildings;
our @ISA = qw(Games::Lacuna::Client::Buildings);
sub api_methods {
return {
view => { default_args => [qw(session_id building_id)] },
rename_empire => { default_args => [qw(session_id building_id)] },
};
}
__PACKAGE__->init();
1;
__END__
=head1 NAME
Games::Lacuna::Client::Buildings::Capitol - The Capitol building
=head1 SYNOPSIS
use Games::Lacuna::Client;
=head1 DESCRIPTION
=head1 AUTHOR
Steffen Mueller, E<lt>smueller@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2010 by Steffen Mueller
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
| RedOrion/Vasari-TLEUtil | lib/Games/Lacuna/Client/Buildings/Capitol.pm | Perl | mit | 931 |
/*******************************************************************
*
* A Common Lisp compiler/interpretor, written in Prolog
*
* (arglists.pl)
*
*
* Douglas'' Notes 2017:
*
*
*
*******************************************************************/
:- module(kp4rms, []).
:- include('./header').
:- meta_predicate apply_as_pred(2,?).
:- meta_predicate apply_as_pred(3,?,?).
:- meta_predicate apply_as_pred(4,?,?,?).
:- meta_predicate call_as_ident(2,?,?).
:- meta_predicate function(*,2,?,?).
:- meta_predicate function(2,?,?).
:- meta_predicate not_fn(1,?).
:- meta_predicate not_fn(2,?,?).
:- meta_predicate not_fn(3,?,?,?).
:- meta_predicate xform_with_ident(*,2,*).
xform_with_ident([],_Ident,[]).
xform_with_ident([Y0|YR0],Ident,[Y|YR]):-
call_as_ident(Ident,Y0,Y),
xform_with_ident(YR0,Ident,YR).
call_as_ident(Pred,X,Result):- function(Pred,X,Result).
apply_as_pred(EqlPred,X,Y,Z):-call(EqlPred,X,Y,Z,R)->R\==[].
apply_as_pred(EqlPred,X,Y):-call(EqlPred,X,Y,R)->R\==[].
apply_as_pred(EqlPred,X):-call(EqlPred,X,R)->R\==[].
% Maybe move to funcall
function(f_funcall,Pred,Y,Result):- !, function(Pred,Y,Result).
function(Pred,X,Y,Result):- f_apply(Pred,[X,Y],Result).
function(X,function(X)).
% used by call_as_ident/3
function([],X,X):-!.
function(Pred,X,Result):- call(Pred,X,Result),!.
% Maybe move to arglists
% key_value(Keys,Name,Value,Default).
key_value(Keys,Name,Value):- is_dict(Keys),!,Keys.Name=Value,!.
key_value(Keys,Name,Value):- get_plist_value(f_eql,Keys,Name,zzzz666,Value),Value\==zzzz666.
key_value(Keys,Name,Value,_Default):- key_value(Keys,Name,Value),!.
key_value(_Keys,_Name,Default,Default).
get_identity_pred(Keys,K,Pred):-
key_value(Keys,K,Value) -> to_function(Value,Pred); Pred = (=).
get_test_pred(IfMissing,Keys,Pred):-
key_value(Keys,kw_test_not,Value) -> to_neg_function(Value,Pred);
key_value(Keys,kw_test,Value) -> to_function(Value,Pred);
Pred = IfMissing.
%to_function(function(ValueI),ValueO):-!,to_function(ValueI,ValueO).
to_function(Value,Call):- find_operator_or_die(_Env,kw_function,Value,Call).
to_neg_function(Value,not_fn(Neg)):-to_function(Value,Neg).
not_fn(Value,A):- \+ call(Value,A).
not_fn(Value,A,B):- \+ call(Value,A,B).
not_fn(Value,A,B,C):- \+ call(Value,A,B,C).
nth_param(Optionals,N,Default,Value):- (nonvar(Optionals),nth1(N,Optionals,Value))->true;Default=Value.
nth_param(Optionals,N,Default,Value,PresentP):- (nonvar(Optionals),nth1(N,Optionals,Value))->(PresentP=t);(Default=Value,PresentP=[]).
:- fixup_exports.
| TeamSPoon/MUD_ScriptEngines | prolog/wam_cl/paramfns.pl | Perl | mit | 2,524 |
#!/usr/bin/perl
use warnings;
use strict;
use Test::More;
use Test::Exception;
use List::Util qw(min max);
# FIXME: fix it to connect to your DB
############################################
use DBI;
my $con_params = {
db => "example", # FIXME
socket => "/var/lib/mysql/mysql.sock", #FIXME
user => "root",
pass => "",
};
my $dbh = DBI->connect(
"DBI:mysql:database=$con_params->{db};mysql_socket=$con_params->{socket}",
$con_params->{user},
$con_params->{pass},
{RaiseError => 1}
);
############################################
my $STRICT_SIZE_CHECK = 0;
my $nullstr = $dbh->quote($STRICT_SIZE_CHECK ? "\0" : "");
# str_or check
for my $i (0..10) {
my ($res) = $dbh->selectrow_array("
select
str_get_bit(
str_or(
str_set_bit($nullstr,1),
str_set_bit($nullstr,2)
),
$i
)
");
my $expected = {1 => 1, 2 => 1};
is($res, $expected->{$i} ? 1 : 0, "bit $i in str_or is ". ($expected->{$i} || 0));
}
# str_and check
for my $i (0..8) {
my ($res) = $dbh->selectrow_array("
select
str_get_bit(
str_and(
str_or(
str_set_bit($nullstr,1),
str_set_bit($nullstr,2)
),
str_set_bit($nullstr,2)
),
$i
)
");
my $expected = {2 => 1};
is($res, $expected->{$i} ? 1 : 0, "bit $i in str_and is ". ($expected->{$i} || 0));
}
$dbh->do("drop table if exists A");
$dbh->do("create table A (a binary(1))");
$dbh->do("
insert into A values
(str_set_bit($nullstr,1)),
(str_set_bit($nullstr,7)),
(str_set_bit($nullstr,9))
");
# str_or_aggr check
for my $i (0..17) {
my ($res) = $dbh->selectrow_array("
select str_get_bit(str_or_aggr(a),$i) from A
");
my $expected = {1 => 1, 7 => 1};
is($res, $expected->{$i} ? 1 : 0, "bit $i in str_or_aggr is ". ($expected->{$i} || 0));
}
# str_and_aggr check
$dbh->do("update A set a = str_set_bit(a,5)");
for my $i (0..17) {
my ($res) = $dbh->selectrow_array("
select str_get_bit(str_and_aggr(a),$i) from A
");
my $expected = {5 => 1};
is($res, $expected->{$i} ? 1 : 0, "bit $i in str_and_aggr is ". ($expected->{$i} || 0));
}
# compatibility with perl vec function
my $null16 = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for my $i (0..127 ) {
my $str = $null16;
vec($str, $i, 1) = 1;
my $another_str = $null16;
vec($another_str, $i+1, 1) = 1;
my ($res2) = $dbh->selectrow_array("select str_get_bit(" . $dbh->quote($str) . ", $i)");
ok($res2, "str_get_bit gets a bit set by vec(str, num) = 1 for num = $i");
my ($res3) = $dbh->selectrow_array("select str_get_bit(" . $dbh->quote($another_str) . ", $i)");
ok(!$res3, "str_get_bit does not get bit num when num+1 is set by vec() for num = $i");
my ($res4) = $dbh->selectrow_array("select str_set_bit(" . $dbh->quote($null16) . ", $i)");
ok(vec($res4, $i, 1), "str_set_bit sets a bit which is accessible by vec(str, num) for num = $i");
diag sprintf("perl string for num $i: %s", unpack("b*", $str));
diag sprintf("mysql string for num $i: %s", unpack("b*", $res4));
}
{
my $is = sub {
my $what = shift;
my $expected = shift;
my $msg = shift;
my $data = shift;
$dbh->do('drop table if exists A');
$dbh->do('create table A (a binary(16))');
my $res = undef;
my $expected_res = undef;
if ($data) {
for my $val (@$data) {
$dbh->do("insert into A set a = $val");
}
($res) = $dbh->selectrow_array("select $what from A limit 1");
($expected_res) = $dbh->selectrow_array("select $expected from A limit 1");
} else {
($res) = $dbh->selectrow_array("select $what");
($expected_res) = $dbh->selectrow_array("select $expected");
}
unless (defined $res) {
fail("$what is undef ($msg)");
return 1;
}
unless (defined $expected_res) {
fail("$expected is undef ($msg)");
return 1;
}
my $not_equal = scalar grep { vec($res, $_, 1) != vec($expected_res, $_, 1) } (0 .. (max(length($res), length($expected_res)) + 1) * 8);
if ($not_equal) {
fail("'$what' is not '$expected' ($msg)");
diag sprintf("Got: %s", unpack("b*", $res));
diag sprintf("Expected: %s", unpack("b*", $expected_res));
} else {
pass("'$what' is '$expected' ($msg)");
# diag sprintf("Got: %s", unpack("b*", $res));
# diag sprintf("Expected: %s", unpack("b*", $expected_res));
}
return 1;
};
# NULL equals to empty string: basic functions
{
$is->(
'str_or(str_set_bit("", 100), str_set_bit("", 50))',
'str_or(str_set_bit("", 50), str_set_bit("", 100))',
"sanity check (basic)"
);
$is->('str_set_bit(NULL, 100)', 'str_set_bit("", 100)', "str_set_bit() treats NULL as ''");
$is->('str_get_bit(NULL, 100)', 0, "str_get_bit() treats NULL as ''");
throws_ok(sub { $dbh->selectrow_array('select str_set_bit("100", NULL)') }, qr/does not accept NULL/, "str_set_bit() returns error for NULL bit" );
throws_ok(sub { $dbh->selectrow_array('select str_get_bit("100", NULL)') }, qr/does not accept NULL/, "str_get_bit() returns error for NULL bit" );
$is->('str_or(NULL, str_set_bit("", 100))', 'str_set_bit("", 100)', "str_or treats left NULL as ''");
$is->('str_or(str_set_bit("", 100), NULL)', 'str_set_bit("", 100)', "str_or treats right NULL as ''");
$is->('str_or(NULL, NULL)', '""', "str_or treats both NULLs as ''");
$is->('str_and(NULL, str_set_bit("", 100))', '""', "str_and treats left NULL as ''");
$is->('str_and(str_set_bit("", 100), NULL)', '""', "str_and treats right NULL as ''");
$is->('str_and(NULL, NULL)', '""', "str_or treats both NULLs as ''");
}
# NULL equals to empty string: aggregate functions
{
$is->(
'str_or_aggr(a)',
'str_or(str_or(str_set_bit("", 10), str_set_bit("", 20)), str_set_bit("", 30))',
'str_or_aggr - sanity check',
[ 'str_set_bit("", 10)', 'str_set_bit("", 20)', 'str_set_bit("", 30)' ]
);
$is->(
'str_or_aggr(a)',
'str_or(str_set_bit("", 10), str_set_bit("", 30))',
'str_or_aggr treats NULL as ""',
[ 'NULL', 'str_set_bit("", 10)', 'NULL', 'NULL', 'str_set_bit("", 30)', 'NULL' ]
);
$is->(
'str_or_aggr(a)',
'""',
'str_or_aggr does not fail on all NULLs',
[ 'NULL', 'NULL', 'NULL', 'NULL' ]
);
# $is->(
# 'str_or_aggr(a)',
# '""',
# 'str_or_aggr does not fail on empty input',
# [ ]
# );
$is->(
'str_and_aggr(a)',
'str_set_bit("", 10)',
'str_and_aggr - sanity check',
[ 'str_set_bit("", 10)', 'str_or(str_set_bit("", 10), str_set_bit("", 20))' ]
);
$is->(
'str_and_aggr(a)',
'str_set_bit("", 10)',
'str_and_aggr treats NULL as ""',
[ 'str_set_bit("", 10)', 'str_or(str_set_bit("", 10), str_set_bit("", 20))' ]
);
$is->(
'str_and_aggr(a)',
'""',
'str_and_aggr does not fail on all NULLs',
[ 'NULL', 'NULL', 'NULL', 'NULL' ]
);
# $is->(
# 'str_and_aggr(a)',
# '""',
# 'str_and_aggr does not fail on empty input',
# [ ]
# );
}
# check bugfix: str_set_bit does not shorten a long string when you set an early bit
$is->('str_set_bit("Cheerilee is the best pony!", 5)', 'str_or(str_set_bit("", 5), "Cheerilee is the best pony!")', "str_set_bit does not eat strings");
# check bugfix: str_and, str_and_aggr should treat non-existant bits as 0
{
my $one10 = ''; vec($one10, $_, 1) = 1 for (1..10); $one10 = $dbh->quote($one10);
my $one20 = ''; vec($one20, $_, 1) = 1 for (1..20); $one20 = $dbh->quote($one20);
$is->("str_and($one10, $one20)", "$one10", "str_and treats unset bits as zeroes (all, left)");
$is->("str_and($one20, $one10)", "$one10", "str_and treats unset bits as zeroes (all, right)");
$is->('str_and(str_set_bit("", 50), "")', '""', "str_and treats unset bits as zeroes (one, left)");
$is->('str_and("", str_set_bit("", 50))', '""', "str_and treats unset bits as zeroes (one, right)");
$is->('str_and_aggr(a)', "$one10", "str_and_aggr treats unset bits as zeroes (all, left)", ["$one10", "$one20"]);
$is->('str_and_aggr(a)', "$one10", "str_and_aggr treats unset bits as zeroes (all, right)", ["$one20", "$one10"]);
$is->('str_and_aggr(a)', '""', "str_and_aggr treats unset bits as zeroes (one, left)", ['str_set_bit("", 50)', '""']);
$is->('str_and_aggr(a)', '""', "str_and_aggr treats unset bits as zeroes (one, right)", ['""', 'str_set_bit("", 50)']);
}
}
done_testing();
| breqwas/mysql-bit-strings | test.pl | Perl | mit | 8,184 |
:- module(binarise,[binarise/3]).
:- use_module(library(lists),[member/2,select/3,append/3]).
:- use_module(printError,[error/2,error/3]).
/* -----------------------------------------------------------------------
Binarising: put branches in a list
----------------------------------------------------------------------- */
binarise(Tree,Name,Bin):-
Tree =.. [tree,Node|Branches], !,
binarise(t(Node,Branches),Name,Bin).
/* -----------------------------------------------------------------------
Binarising: definite prepositions
------------------------------------------------------------------------ */
binarise(t(Cat,[h:T1,a:T2]),B,C):-
T1 = tree('PREP',Tok1),
T2 = tree(DPARG, h:tree('Dbar', h:tree('ART~DE', Tok2), a:Tree)),
constituent(DPARG,'DP-ARG'),
atom_codes(Tok1,Codes1), atom_codes(Tok2,Codes2),
append(_,[47|Codes],Codes1), append(_,[47|Codes],Codes2), !,
binarise(t(Cat,[h:tree('DEFPREP',Tok1),a:Tree]),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of embedded and relative clauses
------------------------------------------------------------------------ */
binarise(t(Cat,[h:T1,a:T2]),B,C):-
Cat = 'CONJP-OBJ',
T1 = tree('CONJ',_),
T2 =.. [tree,'S-ARG'|_], !,
binarise(t(Cat,[m:T1,h:T2]),B,C).
%binarise(t(Cat,[a:T1,h:T2]),B,C):-
% Cat = 'S-RMOD+RELCL',
% T1 = tree('NP-SUBJ',_),
% T2 =.. [tree,'Sbar'|_], !,
% binarise(t(Cat,[h:T1,a:T2]),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of double-headed preposition
------------------------------------------------------------------------ */
binarise(t(Cat,[h:T1,h:T2]),B,C):-
T1 =.. [tree,'PREP'|_],
T2 =.. [tree,'PP-CONTIN+PREP'|_], !,
binarise(t(Cat,[h:T1,a:T2]),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of name/noun compounds
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'Nbar'|_],
T2 =.. [tree,'NP-CONTIN+DENOM'|_], !,
sublist([h:t(Cat,[m:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'Nbar'|_],
T2 =.. [tree,'NOU~CA-CONTIN'|_], !,
sublist([h:t(Cat,[m:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of numerical compounds
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,'DP-CONTIN+NUM'|_], !,
sublist([h:t(Cat,[a:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,NUMRC|_],
constituent(NUMRC,'NUMR-CONTIN+NUM'), !,
sublist([h:t(Cat,[a:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,'Dbar-CONTIN+NUM'|_], !,
sublist([h:t(Cat,[a:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of comparative
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,'ADVB-COORDANTEC+COMPAR'|_],
T2 =.. [tree,'ADJ~QU'|_], !,
sublist([h:t(Cat,[h:T1,a:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of percentage expressions
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([h:T1,a:T2,h:T3],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,'SPECIAL-ARG-PERCENT'|_],
T3 =.. [tree,'PP-ARG-PARTITIVE'|_], !,
sublist([h:t(Cat,[h:T1,a:T2,a:T3])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([h:T1,a:T2,h:T3],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,'PP-ARG-PERCENT'|_],
T3 =.. [tree,'PP-ARG-PARTITIVE'|_], !,
sublist([h:t(Cat,[h:T1,a:T2,a:T3])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([h:T1,a:T2,a:T3,h:T4],L1,Before,After),
T1 =.. [tree,'NUMR'|_],
T2 =.. [tree,'SPECIAL-ARG-PERCENT'|_],
T3 =.. [tree,'PP-ARG'|_],
T4 =.. [tree,'PP-ARG-PARTITIVE'|_], !,
sublist([h:t(Cat,[h:T1,a:T2,a:T3,a:T4])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: repair of sentences with VP as subject
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([h:T1,h:T2],L1,Before,After),
T1 =.. [tree,VPSUBJ|_], constituent(VPSUBJ,'VP-SUBJ'),
T2 =.. [tree,'Sbar'|_], !,
sublist([h:t(Cat,[a:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: possessives (ALB-19)
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([a:T1,a:T2],L1,Before,After),
T1 =.. [tree,'ADJ~PO'|_],
T2 =.. [tree,'NOU~CS-ARG'|_], !,
sublist([h:t(Cat,[h:T1,a:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: DP modifiers (ALB-33, ALB-381)
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
sublist([m:T1,a:T2],L1,Before,After),
T1 =.. [tree,'ADVP-RMOD'|_],
T2 =.. [tree,'Dbar'|_], !,
sublist([h:t(Cat,[m:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([m:T1,a:T2],L1,Before,After),
T1 =.. [tree,'PRDT-RMOD'|_],
T2 =.. [tree,'Dbar'|_], !,
sublist([h:t(Cat,[m:T1,h:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
binarise(t(Cat,L1),B,C):-
sublist([a:T1,a:T2],L1,Before,After),
T1 =.. [tree,ADJ|_], constituent(ADJ,'ADJ'),
T2 =.. [tree,NOU|_], constituent(NOU,'NOU'), !,
sublist([h:t(Cat,[h:T1,a:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* -----------------------------------------------------------------------
Binarising: embedded clauses (CHIAM-47, V-19)
------------------------------------------------------------------------ */
binarise(t(Cat,L1),B,C):-
Cat = 'Vbar',
sublist([a:T1,m:T2],L1,Before,After),
T1 =.. [tree,VMA|_], constituent(VMA,'VMA~'),
T2 =.. [tree,CON|_], constituent(CON,'CONJP-OBJ'), !,
sublist([h:t(Cat,[h:T1,a:T2])],L2,Before,After),
binarise(t(Cat,L2),B,C).
/* ------------------------------------------------------
Binarising: headless monsters
------------------------------------------------------ */
binarise(t(Cat,Branches),Name,_):-
Branches = [_,_|_],
\+ member(h:_,Branches),
error('headless monster in ~p (~p)~n',[Name,Cat]),
printBranches(Branches),
!, fail.
/* ------------------------------------------------------
Binarising: two headed monsters
------------------------------------------------------ */
binarise(t(Cat,Branches),Name,_):-
select(h:_,Branches,Rest),
member(h:_,Rest),
error('two-headed monster in ~p (~p)~n',[Name,Cat]),
printBranches(Branches),
!, fail.
/* ------------------------------------------------------
Binarising: traces
------------------------------------------------------ */
binarise(t(Cat,[]),_,trace(S,Trace)):-
atom_chars(Cat,Chars),
append(Pre,['*','['|List],Chars), !,
atom_chars(Trace,['['|List]),
atom_chars(S,Pre).
binarise(t(Node,_,[h:tree('Nbar',h:tree(_,Word))]),_,trace(Node,'[]')):-
atom(Word),
atom_chars(Word,Chars),
append(_,['*','[',']'],Chars), !.
/* ------------------------------------------------------
Binarising: leaf nodes
------------------------------------------------------ */
binarise(t(Cat,[Word]),_,leaf(NewCat,Number,Token)):-
atom(Word),
atom_codes(Word,Codes),
append(NumCodes,[47|TokenCodes],Codes), !,
number_codes(Number,NumCodes),
atom_codes(Token,TokenCodes),
( atom_codes(Cat,CatCodes), append(NewCatCodes,[42|_],CatCodes), !, atom_codes(NewCat,NewCatCodes) ; NewCat = Cat ).
/* ------------------------------------------------------
Binarising: unary branching
------------------------------------------------------ */
binarise(t(N,[T:A]),Name,tree(N,T:B)):- !,
binarise(A,Name,B).
/* ------------------------------------------------------
Binarising: binary branching
------------------------------------------------------ */
binarise(t(N,[T1:A1,T2:A2]),Name,tree(N,T1:B1,T2:B2)):- !,
binarise(A1,Name,B1),
binarise(A2,Name,B2).
/* ------------------------------------------------------
Binarising: aux verbs
------------------------------------------------------ */
binarise(t(Node,B1),Name,Bin):-
Node = 'Vbar',
sublist([m:T1,h:T2],B1,Before,After),
T1 =.. [tree,'VP'|_], T2 =.. [tree,Verb|_],
member(Verb,['VMA~GE','VMA~PA','VMO~PA']), !,
sublist([h:t(Node,[m:T1,h:T2])],B2,Before,After),
binarise(t(Node,B2),Name,Bin).
/* ------------------------------------------------------
Binarising: punctuation (itemisation)
------------------------------------------------------ */
binarise(t(Node,Branches),Name,Bin):-
Branches = [Mod1,Mod2|Rest],
Mod1 = m:T1, T1 =.. [tree,'DP-RMOD-LISTPOS'|_],
Mod2 = m:T2, T2 =.. [tree,'PUNCT-SEPARATOR'|_], !,
Tree = t(Node,[m:tree('LISTPOS',a:T1,h:T2)|Rest]),
binarise(Tree,Name,Bin).
/* ------------------------------------------------------
Binarising: punctuation (separators)
------------------------------------------------------ */
binarise(t(Node,Branches),Name,Bin):-
Mod = m:tree('PUNCT-SEPARATOR',_),
member(Mod,Branches),
append([a:Tree3,Mod],Rest,Branches), !,
Tree = t(Node,[a:tree(Node,h:Tree3,Mod)|Rest]),
binarise(Tree,Name,Bin).
/* ------------------------------------------------------
Binarising: punctuation (brackets, quotes)
------------------------------------------------------ */
binarise(t(Node,Branches),Name,Bin):-
member(Open, ['PUNCT-OPEN+QUOTES', 'PUNCT-OPEN+PARENTHETICAL']),
member(Close,['PUNCT-CLOSE+QUOTES','PUNCT-CLOSE+PARENTHETICAL']),
TFi = m:tree(Open,Fi),
TLa = m:tree(Close,La),
append(Before,[TFi|Temp],Branches),
append(Mid,[TLa|After],Temp), !,
NTFi = m:tree(Open,Fi),
NTLa = m:tree(Close,La),
New = h:tree(Node,h:tree('PUNCT',NTFi,h:t(Node,Mid)),NTLa),
sublist([New],NewBranches,Before,After),
binarise(t(Node,NewBranches),Name,Bin).
/* ------------------------------------------------------
Binarising: ternary (or more) branching
------------------------------------------------------ */
binarise(t(Node,B1),Name,Bin):-
member(Pattern,[[h:_,a:_],[a:_,h:_],[h:_,m:_],[m:_,h:_]]),
sublist( Pattern, B1,Before,After), !,
sublist([h:t(Node,Pattern)],B2,Before,After),
binarise(t(Node,B2),Name,Bin).
/* ===========================================================
SubList
=========================================================== */
sublist(Sub,List,Before,After):-
append(Temp,After,List),
append(Before,Sub,Temp),!.
/* ===========================================================
Print branches
=========================================================== */
printBranches([]):-
error('.............~n',[]).
printBranches([X|L]):-
error(' ~p~n',[X]),
printBranches(L).
/* ===================================================================
Constituent checking
=================================================================== */
constituent(Cons,Goal):-
atom(Cons), atom(Goal),
atom_chars(Goal,GoalChars),
atom_chars(Cons,ConsChars),
append(GoalChars,_,ConsChars), !.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/candc/src/data/italian/prolog/binarise.pl | Perl | mit | 12,173 |
=begin pod
=head1 JSON::Tiny
C<JSON::Tiny> is a minimalistic module that reads and writes JSON.
It supports strings, numbers, arrays and hashes (no custom objects).
=head1 Synopsis
use JSON::Tiny;
my $json = to-json([1, 2, "a third item"]);
my $copy-of-original-data-structure = from-json($json);
=end pod
unit module JSON::Tiny;
use JSON::Tiny::Actions;
use JSON::Tiny::Grammar;
class X::JSON::Tiny::Invalid is Exception {
has $.source;
method message { "Input ($.source.chars() characters) is not a valid JSON string" }
}
proto to-json($) is export {*}
multi to-json(Real:D $d) { ~$d }
multi to-json(Bool:D $d) { $d ?? 'true' !! 'false'; }
multi to-json(Str:D $d) {
'"'
~ $d.trans(['"', '\\', "\b", "\f", "\n", "\r", "\t"]
=> ['\"', '\\\\', '\b', '\f', '\n', '\r', '\t'])\
.subst(/<-[\c32..\c126]>/, {
$_.Str.encode('utf-16').values».fmt('\u%04x').join
}, :g)
~ '"'
}
multi to-json(Positional:D $d) {
return '[ '
~ $d.flatmap(&to-json).join(', ')
~ ' ]';
}
multi to-json(Associative:D $d) {
return '{ '
~ $d.flatmap({ to-json(.key) ~ ' : ' ~ to-json(.value) }).join(', ')
~ ' }';
}
multi to-json(Mu:U $) { 'null' }
multi to-json(Mu:D $s) {
die "Can't serialize an object of type " ~ $s.WHAT.perl
}
sub from-json($text) is export {
my $a = JSON::Tiny::Actions.new();
my $o = JSON::Tiny::Grammar.parse($text, :actions($a));
unless $o {
X::JSON::Tiny::Invalid.new(source => $text).throw;
}
return $o.made;
}
# vim: ft=perl6
| niner/panda | ext/JSON__Tiny/lib/JSON/Tiny.pm | Perl | mit | 1,619 |
# Copyright 1999-2006 University of Chicago
#
# 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.
# Globus::GRAM::JobManager::fork package
#
# CVS Information:
# $Source$
# $Date$
# $Revision$
# $Author$
use Globus::GRAM::Error;
use Globus::GRAM::JobState;
use Globus::GRAM::JobManager;
use Globus::GRAM::StdioMerger;
use Globus::Core::Paths;
use Globus::Core::Config;
use Config;
use IPC::Open2;
package Globus::GRAM::JobManager::fork;
@ISA = qw(Globus::GRAM::JobManager);
my ($mpirun, $mpiexec, $log_path);
my ($starter_in, $starter_out, $starter_index) = (undef, undef, 0);
my %signo;
BEGIN
{
my $i = 0;
foreach (split(' ', $Config::Config{sig_name}))
{
$signo{$_} = $i++;
}
my $config = new Globus::Core::Config(
'${sysconfdir}/globus/globus-fork.conf');
if ($config)
{
$mpirun = $config->get_attribute("mpirun") || "no";
if ($mpirun ne "no" && ! -x $mpirun)
{
$mpirun = "no";
}
$mpiexec = $config->get_attribute("mpiexec") || "no";
if ($mpiexec ne "no" && ! -x $mpiexec)
{
$mpiexec = "no";
}
$softenv_dir = $config->get_attribute("softenv_dir") || "";
$log_path = $config->get_attribute("log_path") || "/dev/null";
}
else
{
$mpirun = "no";
$mpiexec = "no";
$softenv_dir = "";
$log_path = "/dev/null";
}
}
sub new
{
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = $class->SUPER::new(@_);
my $description = $self->{JobDescription};
my $stdout = $description->stdout();
my $stderr = $description->stderr();
if($description->jobtype() eq 'multiple' && $description->count > 1)
{
$self->{STDIO_MERGER} =
new Globus::GRAM::StdioMerger($self->job_dir(), $stdout, $stderr);
}
else
{
$self->{STDIO_MERGER} = 0;
}
return $self;
}
sub submit
{
my $self = shift;
my $cmd;
my $pid;
my $pgid;
my @job_id;
my $count;
my $multi_output = 0;
my $description = $self->{JobDescription};
my $pipe;
my @cmdline;
my @environment;
my @arguments;
my $fork_starter = "$Globus::Core::Paths::sbindir/globus-fork-starter";
my $streamer = "$Globus::Core::Paths::sbindir/globus-gram-streamer";
my $is_grid_monitor = 0;
my $soft_msc = "$softenv_dir/bin/soft-msc";
my $softenv_load = "$softenv_dir/etc/softenv-load.sh";
$starter_index++;
if(!defined($description->directory()))
{
return Globus::GRAM::Error::RSL_DIRECTORY;
}
if ($description->directory() =~ m|^[^/]|) {
$description->add("directory",
$ENV{HOME} . '/' . $description->directory());
}
chdir $description->directory() or
return Globus::GRAM::Error::BAD_DIRECTORY;
@environment = $description->environment();
foreach $tuple ($description->environment())
{
if(!ref($tuple) || scalar(@$tuple) != 2)
{
return Globus::GRAM::Error::RSL_ENVIRONMENT();
}
$CHILD_ENV{$tuple->[0]} = $tuple->[1];
}
if(ref($description->count()) ||
$description->count() != int($description->count()))
{
return Globus::GRAM::Error::INVALID_COUNT();
}
if($description->jobtype() eq 'multiple')
{
$count = $description->count();
$multi_output = 1 if $count > 1;
}
elsif($description->jobtype() eq 'single')
{
$count = 1;
}
elsif($description->jobtype() eq 'mpi' && $mpiexec ne 'no')
{
$count = 1;
@cmdline = ($mpiexec, '-n', $description->count());
}
elsif($description->jobtype() eq 'mpi' && $mpirun ne 'no')
{
$count = 1;
@cmdline = ($mpirun, '-np', $description->count());
}
else
{
return Globus::GRAM::Error::JOBTYPE_NOT_SUPPORTED();
}
if( $description->executable eq "")
{
return Globus::GRAM::Error::RSL_EXECUTABLE();
}
elsif(! -e $description->executable())
{
return Globus::GRAM::Error::EXECUTABLE_NOT_FOUND();
}
elsif( (! -x $description->executable())
|| (! -f $description->executable()))
{
return Globus::GRAM::Error::EXECUTABLE_PERMISSIONS();
}
elsif( $description->stdin() eq "")
{
return Globus::GRAM::Error::RSL_STDIN;
}
elsif(! -r $description->stdin())
{
return Globus::GRAM::Error::STDIN_NOT_FOUND();
}
if ($description->executable() =~ m:^(/|\.):) {
push(@cmdline, $description->executable());
} else {
push(@cmdline,
$description->directory()
. '/'
. $description->executable());
}
# Check if this is the Condor-G grid monitor
my $exec = $description->executable();
my $file_out = `/usr/bin/file $exec`;
if ( $file_out =~ /script/ || $file_out =~ /text/ ||
$file_out =~ m|/usr/bin/env| ) {
open( EXEC, "<$exec" ) or
return Globus::GRAM::Error::EXECUTABLE_PERMISSIONS();
while( <EXEC> ) {
if ( /Sends results from the grid_manager_monitor_agent back to a/ ) {
$is_grid_monitor = 1;
}
}
close( EXEC );
}
# Reject jobs that want streaming, if so configured, but not for
# grid monitor jobs
if ( $description->streamingrequested() &&
$description->streamingdisabled() && !$is_grid_monitor ) {
$self->log("Streaming is not allowed.");
return Globus::GRAM::Error::OPENING_STDOUT;
}
@arguments = $description->arguments();
foreach(@arguments)
{
if(ref($_))
{
return Globus::GRAM::Error::RSL_ARGUMENTS;
}
}
if ($#arguments >= 0)
{
push(@cmdline, @arguments);
}
if ($description->use_fork_starter())
{
if (!-x $fork_starter)
{
for my $path_component (split(/:/, $ENV{PATH}))
{
if (-x "$path_component/globus-fork-starter") {
$fork_starter ="$path_component/globus-fork-starter";
last;
}
}
}
}
if ($description->use_fork_starter() && -x $fork_starter)
{
if (!defined($starter_in) && !defined($starter_out))
{
$pid = IPC::Open2::open2($starter_out, $starter_in,
"$fork_starter $log_path");
my $oldfh = select $starter_out;
$|=1;
select $oldfh;
}
print $starter_in "100;perl-fork-start-$$-$starter_index;";
print $starter_in 'directory='.
&escape_for_starter($description->directory()) . ';';
if (keys %CHILD_ENV > 0) {
print $starter_in 'environment='.
join(',', map { &escape_for_starter($_)
.'='.&escape_for_starter($CHILD_ENV{$_})
} (keys %CHILD_ENV)) . ';';
}
print $starter_in "count=$count;";
my @softenv = $description->softenv();
my $enable_default_software_environment
= $description->enable_default_software_environment();
if ( ($softenv_dir ne '')
&& (@softenv || $enable_default_software_environment))
{
### SoftEnv extension ###
$cmd_script_name = $self->job_dir() . '/scheduler_fork_cmd_script';
local(*CMD);
open( CMD, '>' . $cmd_script_name );
print CMD "#!/bin/sh\n";
$self->setup_softenv(
$self->job_dir() . '/fork_softenv_cmd_script',
$soft_msc,
$softenv_load,
*CMD);
print CMD 'cd ', $description->directory(), "\n";
print CMD "@cmdline\n";
print CMD "exit \$?\n";
close(CMD);
chmod 0700, $cmd_script_name;
print $starter_in 'executable=' .
&escape_for_starter($cmd_script_name). ';';
print $starter_in 'arguments=;';
#########################
}
else
{
print $starter_in 'executable=' .
&escape_for_starter($cmdline[0]). ';';
shift @cmdline;
if ($#cmdline >= 0)
{
print $starter_in 'arguments=' .
join(',', map {&escape_for_starter($_)} @cmdline) .
';';
}
}
my @job_stdout;
my @job_stderr;
for ($i = 0; $i < $count; $i++) {
if($multi_output)
{
push(@job_stdout, $self->{STDIO_MERGER}->add_file('out'));
push(@job_stderr, $self->{STDIO_MERGER}->add_file('err'));
}
else
{
if (defined($description->stdout)) {
push(@job_stdout, $description->stdout());
} else {
push(@job_stdout, '/dev/null');
}
if (defined($description->stderr)) {
push(@job_stderr, $description->stderr());
} else {
push(@job_stderr, '/dev/null');
}
}
}
print $starter_in "stdin=" . &escape_for_starter($description->stdin()).
';';
print $starter_in "stdout=" .
join(',', map {&escape_for_starter($_)} @job_stdout) . ';';
print $starter_in "stderr=" .
join(',', map {&escape_for_starter($_)} @job_stderr) . "\n";
while (<$starter_out>) {
chomp;
my @res = split(/;/, $_);
if ($res[1] ne "perl-fork-start-$$-$starter_index") {
next;
}
if ($res[0] == '101') {
@job_id = split(',', $res[2]);
last;
} elsif ($res[0] == '102') {
$self->respond({GT3_FAILURE_MESSAGE => "starter: $res[3]" });
return new Globus::GRAM::Error($res[2]);
}
}
if ($is_grid_monitor)
{
if (! -x $streamer)
{
for my $path_component (split(/:/, $ENV{PATH})) {
if (-x "$path_component/$globus-gram-streamer")
{
$streamer = "$path_component/$globus-gram-streamer";
last;
}
}
}
}
if ($is_grid_monitor && -x $streamer)
{
my $streamer_startup='';
$starter_index++;
$streamer_startup .= "100;perl-fork-start-$$-$starter_index;";
$streamer_startup .= 'directory='.$self->job_dir().';';
if (keys %CHILD_ENV > 0) {
$streamer_startup .= 'environment='.
join(',', map { &escape_for_starter($_)
.'='.&escape_for_starter($CHILD_ENV{$_})
} (keys %CHILD_ENV)) . ';';
}
$streamer_startup .= "count=1;";
$streamer_startup .= 'executable=' . &escape_for_starter($streamer)
. ';';
@cmdline = ('-s', $description->state_file());
foreach my $p (@job_id)
{
my $q = $p;
# strip leading uuid
$q =~ s/.*://;
push(@cmdline, '-p', $q);
}
$streamer_startup .= 'arguments=' .
join(',', map {&escape_for_starter($_)} @cmdline) .
';';
$streamer_startup .= "stdin=/dev/null;";
$streamer_startup .= "stdout=gram_streamer_out;";
$streamer_startup .= "stderr=gram_streamer_err\n";
$self->log("streamer_startup is $streamer_startup");
print $starter_in $streamer_startup;
while (<$starter_out>) {
chomp;
my @res = split(/;/, $_);
if ($res[1] ne "perl-fork-start-$$-$starter_index") {
next;
}
if ($res[0] == '101') {
@job_id = (@job_id, split(',', $res[2]));
last;
} elsif ($res[0] == '102') {
$self->respond({GT3_FAILURE_MESSAGE => "starter: $res[3]" });
return new Globus::GRAM::Error($res[2]);
}
}
}
$description->add('jobid', join(',', @job_id));
return { JOB_STATE => Globus::GRAM::JobState::ACTIVE,
JOB_ID => join(',', @job_id) };
} else {
my $starter_pid;
local(*READER,*WRITER); # always use local on perl FDs
pipe(READER, WRITER);
$starter_pid = fork();
if (! defined($starter_pid))
{
$failure_code = "fork:$!";
$self->respond({GT3_FAILURE_MESSAGE => $failure_code });
return Globus::GRAM::Error::JOB_EXECUTION_FAILED;
}
elsif ($starter_pid == 0)
{
# Starter Process
close(READER);
local(*JOB_READER, *JOB_WRITER);
pipe(JOB_READER, JOB_WRITER);
for(my $i = 0; $i < $count; $i++)
{
if($multi_output)
{
$job_stdout = $self->{STDIO_MERGER}->add_file('out');
$job_stderr = $self->{STDIO_MERGER}->add_file('err');
}
else
{
$job_stdout = $description->stdout();
$job_stderr = $description->stderr();
}
# obtain plain old pipe into temporary variables
local $^F = 2; # assure close-on-exec for pipe FDs
select((select(WRITER),$|=1)[$[]);
if( ($pid=fork()) == 0)
{
close(JOB_READER);
# forked child
%ENV = %CHILD_ENV;
close(STDIN);
close(STDOUT);
close(STDERR);
open(STDIN, '<' . $description->stdin());
open(STDOUT, ">>$job_stdout");
open(STDERR, ">>$job_stderr");
# the below should never fail since we just forked
setpgrp(0,$$);
if ( ! exec (@cmdline) )
{
my $err = "$!\n";
$SIG{PIPE} = 'IGNORE';
print JOB_WRITER "$err";
close(JOB_WRITER);
exit(1);
}
}
else
{
my $error_code = '';
if ($pid == undef)
{
$self->log("fork failed\n");
$failure_code = "fork: $!";
}
close(JOB_WRITER);
$_ = <JOB_READER>;
close(JOB_READER);
if($_ ne '')
{
chomp($_);
$self->log("exec failed\n");
$failure_code = "exec: $_";
}
if ($failure_code ne '')
{
# fork or exec failed. kill rest of job and return an error
$failure_code =~ s/\n/\\n/g;
foreach(@job_id)
{
$pgid = getpgrp($_);
$pgid == -1 ? kill($signo{TERM}, $_) :
kill(-$signo{TERM}, $pgid);
sleep(5);
$pgid == -1 ? kill($signo{KILL}, $_) :
kill(-$signo{KILL}, $pgid);
}
local(*ERR);
open(ERR, '>' . $description->stderr());
print ERR "$failure_code\n";
close(ERR);
print WRITER "FAIL:$failure_code\n";
exit(1);
}
push(@job_id, $pid);
}
}
if ($is_grid_monitor)
{
# Create an extra process to stream output for grid monitor
# obtain plain old pipe into temporary variables
local $^F = 2; # assure close-on-exec for pipe FDs
select((select(WRITER),$|=1)[$[]);
if( ($pid=fork()) == 0)
{
close(JOB_READER);
# forked child
%ENV = %CHILD_ENV;
close(STDIN);
close(STDOUT);
close(STDERR);
chdir $self->job_dir();
open(STDIN, '<' . $description->stdin());
open(STDOUT, '>gram_streamer_out');
open(STDERR, '>gram_streamer_error');
select STDERR; $| = 1; # make unbuffered
select STDOUT; $| = 1; # make unbuffered
# the below should never fail since we just forked
setpgrp(0,$$);
@cmdline = ($streamer, '-s', $description->state_file());
foreach my $p (@job_id)
{
push(@cmdline, '-p', $p);
}
if ( ! exec (@cmdline) )
{
my $err = "$!\n";
$SIG{PIPE} = 'IGNORE';
print JOB_WRITER "$err";
close(JOB_WRITER);
exit(1);
}
}
else
{
my $error_code = '';
if ($pid == undef)
{
$self->log("fork failed\n");
$failure_code = "fork: $!";
}
close(JOB_WRITER);
$_ = <JOB_READER>;
close(JOB_READER);
if($_ ne '')
{
chomp($_);
$self->log("exec failed\n");
$failure_code = "exec: $_";
}
if ($failure_code ne '')
{
# fork or exec failed. kill rest of job and return an error
$failure_code =~ s/\n/\\n/g;
foreach(@job_id)
{
$pgid = getpgrp($_);
$pgid == -1 ? kill($signo{TERM}, $_) :
kill(-$signo{TERM}, $pgid);
sleep(5);
$pgid == -1 ? kill($signo{KILL}, $_) :
kill(-$signo{KILL}, $pgid);
}
local(*ERR);
open(ERR, '>' . $description->stderr());
print ERR "$failure_code\n";
close(ERR);
print WRITER "FAIL:$failure_code\n";
exit(1);
}
push(@job_id, $pid);
}
}
print WRITER "SUCCESS:" . join(',', @job_id) . "\n";
exit(0);
}
else
{
my ($res, $value);
close(WRITER);
$_ = <READER>;
close(READER);
chomp($_);
waitpid($starter_pid, 0);
($res, $value) = split(/:/, $_, 2);
if ($res eq 'SUCCESS')
{
$description->add('jobid', $value);
return { JOB_STATE => Globus::GRAM::JobState::ACTIVE,
JOB_ID => $value };
}
elsif ($res eq 'FAIL')
{
$self->respond({GT3_FAILURE_MESSAGE => "$value" });
return Globus::GRAM::Error::JOB_EXECUTION_FAILED;
}
else
{
return Globus::GRAM::Error::JOB_EXECUTION_FAILED;
}
}
}
}
sub poll
{
my $self = shift;
my $description = $self->{JobDescription};
my $state;
my $jobid = $description->jobid();
if(!defined $jobid)
{
$self->log("poll: job id defined!");
return { JOB_STATE => Globus::GRAM::JobState::FAILED };
}
$self->log("polling job " . $jobid);
$_ = kill(0, split(/,/, $jobid));
if($_ > 0)
{
$state = Globus::GRAM::JobState::ACTIVE;
}
else
{
$state = Globus::GRAM::JobState::DONE;
}
if($self->{STDIO_MERGER})
{
$self->{STDIO_MERGER}->poll($state == Globus::GRAM::JobState::DONE);
}
return { JOB_STATE => $state };
}
sub cancel
{
my $self = shift;
my $description = $self->{JobDescription};
my $pgid;
my $jobid = $description->jobid();
if(!defined $jobid)
{
$self->log("cancel: no jobid defined!");
return { JOB_STATE => Globus::GRAM::JobState::FAILED };
}
$self->log("cancel job " . $jobid);
foreach (split(/,/,$jobid))
{
s/..*://;
$pgid = getpgrp($_);
$pgid == -1 ? kill($signo{TERM}, $_) :
kill(-$signo{TERM}, $pgid);
sleep(5);
$pgid == -1 ? kill($signo{KILL}, $_) :
kill(-$signo{KILL}, $pgid);
}
return { JOB_STATE => Globus::GRAM::JobState::FAILED };
}
sub stage_out
{
my $self = shift;
my $description = $self->{JobDescription};
my $is_grid_monitor = 0;
my $job_dir = $self->job_dir();
my $rc;
my $line;
my @fields;
my $stream_out;
$self->log("Fork stage out");
# Check if this is the Condor-G grid monitor
my $exec = $description->executable();
my $file_out = `/usr/bin/file $exec`;
if ( $file_out =~ /script/ || $file_out =~ /text/ ||
$file_out =~ m|/usr/bin/env| ) {
open( EXEC, "<$exec" ) or
return Globus::GRAM::Error::EXECUTABLE_PERMISSIONS();
while( <EXEC> ) {
if ( /Sends results from the grid_manager_monitor_agent back to a/ ) {
$is_grid_monitor = 1;
}
}
close( EXEC );
}
if ($is_grid_monitor)
{
$self->log("Fork stage out is grid monitor");
local(*STREAMER_ERROR, *STREAMER_OUTPUT);
$rc = open(STREAMER_ERROR, "<$job_dir/gram_streamer_error");
if (!$rc)
{
$self->log("Error opening gram_streamer_error: $!");
}
chomp($line = <STREAMER_ERROR>);
if ($line eq '')
{
$self->log("No error from streamer");
}
else
{
$self->log("Error from streamer $line");
@fields = split(':', $line, 2);
$self->respond({GT3_FAILURE_MESSAGE => "$fields[0]" });
return new Globus::GRAM::Error($fields[1]);
}
close(STREAMER_ERROR);
$stream_out = $description->get('file_stream_out');
$rc = open(STREAMER_OUTPUT, "<$job_dir/gram_streamer_out");
if (!$rc)
{
$self->log("Error opening gram_streamer_output: $!");
}
else
{
while ($line = <STREAMER_OUTPUT>)
{
chomp($line);
$self->log("Streamer output: $line");
my ($from, $to) = split(' ', $line);
for (my $i = 0; $i < scalar(@{$stream_out}); $i++)
{
my $pair = $stream_out->[$i];
if ($pair->[0] eq $from && $pair->[1] eq $to)
{
splice(@{$stream_out}, $i, 1);
last;
}
}
$self->respond({'STAGED_STREAM' => "$from $to"});
}
$description->add('filestreamout', $stream_out);
}
}
return $self->SUPER::stage_out();
}
sub escape_for_starter
{
my $str = shift;
$str =~ s/\\/\\\\/g;
$str =~ s/;/\\;/g;
$str =~ s/,/\\,/g;
$str =~ s/\n/\\n/g;
$str =~ s/=/\\=/g;
return $str;
}
END
{
if (defined($starter_in))
{
close($starter_in);
}
if (defined($starter_out))
{
close($starter_out);
}
}
1;
| globus/globus-toolkit | gram/jobmanager/lrms/fork/source/fork.pm | Perl | apache-2.0 | 25,231 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
000B 000C
2028 2029
END
| Dokaponteam/ITF_Project | xampp/perl/lib/unicore/lib/Lb/BK.pl | Perl | mit | 431 |
package DDG::Spice::BitbucketStatus;
# ABSTRACT: Returns the status of Bitbucket
use DDG::Spice;
use Text::Trim;
spice is_cached => 1;
spice proxy_cache_valid => "200 5m";
spice wrap_jsonp_callback => 1;
spice to => 'http://status.bitbucket.org/index.json';
triggers any => 'bitbucket', 'bb';
handle remainder => sub {
return $_ if m/^(is\s*)?(system)?\s*(status|up|down)\s*(of\s*)?$/i; # return if query contains (system) status, up or down; (system) status of and etc
return;
};
1;
| soleo/zeroclickinfo-spice | lib/DDG/Spice/BitbucketStatus.pm | Perl | apache-2.0 | 499 |
=head1 NAME
perldebguts - Guts of Perl debugging
=head1 DESCRIPTION
This is not L<perldebug>, which tells you how to use
the debugger. This manpage describes low-level details concerning
the debugger's internals, which range from difficult to impossible
to understand for anyone who isn't incredibly intimate with Perl's guts.
Caveat lector.
=head1 Debugger Internals
Perl has special debugging hooks at compile-time and run-time used
to create debugging environments. These hooks are not to be confused
with the I<perl -Dxxx> command described in L<perlrun>, which is
usable only if a special Perl is built per the instructions in the
F<INSTALL> podpage in the Perl source tree.
For example, whenever you call Perl's built-in C<caller> function
from the package C<DB>, the arguments that the corresponding stack
frame was called with are copied to the C<@DB::args> array. These
mechanisms are enabled by calling Perl with the B<-d> switch.
Specifically, the following additional features are enabled
(cf. L<perlvar/$^P>):
=over 4
=item *
Perl inserts the contents of C<$ENV{PERL5DB}> (or C<BEGIN {require
'perl5db.pl'}> if not present) before the first line of your program.
=item *
Each array C<@{"_<$filename"}> holds the lines of $filename for a
file compiled by Perl. The same is also true for C<eval>ed strings
that contain subroutines, or which are currently being executed.
The $filename for C<eval>ed strings looks like C<(eval 34)>.
Code assertions in regexes look like C<(re_eval 19)>.
Values in this array are magical in numeric context: they compare
equal to zero only if the line is not breakable.
=item *
Each hash C<%{"_<$filename"}> contains breakpoints and actions keyed
by line number. Individual entries (as opposed to the whole hash)
are settable. Perl only cares about Boolean true here, although
the values used by F<perl5db.pl> have the form
C<"$break_condition\0$action">.
The same holds for evaluated strings that contain subroutines, or
which are currently being executed. The $filename for C<eval>ed strings
looks like C<(eval 34)> or C<(re_eval 19)>.
=item *
Each scalar C<${"_<$filename"}> contains C<"_<$filename">. This is
also the case for evaluated strings that contain subroutines, or
which are currently being executed. The $filename for C<eval>ed
strings looks like C<(eval 34)> or C<(re_eval 19)>.
=item *
After each C<require>d file is compiled, but before it is executed,
C<DB::postponed(*{"_<$filename"})> is called if the subroutine
C<DB::postponed> exists. Here, the $filename is the expanded name of
the C<require>d file, as found in the values of %INC.
=item *
After each subroutine C<subname> is compiled, the existence of
C<$DB::postponed{subname}> is checked. If this key exists,
C<DB::postponed(subname)> is called if the C<DB::postponed> subroutine
also exists.
=item *
A hash C<%DB::sub> is maintained, whose keys are subroutine names
and whose values have the form C<filename:startline-endline>.
C<filename> has the form C<(eval 34)> for subroutines defined inside
C<eval>s, or C<(re_eval 19)> for those within regex code assertions.
=item *
When the execution of your program reaches a point that can hold a
breakpoint, the C<DB::DB()> subroutine is called if any of the variables
C<$DB::trace>, C<$DB::single>, or C<$DB::signal> is true. These variables
are not C<local>izable. This feature is disabled when executing
inside C<DB::DB()>, including functions called from it
unless C<< $^D & (1<<30) >> is true.
=item *
When execution of the program reaches a subroutine call, a call to
C<&DB::sub>(I<args>) is made instead, with C<$DB::sub> holding the
name of the called subroutine. (This doesn't happen if the subroutine
was compiled in the C<DB> package.)
=back
Note that if C<&DB::sub> needs external data for it to work, no
subroutine call is possible without it. As an example, the standard
debugger's C<&DB::sub> depends on the C<$DB::deep> variable
(it defines how many levels of recursion deep into the debugger you can go
before a mandatory break). If C<$DB::deep> is not defined, subroutine
calls are not possible, even though C<&DB::sub> exists.
=head2 Writing Your Own Debugger
=head3 Environment Variables
The C<PERL5DB> environment variable can be used to define a debugger.
For example, the minimal "working" debugger (it actually doesn't do anything)
consists of one line:
sub DB::DB {}
It can easily be defined like this:
$ PERL5DB="sub DB::DB {}" perl -d your-script
Another brief debugger, slightly more useful, can be created
with only the line:
sub DB::DB {print ++$i; scalar <STDIN>}
This debugger prints a number which increments for each statement
encountered and waits for you to hit a newline before continuing
to the next statement.
The following debugger is actually useful:
{
package DB;
sub DB {}
sub sub {print ++$i, " $sub\n"; &$sub}
}
It prints the sequence number of each subroutine call and the name of the
called subroutine. Note that C<&DB::sub> is being compiled into the
package C<DB> through the use of the C<package> directive.
When it starts, the debugger reads your rc file (F<./.perldb> or
F<~/.perldb> under Unix), which can set important options.
(A subroutine (C<&afterinit>) can be defined here as well; it is executed
after the debugger completes its own initialization.)
After the rc file is read, the debugger reads the PERLDB_OPTS
environment variable and uses it to set debugger options. The
contents of this variable are treated as if they were the argument
of an C<o ...> debugger command (q.v. in L<perldebug/"Configurable Options">).
=head3 Debugger Internal Variables
In addition to the file and subroutine-related variables mentioned above,
the debugger also maintains various magical internal variables.
=over 4
=item *
C<@DB::dbline> is an alias for C<@{"::_<current_file"}>, which
holds the lines of the currently-selected file (compiled by Perl), either
explicitly chosen with the debugger's C<f> command, or implicitly by flow
of execution.
Values in this array are magical in numeric context: they compare
equal to zero only if the line is not breakable.
=item *
C<%DB::dbline> is an alias for C<%{"::_<current_file"}>, which
contains breakpoints and actions keyed by line number in
the currently-selected file, either explicitly chosen with the
debugger's C<f> command, or implicitly by flow of execution.
As previously noted, individual entries (as opposed to the whole hash)
are settable. Perl only cares about Boolean true here, although
the values used by F<perl5db.pl> have the form
C<"$break_condition\0$action">.
=back
=head3 Debugger Customization Functions
Some functions are provided to simplify customization.
=over 4
=item *
See L<perldebug/"Configurable Options"> for a description of options parsed by
C<DB::parse_options(string)>.
=item *
C<DB::dump_trace(skip[,count])> skips the specified number of frames
and returns a list containing information about the calling frames (all
of them, if C<count> is missing). Each entry is reference to a hash
with keys C<context> (either C<.>, C<$>, or C<@>), C<sub> (subroutine
name, or info about C<eval>), C<args> (C<undef> or a reference to
an array), C<file>, and C<line>.
=item *
C<DB::print_trace(FH, skip[, count[, short]])> prints
formatted info about caller frames. The last two functions may be
convenient as arguments to C<< < >>, C<< << >> commands.
=back
Note that any variables and functions that are not documented in
this manpages (or in L<perldebug>) are considered for internal
use only, and as such are subject to change without notice.
=head1 Frame Listing Output Examples
The C<frame> option can be used to control the output of frame
information. For example, contrast this expression trace:
$ perl -de 42
Stack dump during die enabled outside of evals.
Loading DB routines from perl5db.pl patch level 0.94
Emacs support available.
Enter h or 'h h' for help.
main::(-e:1): 0
DB<1> sub foo { 14 }
DB<2> sub bar { 3 }
DB<3> t print foo() * bar()
main::((eval 172):3): print foo() + bar();
main::foo((eval 168):2):
main::bar((eval 170):2):
42
with this one, once the C<o>ption C<frame=2> has been set:
DB<4> o f=2
frame = '2'
DB<5> t print foo() * bar()
3: foo() * bar()
entering main::foo
2: sub foo { 14 };
exited main::foo
entering main::bar
2: sub bar { 3 };
exited main::bar
42
By way of demonstration, we present below a laborious listing
resulting from setting your C<PERLDB_OPTS> environment variable to
the value C<f=n N>, and running I<perl -d -V> from the command line.
Examples using various values of C<n> are shown to give you a feel
for the difference between settings. Long though it may be, this
is not a complete listing, but only excerpts.
=over 4
=item 1
entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
entering Config::TIEHASH
entering Exporter::import
entering Exporter::export
entering Config::myconfig
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
entering Config::FETCH
=item 2
entering main::BEGIN
entering Config::BEGIN
Package lib/Exporter.pm.
Package lib/Carp.pm.
exited Config::BEGIN
Package lib/Config.pm.
entering Config::TIEHASH
exited Config::TIEHASH
entering Exporter::import
entering Exporter::export
exited Exporter::export
exited Exporter::import
exited main::BEGIN
entering Config::myconfig
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
exited Config::FETCH
entering Config::FETCH
=item 3
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from li
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osname') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'osvers') from lib/Config.pm:574
=item 4
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
out $=main::BEGIN() from /dev/null:0
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'package') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'baserev') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
out $=Config::FETCH(ref(Config), 'PERL_VERSION') from lib/Config.pm:574
in $=Config::FETCH(ref(Config), 'PERL_SUBVERSION') from lib/Config.pm:574
=item 5
in $=main::BEGIN() from /dev/null:0
in $=Config::BEGIN() from lib/Config.pm:2
Package lib/Exporter.pm.
Package lib/Carp.pm.
out $=Config::BEGIN() from lib/Config.pm:0
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:644
out $=Config::TIEHASH('Config') from lib/Config.pm:644
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/E
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
out $=main::BEGIN() from /dev/null:0
in @=Config::myconfig() from /dev/null:0
in $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'package') from lib/Config.pm:574
in $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
out $=Config::FETCH('Config=HASH(0x1aa444)', 'baserev') from lib/Config.pm:574
=item 6
in $=CODE(0x15eca4)() from /dev/null:0
in $=CODE(0x182528)() from lib/Config.pm:2
Package lib/Exporter.pm.
out $=CODE(0x182528)() from lib/Config.pm:0
scalar context return from CODE(0x182528): undef
Package lib/Config.pm.
in $=Config::TIEHASH('Config') from lib/Config.pm:628
out $=Config::TIEHASH('Config') from lib/Config.pm:628
scalar context return from Config::TIEHASH: empty hash
in $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
in $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
out $=Exporter::export('Config', 'main', 'myconfig', 'config_vars') from lib/Exporter.pm:171
scalar context return from Exporter::export: ''
out $=Exporter::import('Config', 'myconfig', 'config_vars') from /dev/null:0
scalar context return from Exporter::import: ''
=back
In all cases shown above, the line indentation shows the call tree.
If bit 2 of C<frame> is set, a line is printed on exit from a
subroutine as well. If bit 4 is set, the arguments are printed
along with the caller info. If bit 8 is set, the arguments are
printed even if they are tied or references. If bit 16 is set, the
return value is printed, too.
When a package is compiled, a line like this
Package lib/Carp.pm.
is printed with proper indentation.
=head1 Debugging Regular Expressions
There are two ways to enable debugging output for regular expressions.
If your perl is compiled with C<-DDEBUGGING>, you may use the
B<-Dr> flag on the command line.
Otherwise, one can C<use re 'debug'>, which has effects at
compile time and run time. Since Perl 5.9.5, this pragma is lexically
scoped.
=head2 Compile-time Output
The debugging output at compile time looks like this:
Compiling REx '[bc]d(ef*g)+h[ij]k$'
size 45 Got 364 bytes for offset annotations.
first at 1
rarest char g at 0
rarest char d at 0
1: ANYOF[bc](12)
12: EXACT <d>(14)
14: CURLYX[0] {1,32767}(28)
16: OPEN1(18)
18: EXACT <e>(20)
20: STAR(23)
21: EXACT <f>(0)
23: EXACT <g>(25)
25: CLOSE1(27)
27: WHILEM[1/1](0)
28: NOTHING(29)
29: EXACT <h>(31)
31: ANYOF[ij](42)
42: EXACT <k>(44)
44: EOL(45)
45: END(0)
anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating)
stclass 'ANYOF[bc]' minlen 7
Offsets: [45]
1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]
Omitting $` $& $' support.
The first line shows the pre-compiled form of the regex. The second
shows the size of the compiled form (in arbitrary units, usually
4-byte words) and the total number of bytes allocated for the
offset/length table, usually 4+C<size>*8. The next line shows the
label I<id> of the first node that does a match.
The
anchored 'de' at 1 floating 'gh' at 3..2147483647 (checking floating)
stclass 'ANYOF[bc]' minlen 7
line (split into two lines above) contains optimizer
information. In the example shown, the optimizer found that the match
should contain a substring C<de> at offset 1, plus substring C<gh>
at some offset between 3 and infinity. Moreover, when checking for
these substrings (to abandon impossible matches quickly), Perl will check
for the substring C<gh> before checking for the substring C<de>. The
optimizer may also use the knowledge that the match starts (at the
C<first> I<id>) with a character class, and no string
shorter than 7 characters can possibly match.
The fields of interest which may appear in this line are
=over 4
=item C<anchored> I<STRING> C<at> I<POS>
=item C<floating> I<STRING> C<at> I<POS1..POS2>
See above.
=item C<matching floating/anchored>
Which substring to check first.
=item C<minlen>
The minimal length of the match.
=item C<stclass> I<TYPE>
Type of first matching node.
=item C<noscan>
Don't scan for the found substrings.
=item C<isall>
Means that the optimizer information is all that the regular
expression contains, and thus one does not need to enter the regex engine at
all.
=item C<GPOS>
Set if the pattern contains C<\G>.
=item C<plus>
Set if the pattern starts with a repeated char (as in C<x+y>).
=item C<implicit>
Set if the pattern starts with C<.*>.
=item C<with eval>
Set if the pattern contain eval-groups, such as C<(?{ code })> and
C<(??{ code })>.
=item C<anchored(TYPE)>
If the pattern may match only at a handful of places, with C<TYPE>
being C<BOL>, C<MBOL>, or C<GPOS>. See the table below.
=back
If a substring is known to match at end-of-line only, it may be
followed by C<$>, as in C<floating 'k'$>.
The optimizer-specific information is used to avoid entering (a slow) regex
engine on strings that will not definitely match. If the C<isall> flag
is set, a call to the regex engine may be avoided even when the optimizer
found an appropriate place for the match.
Above the optimizer section is the list of I<nodes> of the compiled
form of the regex. Each line has format
C< >I<id>: I<TYPE> I<OPTIONAL-INFO> (I<next-id>)
=head2 Types of Nodes
Here are the possible types, with short descriptions:
# TYPE arg-description [num-args] [longjump-len] DESCRIPTION
# Exit points
END no End of program.
SUCCEED no Return from a subroutine, basically.
# Anchors:
BOL no Match "" at beginning of line.
MBOL no Same, assuming multiline.
SBOL no Same, assuming singleline.
EOS no Match "" at end of string.
EOL no Match "" at end of line.
MEOL no Same, assuming multiline.
SEOL no Same, assuming singleline.
BOUND no Match "" at any word boundary using native charset
semantics for non-utf8
BOUNDL no Match "" at any locale word boundary
BOUNDU no Match "" at any word boundary using Unicode semantics
BOUNDA no Match "" at any word boundary using ASCII semantics
NBOUND no Match "" at any word non-boundary using native charset
semantics for non-utf8
NBOUNDL no Match "" at any locale word non-boundary
NBOUNDU no Match "" at any word non-boundary using Unicode semantics
NBOUNDA no Match "" at any word non-boundary using ASCII semantics
GPOS no Matches where last m//g left off.
# [Special] alternatives:
REG_ANY no Match any one character (except newline).
SANY no Match any one character.
CANY no Match any one byte.
ANYOF sv Match character in (or not in) this class, single char
match only
ANYOFV sv Match character in (or not in) this class, can
match-multiple chars
ALNUM no Match any alphanumeric character using native charset
semantics for non-utf8
ALNUML no Match any alphanumeric char in locale
ALNUMU no Match any alphanumeric char using Unicode semantics
ALNUMA no Match [A-Za-z_0-9]
NALNUM no Match any non-alphanumeric character using native charset
semantics for non-utf8
NALNUML no Match any non-alphanumeric char in locale
NALNUMU no Match any non-alphanumeric char using Unicode semantics
NALNUMA no Match [^A-Za-z_0-9]
SPACE no Match any whitespace character using native charset
semantics for non-utf8
SPACEL no Match any whitespace char in locale
SPACEU no Match any whitespace char using Unicode semantics
SPACEA no Match [ \t\n\f\r]
NSPACE no Match any non-whitespace character using native charset
semantics for non-utf8
NSPACEL no Match any non-whitespace char in locale
NSPACEU no Match any non-whitespace char using Unicode semantics
NSPACEA no Match [^ \t\n\f\r]
DIGIT no Match any numeric character using native charset semantics
for non-utf8
DIGITL no Match any numeric character in locale
DIGITA no Match [0-9]
NDIGIT no Match any non-numeric character using native charset
i semantics for non-utf8
NDIGITL no Match any non-numeric character in locale
NDIGITA no Match [^0-9]
CLUMP no Match any extended grapheme cluster sequence
# Alternation
# BRANCH The set of branches constituting a single choice are hooked
# together with their "next" pointers, since precedence prevents
# anything being concatenated to any individual branch. The
# "next" pointer of the last BRANCH in a choice points to the
# thing following the whole choice. This is also where the
# final "next" pointer of each individual branch points; each
# branch starts with the operand node of a BRANCH node.
#
BRANCH node Match this alternative, or the next...
# Back pointer
# BACK Normal "next" pointers all implicitly point forward; BACK
# exists to make loop structures possible.
# not used
BACK no Match "", "next" ptr points backward.
# Literals
EXACT str Match this string (preceded by length).
EXACTF str Match this string, folded, native charset semantics for
non-utf8 (prec. by length).
EXACTFL str Match this string, folded in locale (w/len).
EXACTFU str Match this string, folded, Unicode semantics for non-utf8
(prec. by length).
EXACTFA str Match this string, folded, Unicode semantics for non-utf8,
but no ASCII-range character matches outside ASCII (prec.
by length),.
# Do nothing types
NOTHING no Match empty string.
# A variant of above which delimits a group, thus stops optimizations
TAIL no Match empty string. Can jump here from outside.
# Loops
# STAR,PLUS '?', and complex '*' and '+', are implemented as circular
# BRANCH structures using BACK. Simple cases (one character
# per match) are implemented with STAR and PLUS for speed
# and to minimize recursive plunges.
#
STAR node Match this (simple) thing 0 or more times.
PLUS node Match this (simple) thing 1 or more times.
CURLY sv 2 Match this simple thing {n,m} times.
CURLYN no 2 Capture next-after-this simple thing
CURLYM no 2 Capture this medium-complex thing {n,m} times.
CURLYX sv 2 Match this complex thing {n,m} times.
# This terminator creates a loop structure for CURLYX
WHILEM no Do curly processing and see if rest matches.
# Buffer related
# OPEN,CLOSE,GROUPP ...are numbered at compile time.
OPEN num 1 Mark this point in input as start of #n.
CLOSE num 1 Analogous to OPEN.
REF num 1 Match some already matched string
REFF num 1 Match already matched string, folded using native charset
semantics for non-utf8
REFFL num 1 Match already matched string, folded in loc.
REFFU num 1 Match already matched string, folded using unicode
semantics for non-utf8
REFFA num 1 Match already matched string, folded using unicode
semantics for non-utf8, no mixing ASCII, non-ASCII
# Named references. Code in regcomp.c assumes that these all are after the
# numbered references
NREF no-sv 1 Match some already matched string
NREFF no-sv 1 Match already matched string, folded using native charset
semantics for non-utf8
NREFFL no-sv 1 Match already matched string, folded in loc.
NREFFU num 1 Match already matched string, folded using unicode
semantics for non-utf8
NREFFA num 1 Match already matched string, folded using unicode
semantics for non-utf8, no mixing ASCII, non-ASCII
IFMATCH off 1 2 Succeeds if the following matches.
UNLESSM off 1 2 Fails if the following matches.
SUSPEND off 1 1 "Independent" sub-RE.
IFTHEN off 1 1 Switch, should be preceded by switcher.
GROUPP num 1 Whether the group matched.
# Support for long RE
LONGJMP off 1 1 Jump far away.
BRANCHJ off 1 1 BRANCH with long offset.
# The heavy worker
EVAL evl 1 Execute some Perl code.
# Modifiers
MINMOD no Next operator is not greedy.
LOGICAL no Next opcode should set the flag only.
# This is not used yet
RENUM off 1 1 Group with independently numbered parens.
# Trie Related
# Behave the same as A|LIST|OF|WORDS would. The '..C' variants have
# inline charclass data (ascii only), the 'C' store it in the structure.
# NOTE: the relative order of the TRIE-like regops is significant
TRIE trie 1 Match many EXACT(F[ALU]?)? at once. flags==type
TRIEC charclass Same as TRIE, but with embedded charclass data
# For start classes, contains an added fail table.
AHOCORASICK trie 1 Aho Corasick stclass. flags==type
AHOCORASICKC charclass Same as AHOCORASICK, but with embedded charclass data
# Regex Subroutines
GOSUB num/ofs 2L recurse to paren arg1 at (signed) ofs arg2
GOSTART no recurse to start of pattern
# Special conditionals
NGROUPP no-sv 1 Whether the group matched.
INSUBP num 1 Whether we are in a specific recurse.
DEFINEP none 1 Never execute directly.
# Backtracking Verbs
ENDLIKE none Used only for the type field of verbs
OPFAIL none Same as (?!)
ACCEPT parno 1 Accepts the current matched string.
# Verbs With Arguments
VERB no-sv 1 Used only for the type field of verbs
PRUNE no-sv 1 Pattern fails at this startpoint if no-backtracking through this
MARKPOINT no-sv 1 Push the current location for rollback by cut.
SKIP no-sv 1 On failure skip forward (to the mark) before retrying
COMMIT no-sv 1 Pattern fails outright if backtracking through this
CUTGROUP no-sv 1 On failure go to the next alternation in the group
# Control what to keep in $&.
KEEPS no $& begins here.
# New charclass like patterns
LNBREAK none generic newline pattern
VERTWS none vertical whitespace (Perl 6)
NVERTWS none not vertical whitespace (Perl 6)
HORIZWS none horizontal whitespace (Perl 6)
NHORIZWS none not horizontal whitespace (Perl 6)
FOLDCHAR codepoint 1 codepoint with tricky case folding properties.
# SPECIAL REGOPS
# This is not really a node, but an optimized away piece of a "long" node.
# To simplify debugging output, we mark it as if it were a node
OPTIMIZED off Placeholder for dump.
# Special opcode with the property that no opcode in a compiled program
# will ever be of this type. Thus it can be used as a flag value that
# no other opcode has been seen. END is used similarly, in that an END
# node cant be optimized. So END implies "unoptimizable" and PSEUDO mean
# "not seen anything to optimize yet".
PSEUDO off Pseudo opcode for internal use.
=for unprinted-credits
Next section M-J. Dominus (mjd-perl-patch+@plover.com) 20010421
Following the optimizer information is a dump of the offset/length
table, here split across several lines:
Offsets: [45]
1[4] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 5[1]
0[0] 12[1] 0[0] 6[1] 0[0] 7[1] 0[0] 9[1] 8[1] 0[0] 10[1] 0[0]
11[1] 0[0] 12[0] 12[0] 13[1] 0[0] 14[4] 0[0] 0[0] 0[0] 0[0]
0[0] 0[0] 0[0] 0[0] 0[0] 0[0] 18[1] 0[0] 19[1] 20[0]
The first line here indicates that the offset/length table contains 45
entries. Each entry is a pair of integers, denoted by C<offset[length]>.
Entries are numbered starting with 1, so entry #1 here is C<1[4]> and
entry #12 is C<5[1]>. C<1[4]> indicates that the node labeled C<1:>
(the C<1: ANYOF[bc]>) begins at character position 1 in the
pre-compiled form of the regex, and has a length of 4 characters.
C<5[1]> in position 12
indicates that the node labeled C<12:>
(the C<< 12: EXACT <d> >>) begins at character position 5 in the
pre-compiled form of the regex, and has a length of 1 character.
C<12[1]> in position 14
indicates that the node labeled C<14:>
(the C<< 14: CURLYX[0] {1,32767} >>) begins at character position 12 in the
pre-compiled form of the regex, and has a length of 1 character---that
is, it corresponds to the C<+> symbol in the precompiled regex.
C<0[0]> items indicate that there is no corresponding node.
=head2 Run-time Output
First of all, when doing a match, one may get no run-time output even
if debugging is enabled. This means that the regex engine was never
entered and that all of the job was therefore done by the optimizer.
If the regex engine was entered, the output may look like this:
Matching '[bc]d(ef*g)+h[ij]k$' against 'abcdefg__gh__'
Setting an EVAL scope, savestack=3
2 <ab> <cdefg__gh_> | 1: ANYOF
3 <abc> <defg__gh_> | 11: EXACT <d>
4 <abcd> <efg__gh_> | 13: CURLYX {1,32767}
4 <abcd> <efg__gh_> | 26: WHILEM
0 out of 1..32767 cc=effff31c
4 <abcd> <efg__gh_> | 15: OPEN1
4 <abcd> <efg__gh_> | 17: EXACT <e>
5 <abcde> <fg__gh_> | 19: STAR
EXACT <f> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
6 <bcdef> <g__gh__> | 22: EXACT <g>
7 <bcdefg> <__gh__> | 24: CLOSE1
7 <bcdefg> <__gh__> | 26: WHILEM
1 out of 1..32767 cc=effff31c
Setting an EVAL scope, savestack=12
7 <bcdefg> <__gh__> | 15: OPEN1
7 <bcdefg> <__gh__> | 17: EXACT <e>
restoring \1 to 4(4)..7
failed, try continuation...
7 <bcdefg> <__gh__> | 27: NOTHING
7 <bcdefg> <__gh__> | 28: EXACT <h>
failed...
failed...
The most significant information in the output is about the particular I<node>
of the compiled regex that is currently being tested against the target string.
The format of these lines is
C< >I<STRING-OFFSET> <I<PRE-STRING>> <I<POST-STRING>> |I<ID>: I<TYPE>
The I<TYPE> info is indented with respect to the backtracking level.
Other incidental information appears interspersed within.
=head1 Debugging Perl Memory Usage
Perl is a profligate wastrel when it comes to memory use. There
is a saying that to estimate memory usage of Perl, assume a reasonable
algorithm for memory allocation, multiply that estimate by 10, and
while you still may miss the mark, at least you won't be quite so
astonished. This is not absolutely true, but may provide a good
grasp of what happens.
Assume that an integer cannot take less than 20 bytes of memory, a
float cannot take less than 24 bytes, a string cannot take less
than 32 bytes (all these examples assume 32-bit architectures, the
result are quite a bit worse on 64-bit architectures). If a variable
is accessed in two of three different ways (which require an integer,
a float, or a string), the memory footprint may increase yet another
20 bytes. A sloppy malloc(3) implementation can inflate these
numbers dramatically.
On the opposite end of the scale, a declaration like
sub foo;
may take up to 500 bytes of memory, depending on which release of Perl
you're running.
Anecdotal estimates of source-to-compiled code bloat suggest an
eightfold increase. This means that the compiled form of reasonable
(normally commented, properly indented etc.) code will take
about eight times more space in memory than the code took
on disk.
The B<-DL> command-line switch is obsolete since circa Perl 5.6.0
(it was available only if Perl was built with C<-DDEBUGGING>).
The switch was used to track Perl's memory allocations and possible
memory leaks. These days the use of malloc debugging tools like
F<Purify> or F<valgrind> is suggested instead. See also
L<perlhacktips/PERL_MEM_LOG>.
One way to find out how much memory is being used by Perl data
structures is to install the Devel::Size module from CPAN: it gives
you the minimum number of bytes required to store a particular data
structure. Please be mindful of the difference between the size()
and total_size().
If Perl has been compiled using Perl's malloc you can analyze Perl
memory usage by setting $ENV{PERL_DEBUG_MSTATS}.
=head2 Using C<$ENV{PERL_DEBUG_MSTATS}>
If your perl is using Perl's malloc() and was compiled with the
necessary switches (this is the default), then it will print memory
usage statistics after compiling your code when C<< $ENV{PERL_DEBUG_MSTATS}
> 1 >>, and before termination of the program when C<<
$ENV{PERL_DEBUG_MSTATS} >= 1 >>. The report format is similar to
the following example:
$ PERL_DEBUG_MSTATS=2 perl -e "require Carp"
Memory allocation statistics after compilation: (buckets 4(4)..8188(8192)
14216 free: 130 117 28 7 9 0 2 2 1 0 0
437 61 36 0 5
60924 used: 125 137 161 55 7 8 6 16 2 0 1
74 109 304 84 20
Total sbrk(): 77824/21:119. Odd ends: pad+heads+chain+tail: 0+636+0+2048.
Memory allocation statistics after execution: (buckets 4(4)..8188(8192)
30888 free: 245 78 85 13 6 2 1 3 2 0 1
315 162 39 42 11
175816 used: 265 176 1112 111 26 22 11 27 2 1 1
196 178 1066 798 39
Total sbrk(): 215040/47:145. Odd ends: pad+heads+chain+tail: 0+2192+0+6144.
It is possible to ask for such a statistic at arbitrary points in
your execution using the mstat() function out of the standard
Devel::Peek module.
Here is some explanation of that format:
=over 4
=item C<buckets SMALLEST(APPROX)..GREATEST(APPROX)>
Perl's malloc() uses bucketed allocations. Every request is rounded
up to the closest bucket size available, and a bucket is taken from
the pool of buckets of that size.
The line above describes the limits of buckets currently in use.
Each bucket has two sizes: memory footprint and the maximal size
of user data that can fit into this bucket. Suppose in the above
example that the smallest bucket were size 4. The biggest bucket
would have usable size 8188, and the memory footprint would be 8192.
In a Perl built for debugging, some buckets may have negative usable
size. This means that these buckets cannot (and will not) be used.
For larger buckets, the memory footprint may be one page greater
than a power of 2. If so, the corresponding power of two is
printed in the C<APPROX> field above.
=item Free/Used
The 1 or 2 rows of numbers following that correspond to the number
of buckets of each size between C<SMALLEST> and C<GREATEST>. In
the first row, the sizes (memory footprints) of buckets are powers
of two--or possibly one page greater. In the second row, if present,
the memory footprints of the buckets are between the memory footprints
of two buckets "above".
For example, suppose under the previous example, the memory footprints
were
free: 8 16 32 64 128 256 512 1024 2048 4096 8192
4 12 24 48 80
With a non-C<DEBUGGING> perl, the buckets starting from C<128> have
a 4-byte overhead, and thus an 8192-long bucket may take up to
8188-byte allocations.
=item C<Total sbrk(): SBRKed/SBRKs:CONTINUOUS>
The first two fields give the total amount of memory perl sbrk(2)ed
(ess-broken? :-) and number of sbrk(2)s used. The third number is
what perl thinks about continuity of returned chunks. So long as
this number is positive, malloc() will assume that it is probable
that sbrk(2) will provide continuous memory.
Memory allocated by external libraries is not counted.
=item C<pad: 0>
The amount of sbrk(2)ed memory needed to keep buckets aligned.
=item C<heads: 2192>
Although memory overhead of bigger buckets is kept inside the bucket, for
smaller buckets, it is kept in separate areas. This field gives the
total size of these areas.
=item C<chain: 0>
malloc() may want to subdivide a bigger bucket into smaller buckets.
If only a part of the deceased bucket is left unsubdivided, the rest
is kept as an element of a linked list. This field gives the total
size of these chunks.
=item C<tail: 6144>
To minimize the number of sbrk(2)s, malloc() asks for more memory. This
field gives the size of the yet unused part, which is sbrk(2)ed, but
never touched.
=back
=head1 SEE ALSO
L<perldebug>,
L<perlguts>,
L<perlrun>
L<re>,
and
L<Devel::DProf>.
| Dokaponteam/ITF_Project | xampp/perl/lib/pods/perldebguts.pod | Perl | mit | 37,672 |
use strict;
use warnings;
use File::Copy;
my $cmd_string = join (" ",@ARGV);
my $results = `$cmd_string`;
my @files = split("\n",$results);
my $fileNameOut = $ARGV[6];
my ($drive, $outputDir, $file) = File::Spec->splitpath( $fileNameOut );
my $destination = $fileNameOut;
foreach my $thisLine (@files)
{
if ($thisLine =~ /Created /)
{
$thisLine =~ /[\w|\.]+$/;
$thisLine =$&;
#print "outfile: $thisLine\n";
#there is only one file to move, so we can quit after finding it
move($drive.$outputDir.$thisLine,$fileNameOut);
exit(1);
}
else
{
print $thisLine,"\n";
}
}
| loraine-gueguen/tools-iuc | tools/emboss_5/emboss_single_outputfile_wrapper.pl | Perl | mit | 586 |
# Copyright (C) 2008 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
# Copyright (C) 2008 Martin Soto <soto@freedesktop.org>
# Copyright (C) 2008 Alp Toker <alp@atoker.com>
# Copyright (C) 2009 Adam Dingle <adam@yorba.org>
# Copyright (C) 2009 Jim Nelson <jim@yorba.org>
# Copyright (C) 2009, 2010 Igalia S.L.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB. If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
package CodeGeneratorGObject;
use constant FileNamePrefix => "WebKitDOM";
# Global Variables
my %implIncludes = ();
my %hdrIncludes = ();
my $defineTypeMacro = "G_DEFINE_TYPE";
my $defineTypeInterfaceImplementation = ")";
my @txtEventListeners = ();
my @txtInstallProps = ();
my @txtSetProps = ();
my @txtGetProps = ();
my $className = "";
# FIXME: this should be replaced with a function that recurses up the tree
# to find the actual base type.
my %baseTypeHash = ("Object" => 1, "Node" => 1, "NodeList" => 1, "NamedNodeMap" => 1, "DOMImplementation" => 1,
"Event" => 1, "CSSRule" => 1, "CSSValue" => 1, "StyleSheet" => 1, "MediaList" => 1,
"Counter" => 1, "Rect" => 1, "RGBColor" => 1, "XPathExpression" => 1, "XPathResult" => 1,
"NodeIterator" => 1, "TreeWalker" => 1, "AbstractView" => 1, "Blob" => 1, "DOMTokenList" => 1,
"HTMLCollection" => 1);
# List of function parameters that are allowed to be NULL
my $canBeNullParams = {
'webkit_dom_document_evaluate' => ['inResult', 'resolver'],
'webkit_dom_node_insert_before' => ['refChild'],
'webkit_dom_dom_window_get_computed_style' => ['pseudoElement']
};
# Default constructor
sub new {
my $object = shift;
my $reference = { };
$codeGenerator = shift;
bless($reference, $object);
}
my $licenceTemplate = << "EOF";
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
EOF
sub GetParentClassName {
my $interface = shift;
return "WebKitDOMObject" unless $interface->parent;
return "WebKitDOM" . $interface->parent;
}
sub GetParentImplClassName {
my $interface = shift;
return "Object" unless $interface->parent;
return $interface->parent;
}
sub IsBaseType
{
my $type = shift;
return 1 if $baseTypeHash{$type};
return 0;
}
sub GetBaseClass
{
$parent = shift;
return $parent if $parent eq "Object" or IsBaseType($parent);
return "Event" if $parent eq "UIEvent" or $parent eq "MouseEvent";
return "CSSValue" if $parent eq "SVGColor" or $parent eq "CSSValueList";
return "Node";
}
# From String::CamelCase 0.01
sub camelize
{
my $s = shift;
join('', map{ ucfirst $_ } split(/(?<=[A-Za-z])_(?=[A-Za-z])|\b/, $s));
}
sub decamelize
{
my $s = shift;
$s =~ s{([^a-zA-Z]?)([A-Z]*)([A-Z])([a-z]?)}{
my $fc = pos($s)==0;
my ($p0,$p1,$p2,$p3) = ($1,lc$2,lc$3,$4);
my $t = $p0 || $fc ? $p0 : '_';
$t .= $p3 ? $p1 ? "${p1}_$p2$p3" : "$p2$p3" : "$p1$p2";
$t;
}ge;
# Some strings are not correctly decamelized, apply fix ups
for ($s) {
s/domcss/dom_css/;
s/domhtml/dom_html/;
s/domdom/dom_dom/;
s/domcdata/dom_cdata/;
s/domui/dom_ui/;
s/x_path/xpath/;
s/web_kit/webkit/;
s/htmli_frame/html_iframe/;
}
return $s;
}
sub HumanReadableConditional {
my @conditional = split('_', shift);
my @upperCaseExceptions = ("SQL", "API");
my @humanReadable;
for $part (@conditional) {
if (!grep {$_ eq $part} @upperCaseExceptions) {
$part = camelize(lc($part));
}
push(@humanReadable, $part);
}
return join(' ', @humanReadable);
}
sub GetParentGObjType {
my $interface = shift;
return "WEBKIT_TYPE_DOM_OBJECT" unless $interface->parent;
return "WEBKIT_TYPE_DOM_" . uc(decamelize(($interface->parent)));
}
sub GetClassName {
my $name = shift;
return "WebKitDOM$name";
}
sub GetCoreObject {
my ($interfaceName, $name, $parameter) = @_;
return "WebCore::${interfaceName}* $name = WebKit::core($parameter);";
}
sub SkipAttribute {
my $attribute = shift;
if ($attribute->signature->extendedAttributes->{"Custom"}
|| $attribute->signature->extendedAttributes->{"CustomGetter"}
|| $attribute->signature->extendedAttributes->{"CustomSetter"}) {
return 1;
}
my $propType = $attribute->signature->type;
if ($propType =~ /Constructor$/) {
return 1;
}
return 1 if $attribute->isStatic;
return 1 if $codeGenerator->IsTypedArrayType($propType);
$codeGenerator->AssertNotSequenceType($propType);
if ($codeGenerator->GetArrayType($propType)) {
return 1;
}
if ($codeGenerator->IsEnumType($propType)) {
return 1;
}
# This is for DOMWindow.idl location attribute
if ($attribute->signature->name eq "location") {
return 1;
}
# This is for HTMLInput.idl valueAsDate
if ($attribute->signature->name eq "valueAsDate") {
return 1;
}
# This is for DOMWindow.idl Crypto attribute
if ($attribute->signature->type eq "Crypto") {
return 1;
}
# Skip indexed database attributes for now, they aren't yet supported for the GObject generator.
if ($attribute->signature->name =~ /^(?:webkit)?[Ii]ndexedDB/ or $attribute->signature->name =~ /^(?:webkit)?IDB/) {
return 1;
}
return 0;
}
sub SkipFunction {
my $function = shift;
my $decamelize = shift;
my $prefix = shift;
my $functionName = "webkit_dom_" . $decamelize . "_" . $prefix . decamelize($function->signature->name);
my $functionReturnType = $prefix eq "set_" ? "void" : $function->signature->type;
my $isCustomFunction = $function->signature->extendedAttributes->{"Custom"};
my $callWith = $function->signature->extendedAttributes->{"CallWith"};
my $isUnsupportedCallWith = $codeGenerator->ExtendedAttributeContains($callWith, "ScriptArguments") || $codeGenerator->ExtendedAttributeContains($callWith, "CallStack");
if (($isCustomFunction || $isUnsupportedCallWith) &&
$functionName ne "webkit_dom_node_replace_child" &&
$functionName ne "webkit_dom_node_insert_before" &&
$functionName ne "webkit_dom_node_remove_child" &&
$functionName ne "webkit_dom_node_append_child" &&
$functionName ne "webkit_dom_html_collection_item" &&
$functionName ne "webkit_dom_html_collection_named_item") {
return 1;
}
if ($function->signature->name eq "getSVGDocument") {
return 1;
}
if ($function->signature->name eq "getCSSCanvasContext") {
return 1;
}
if ($function->signature->name eq "setRangeText" && @{$function->parameters} == 1) {
return 1;
}
# This is for DataTransferItemList.idl add(File) method
if ($functionName eq "webkit_dom_data_transfer_item_list_add" &&
@{$function->parameters} == 1) {
return 1;
}
if ($function->signature->name eq "timeEnd") {
return 1;
}
if ($codeGenerator->GetSequenceType($functionReturnType)) {
return 1;
}
if ($function->signature->name eq "supports" && @{$function->parameters} == 1) {
return 1;
}
# Skip functions that have callback parameters, because this
# code generator doesn't know how to auto-generate callbacks.
# Skip functions that have "MediaQueryListListener" or sequence<T> parameters, because this
# code generator doesn't know how to auto-generate MediaQueryListListener or sequence<T>.
foreach my $param (@{$function->parameters}) {
if ($codeGenerator->IsCallbackInterface($param->type) ||
$param->extendedAttributes->{"Clamp"} ||
$param->type eq "MediaQueryListListener" ||
$codeGenerator->GetSequenceType($param->type)) {
return 1;
}
}
return 0;
}
# Name type used in the g_value_{set,get}_* functions
sub GetGValueTypeName {
my $type = shift;
my %types = ("DOMString", "string",
"DOMTimeStamp", "uint",
"float", "float",
"double", "double",
"boolean", "boolean",
"char", "char",
"long", "long",
"long long", "int64",
"byte", "int8",
"octet", "uint8",
"short", "int",
"uchar", "uchar",
"unsigned", "uint",
"int", "int",
"unsigned int", "uint",
"unsigned long long", "uint64",
"unsigned long", "ulong",
"unsigned short", "uint");
return $types{$type} ? $types{$type} : "object";
}
# Name type used in C declarations
sub GetGlibTypeName {
my $type = shift;
my $name = GetClassName($type);
my %types = ("DOMString", "gchar*",
"DOMTimeStamp", "guint32",
"CompareHow", "gushort",
"float", "gfloat",
"double", "gdouble",
"boolean", "gboolean",
"char", "gchar",
"long", "glong",
"long long", "gint64",
"byte", "gint8",
"octet", "guint8",
"short", "gshort",
"uchar", "guchar",
"unsigned", "guint",
"int", "gint",
"unsigned int", "guint",
"unsigned long", "gulong",
"unsigned long long", "guint64",
"unsigned short", "gushort",
"void", "void");
return $types{$type} ? $types{$type} : "$name*";
}
sub IsGDOMClassType {
my $type = shift;
return 0 if $codeGenerator->IsNonPointerType($type) || $codeGenerator->IsStringType($type);
return 1;
}
sub GetReadableProperties {
my $properties = shift;
my @result = ();
foreach my $property (@{$properties}) {
if (!SkipAttribute($property)) {
push(@result, $property);
}
}
return @result;
}
sub GetWriteableProperties {
my $properties = shift;
my @result = ();
foreach my $property (@{$properties}) {
my $gtype = GetGValueTypeName($property->signature->type);
my $hasGtypeSignature = ($gtype eq "boolean" || $gtype eq "float" || $gtype eq "double" ||
$gtype eq "uint64" || $gtype eq "ulong" || $gtype eq "long" ||
$gtype eq "uint" || $gtype eq "ushort" || $gtype eq "int8" ||
$gtype eq "uint8" || $gtype eq "uchar" || $gtype eq "char" ||
$gtype eq "string");
# FIXME: We are not generating setters for 'Replaceable'
# attributes now, but we should somehow.
my $replaceable = $property->signature->extendedAttributes->{"Replaceable"};
if (!$property->isReadOnly && $hasGtypeSignature && !$replaceable) {
push(@result, $property);
}
}
return @result;
}
sub GenerateConditionalWarning
{
my $node = shift;
my $indentSize = shift;
if (!$indentSize) {
$indentSize = 4;
}
my $conditional = $node->extendedAttributes->{"Conditional"};
my @warn;
if ($conditional) {
if ($conditional =~ /&/) {
my @splitConditionals = split(/&/, $conditional);
foreach $condition (@splitConditionals) {
push(@warn, "#if !ENABLE($condition)\n");
push(@warn, ' ' x $indentSize . "WEBKIT_WARN_FEATURE_NOT_PRESENT(\"" . HumanReadableConditional($condition) . "\")\n");
push(@warn, "#endif\n");
}
} elsif ($conditional =~ /\|/) {
foreach $condition (split(/\|/, $conditional)) {
push(@warn, ' ' x $indentSize . "WEBKIT_WARN_FEATURE_NOT_PRESENT(\"" . HumanReadableConditional($condition) . "\")\n");
}
} else {
push(@warn, ' ' x $indentSize . "WEBKIT_WARN_FEATURE_NOT_PRESENT(\"" . HumanReadableConditional($conditional) . "\")\n");
}
}
return @warn;
}
sub GenerateProperty {
my $attribute = shift;
my $interfaceName = shift;
my @writeableProperties = @{shift @_};
my $parentNode = shift;
my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
my @conditionalWarn = GenerateConditionalWarning($attribute->signature, 8);
my $parentConditionalString = $codeGenerator->GenerateConditionalString($parentNode);
my @parentConditionalWarn = GenerateConditionalWarning($parentNode, 8);
my $camelPropName = $attribute->signature->name;
my $setPropNameFunction = $codeGenerator->WK_ucfirst($camelPropName);
my $getPropNameFunction = $codeGenerator->WK_lcfirst($camelPropName);
my $hasGetterException = $attribute->signature->extendedAttributes->{"GetterRaisesException"};
my $hasSetterException = $attribute->signature->extendedAttributes->{"SetterRaisesException"};
my $propName = decamelize($camelPropName);
my $propNameCaps = uc($propName);
$propName =~ s/_/-/g;
my ${propEnum} = "PROP_${propNameCaps}";
push(@cBodyProperties, " ${propEnum},\n");
my $propType = $attribute->signature->type;
my ${propGType} = decamelize($propType);
my ${ucPropGType} = uc($propGType);
my $gtype = GetGValueTypeName($propType);
my $gparamflag = "WEBKIT_PARAM_READABLE";
my $writeable = !$attribute->isReadOnly;
my $const = "read-only ";
my $custom = $attribute->signature->extendedAttributes->{"Custom"};
if ($writeable && $custom) {
$const = "read-only (due to custom functions needed in webkitdom)";
return;
}
if ($writeable && !$custom) {
$gparamflag = "WEBKIT_PARAM_READWRITE";
$const = "read-write ";
}
my $type = GetGlibTypeName($propType);
$nick = decamelize("${interfaceName}_${propName}");
$long = "${const} ${type} ${interfaceName}.${propName}";
my $convertFunction = "";
if ($gtype eq "string") {
$convertFunction = "WTF::String::fromUTF8";
}
my ($getterFunctionName, @getterArguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $attribute);
my ($setterFunctionName, @setterArguments) = $codeGenerator->SetterExpression(\%implIncludes, $interfaceName, $attribute);
if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
push(@setterArguments, "${convertFunction}(g_value_get_$gtype(value))");
unshift(@getterArguments, "coreSelf");
unshift(@setterArguments, "coreSelf");
$getterFunctionName = "WebCore::${implementedBy}::$getterFunctionName";
$setterFunctionName = "WebCore::${implementedBy}::$setterFunctionName";
} else {
push(@setterArguments, "${convertFunction}(g_value_get_$gtype(value))");
$getterFunctionName = "coreSelf->$getterFunctionName";
$setterFunctionName = "coreSelf->$setterFunctionName";
}
push(@getterArguments, "isNull") if $attribute->signature->isNullable;
push(@getterArguments, "ec") if $hasGetterException;
push(@setterArguments, "ec") if $hasSetterException;
if (grep {$_ eq $attribute} @writeableProperties) {
push(@txtSetProps, " case ${propEnum}: {\n");
push(@txtSetProps, "#if ${parentConditionalString}\n") if $parentConditionalString;
push(@txtSetProps, "#if ${conditionalString}\n") if $conditionalString;
push(@txtSetProps, " WebCore::ExceptionCode ec = 0;\n") if $hasSetterException;
push(@txtSetProps, " ${setterFunctionName}(" . join(", ", @setterArguments) . ");\n");
push(@txtSetProps, "#else\n") if $conditionalString;
push(@txtSetProps, @conditionalWarn) if scalar(@conditionalWarn);
push(@txtSetProps, "#endif /* ${conditionalString} */\n") if $conditionalString;
push(@txtSetProps, "#else\n") if $parentConditionalString;
push(@txtSetProps, @parentConditionalWarn) if scalar(@parentConditionalWarn);
push(@txtSetProps, "#endif /* ${parentConditionalString} */\n") if $parentConditionalString;
push(@txtSetProps, " break;\n }\n");
}
push(@txtGetProps, " case ${propEnum}: {\n");
push(@txtGetProps, "#if ${parentConditionalString}\n") if $parentConditionalString;
push(@txtGetProps, "#if ${conditionalString}\n") if $conditionalString;
push(@txtGetProps, " bool isNull = false;\n") if $attribute->signature->isNullable;
push(@txtGetProps, " WebCore::ExceptionCode ec = 0;\n") if $hasGetterException;
# FIXME: Should we return a default value when isNull == true?
my $postConvertFunction = "";
my $done = 0;
if ($gtype eq "string") {
push(@txtGetProps, " g_value_take_string(value, convertToUTF8String(${getterFunctionName}(" . join(", ", @getterArguments) . ")));\n");
$done = 1;
} elsif ($gtype eq "object") {
push(@txtGetProps, " RefPtr<WebCore::${propType}> ptr = ${getterFunctionName}(" . join(", ", @getterArguments) . ");\n");
push(@txtGetProps, " g_value_set_object(value, WebKit::kit(ptr.get()));\n");
$done = 1;
}
# FIXME: get rid of this glitch?
my $_gtype = $gtype;
if ($gtype eq "ushort") {
$_gtype = "uint";
}
if (!$done) {
if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
push(@txtGetProps, " g_value_set_$_gtype(value, ${convertFunction}${getterFunctionName}(" . join(", ", @getterArguments) . ")${postConvertFunction});\n");
} else {
push(@txtGetProps, " g_value_set_$_gtype(value, ${convertFunction}${getterFunctionName}(" . join(", ", @getterArguments) . ")${postConvertFunction});\n");
}
}
push(@txtGetProps, "#else\n") if $conditionalString;
push(@txtGetProps, @conditionalWarn) if scalar(@conditionalWarn);
push(@txtGetProps, "#endif /* ${conditionalString} */\n") if $conditionalString;
push(@txtGetProps, "#else\n") if $parentConditionalString;
push(@txtGetProps, @parentConditionalWarn) if scalar(@parentConditionalWarn);
push(@txtGetProps, "#endif /* ${parentConditionalString} */\n") if $parentConditionalString;
push(@txtGetProps, " break;\n }\n");
my %param_spec_options = ("int", "G_MININT, /* min */\nG_MAXINT, /* max */\n0, /* default */",
"int8", "G_MININT8, /* min */\nG_MAXINT8, /* max */\n0, /* default */",
"boolean", "FALSE, /* default */",
"float", "-G_MAXFLOAT, /* min */\nG_MAXFLOAT, /* max */\n0.0, /* default */",
"double", "-G_MAXDOUBLE, /* min */\nG_MAXDOUBLE, /* max */\n0.0, /* default */",
"uint64", "0, /* min */\nG_MAXUINT64, /* min */\n0, /* default */",
"long", "G_MINLONG, /* min */\nG_MAXLONG, /* max */\n0, /* default */",
"int64", "G_MININT64, /* min */\nG_MAXINT64, /* max */\n0, /* default */",
"ulong", "0, /* min */\nG_MAXULONG, /* max */\n0, /* default */",
"uint", "0, /* min */\nG_MAXUINT, /* max */\n0, /* default */",
"uint8", "0, /* min */\nG_MAXUINT8, /* max */\n0, /* default */",
"ushort", "0, /* min */\nG_MAXUINT16, /* max */\n0, /* default */",
"uchar", "G_MININT8, /* min */\nG_MAXINT8, /* max */\n0, /* default */",
"char", "0, /* min */\nG_MAXUINT8, /* max */\n0, /* default */",
"string", "\"\", /* default */",
"object", "WEBKIT_TYPE_DOM_${ucPropGType}, /* gobject type */");
my $txtInstallProp = << "EOF";
g_object_class_install_property(gobjectClass,
${propEnum},
g_param_spec_${_gtype}("${propName}", /* name */
"$nick", /* short description */
"$long", /* longer - could do with some extra doc stuff here */
$param_spec_options{$gtype}
${gparamflag}));
EOF
push(@txtInstallProps, $txtInstallProp);
}
sub GenerateProperties {
my ($object, $interfaceName, $interface) = @_;
my $decamelize = decamelize($interfaceName);
my $clsCaps = uc($decamelize);
my $lowerCaseIfaceName = "webkit_dom_$decamelize";
my $parentImplClassName = GetParentImplClassName($interface);
my $conditionGuardStart = "";
my $conditionGuardEnd = "";
my $conditionalString = $codeGenerator->GenerateConditionalString($interface);
if ($conditionalString) {
$conditionGuardStart = "#if ${conditionalString}";
$conditionGuardEnd = "#endif // ${conditionalString}";
}
# Properties
my $implContent = "";
my @readableProperties = GetReadableProperties($interface->attributes);
my @writeableProperties = GetWriteableProperties(\@readableProperties);
my $numProperties = scalar @readableProperties;
# Properties
my $privFunction = GetCoreObject($interfaceName, "coreSelf", "self");
if ($numProperties > 0) {
$implContent = << "EOF";
enum {
PROP_0,
EOF
push(@cBodyProperties, $implContent);
my $txtGetProp = << "EOF";
static void ${lowerCaseIfaceName}_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec)
{
WebCore::JSMainThreadNullState state;
EOF
push(@txtGetProps, $txtGetProp);
$txtGetProp = << "EOF";
$conditionGuardStart
${className}* self = WEBKIT_DOM_${clsCaps}(object);
$privFunction
$conditionGuardEnd
EOF
push(@txtGetProps, $txtGetProp);
$txtGetProp = << "EOF";
switch (propertyId) {
EOF
push(@txtGetProps, $txtGetProp);
if (scalar @writeableProperties > 0) {
my $txtSetProps = << "EOF";
static void ${lowerCaseIfaceName}_set_property(GObject* object, guint propertyId, const GValue* value, GParamSpec* pspec)
{
WebCore::JSMainThreadNullState state;
EOF
push(@txtSetProps, $txtSetProps);
$txtSetProps = << "EOF";
$conditionGuardStart
${className}* self = WEBKIT_DOM_${clsCaps}(object);
$privFunction
$conditionGuardEnd
EOF
push(@txtSetProps, $txtSetProps);
$txtSetProps = << "EOF";
switch (propertyId) {
EOF
push(@txtSetProps, $txtSetProps);
}
foreach my $attribute (@readableProperties) {
if ($attribute->signature->type ne "EventListener" &&
$attribute->signature->type ne "MediaQueryListListener") {
GenerateProperty($attribute, $interfaceName, \@writeableProperties, $interface);
}
}
push(@cBodyProperties, "};\n\n");
$txtGetProp = << "EOF";
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
EOF
push(@txtGetProps, $txtGetProp);
if (scalar @writeableProperties > 0) {
$txtSetProps = << "EOF";
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
EOF
push(@txtSetProps, $txtSetProps);
}
}
# Do not insert extra spaces when interpolating array variables
$" = "";
if ($parentImplClassName eq "Object") {
$implContent = << "EOF";
static void ${lowerCaseIfaceName}_finalize(GObject* object)
{
${className}Private* priv = WEBKIT_DOM_${clsCaps}_GET_PRIVATE(object);
$conditionGuardStart
WebKit::DOMObjectCache::forget(priv->coreObject.get());
$conditionGuardEnd
priv->~${className}Private();
G_OBJECT_CLASS(${lowerCaseIfaceName}_parent_class)->finalize(object);
}
EOF
push(@cBodyProperties, $implContent);
}
if ($numProperties > 0) {
if (scalar @writeableProperties > 0) {
push(@cBodyProperties, @txtSetProps);
push(@cBodyProperties, "\n");
}
push(@cBodyProperties, @txtGetProps);
push(@cBodyProperties, "\n");
}
# Add a constructor implementation only for direct subclasses of Object to make sure
# that the WebCore wrapped object is added only once to the DOM cache. The DOM garbage
# collector works because Node is a direct subclass of Object and the version of
# DOMObjectCache::put() that receives a Node (which is the one setting the frame) is
# always called for DOM objects derived from Node.
if ($parentImplClassName eq "Object") {
$implContent = << "EOF";
static GObject* ${lowerCaseIfaceName}_constructor(GType type, guint constructPropertiesCount, GObjectConstructParam* constructProperties)
{
GObject* object = G_OBJECT_CLASS(${lowerCaseIfaceName}_parent_class)->constructor(type, constructPropertiesCount, constructProperties);
$conditionGuardStart
${className}Private* priv = WEBKIT_DOM_${clsCaps}_GET_PRIVATE(object);
priv->coreObject = static_cast<WebCore::${interfaceName}*>(WEBKIT_DOM_OBJECT(object)->coreObject);
WebKit::DOMObjectCache::put(priv->coreObject.get(), object);
$conditionGuardEnd
return object;
}
EOF
push(@cBodyProperties, $implContent);
}
$implContent = << "EOF";
static void ${lowerCaseIfaceName}_class_init(${className}Class* requestClass)
{
EOF
push(@cBodyProperties, $implContent);
if ($parentImplClassName eq "Object" || $numProperties > 0) {
push(@cBodyProperties, " GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass);\n");
if ($parentImplClassName eq "Object") {
push(@cBodyProperties, " g_type_class_add_private(gobjectClass, sizeof(${className}Private));\n");
push(@cBodyProperties, " gobjectClass->constructor = ${lowerCaseIfaceName}_constructor;\n");
push(@cBodyProperties, " gobjectClass->finalize = ${lowerCaseIfaceName}_finalize;\n");
}
if ($numProperties > 0) {
if (scalar @writeableProperties > 0) {
push(@cBodyProperties, " gobjectClass->set_property = ${lowerCaseIfaceName}_set_property;\n");
}
push(@cBodyProperties, " gobjectClass->get_property = ${lowerCaseIfaceName}_get_property;\n");
push(@cBodyProperties, "\n");
push(@cBodyProperties, @txtInstallProps);
}
}
$implContent = << "EOF";
}
static void ${lowerCaseIfaceName}_init(${className}* request)
{
EOF
push(@cBodyProperties, $implContent);
if ($parentImplClassName eq "Object") {
$implContent = << "EOF";
${className}Private* priv = WEBKIT_DOM_${clsCaps}_GET_PRIVATE(request);
new (priv) ${className}Private();
EOF
push(@cBodyProperties, $implContent);
}
$implContent = << "EOF";
}
EOF
push(@cBodyProperties, $implContent);
}
sub GenerateHeader {
my ($object, $interfaceName, $parentClassName) = @_;
my $implContent = "";
# Add the default header template
@hPrefix = split("\r", $licenceTemplate);
push(@hPrefix, "\n");
# Force single header include.
my $headerCheck = << "EOF";
#if !defined(__WEBKITDOM_H_INSIDE__) && !defined(BUILDING_WEBKIT)
#error "Only <webkitdom/webkitdom.h> can be included directly."
#endif
EOF
push(@hPrefix, $headerCheck);
# Header guard
my $guard = $className . "_h";
@hPrefixGuard = << "EOF";
#ifndef $guard
#define $guard
EOF
$implContent = << "EOF";
G_BEGIN_DECLS
EOF
push(@hBodyPre, $implContent);
my $decamelize = decamelize($interfaceName);
my $clsCaps = uc($decamelize);
my $lowerCaseIfaceName = "webkit_dom_$decamelize";
$implContent = << "EOF";
#define WEBKIT_TYPE_DOM_${clsCaps} (${lowerCaseIfaceName}_get_type())
#define WEBKIT_DOM_${clsCaps}(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_DOM_${clsCaps}, ${className}))
#define WEBKIT_DOM_${clsCaps}_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_DOM_${clsCaps}, ${className}Class)
#define WEBKIT_DOM_IS_${clsCaps}(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_DOM_${clsCaps}))
#define WEBKIT_DOM_IS_${clsCaps}_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_DOM_${clsCaps}))
#define WEBKIT_DOM_${clsCaps}_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_DOM_${clsCaps}, ${className}Class))
struct _${className} {
${parentClassName} parent_instance;
};
struct _${className}Class {
${parentClassName}Class parent_class;
};
WEBKIT_API GType
${lowerCaseIfaceName}_get_type (void);
EOF
push(@hBody, $implContent);
}
sub GetGReturnMacro {
my ($paramName, $paramIDLType, $returnType, $functionName) = @_;
my $condition;
if ($paramIDLType eq "GError") {
$condition = "!$paramName || !*$paramName";
} elsif (IsGDOMClassType($paramIDLType)) {
my $paramTypeCaps = uc(decamelize($paramIDLType));
$condition = "WEBKIT_DOM_IS_${paramTypeCaps}($paramName)";
if (ParamCanBeNull($functionName, $paramName)) {
$condition = "!$paramName || $condition";
}
} else {
if (ParamCanBeNull($functionName, $paramName)) {
return;
}
$condition = "$paramName";
}
my $macro;
if ($returnType ne "void") {
$defaultReturn = $returnType eq "gboolean" ? "FALSE" : 0;
$macro = " g_return_val_if_fail($condition, $defaultReturn);\n";
} else {
$macro = " g_return_if_fail($condition);\n";
}
return $macro;
}
sub ParamCanBeNull {
my($functionName, $paramName) = @_;
if (defined($functionName)) {
return scalar(grep(/$paramName/, @{$canBeNullParams->{$functionName}}));
}
return 0;
}
sub GenerateFunction {
my ($object, $interfaceName, $function, $prefix, $parentNode) = @_;
my $decamelize = decamelize($interfaceName);
if ($object eq "MediaQueryListListener") {
return;
}
if (SkipFunction($function, $decamelize, $prefix)) {
return;
}
return if ($function->signature->name eq "set" and $parentNode->extendedAttributes->{"TypedArray"});
my $functionSigType = $prefix eq "set_" ? "void" : $function->signature->type;
my $functionName = "webkit_dom_" . $decamelize . "_" . $prefix . decamelize($function->signature->name);
my $returnType = GetGlibTypeName($functionSigType);
my $returnValueIsGDOMType = IsGDOMClassType($functionSigType);
my $raisesException = $function->signature->extendedAttributes->{"RaisesException"};
my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
my $parentConditionalString = $codeGenerator->GenerateConditionalString($parentNode);
my @conditionalWarn = GenerateConditionalWarning($function->signature);
my @parentConditionalWarn = GenerateConditionalWarning($parentNode);
my $functionSig = "${className}* self";
my @callImplParams;
foreach my $param (@{$function->parameters}) {
my $paramIDLType = $param->type;
if ($paramIDLType eq "EventListener" || $paramIDLType eq "MediaQueryListListener") {
# EventListeners are handled elsewhere.
return;
}
my $paramType = GetGlibTypeName($paramIDLType);
my $const = $paramType eq "gchar*" ? "const " : "";
my $paramName = $param->name;
$functionSig .= ", ${const}$paramType $paramName";
my $paramIsGDOMType = IsGDOMClassType($paramIDLType);
if ($paramIsGDOMType) {
if ($paramIDLType ne "any") {
$implIncludes{"WebKitDOM${paramIDLType}Private.h"} = 1;
}
}
if ($paramIsGDOMType || ($paramIDLType eq "DOMString") || ($paramIDLType eq "CompareHow")) {
$paramName = "converted" . $codeGenerator->WK_ucfirst($paramName);
}
push(@callImplParams, $paramName);
}
if ($returnType ne "void" && $returnValueIsGDOMType && $functionSigType ne "any") {
$implIncludes{"WebKitDOM${functionSigType}Private.h"} = 1;
}
$functionSig .= ", GError** error" if $raisesException;
# Insert introspection annotations
push(@hBody, "/**\n");
push(@hBody, " * ${functionName}:\n");
push(@hBody, " * \@self: A #${className}\n");
foreach my $param (@{$function->parameters}) {
my $paramType = GetGlibTypeName($param->type);
# $paramType can have a trailing * in some cases
$paramType =~ s/\*$//;
my $paramName = $param->name;
push(@hBody, " * \@${paramName}: A #${paramType}\n");
}
push(@hBody, " * \@error: #GError\n") if $raisesException;
push(@hBody, " *\n");
if (IsGDOMClassType($function->signature->type)) {
push(@hBody, " * Returns: (transfer none):\n");
} else {
push(@hBody, " * Returns:\n");
}
push(@hBody, " *\n");
push(@hBody, "**/\n");
push(@hBody, "WEBKIT_API $returnType\n$functionName($functionSig);\n");
push(@hBody, "\n");
push(@cBody, "$returnType\n$functionName($functionSig)\n{\n");
push(@cBody, "#if ${parentConditionalString}\n") if $parentConditionalString;
push(@cBody, "#if ${conditionalString}\n") if $conditionalString;
push(@cBody, " WebCore::JSMainThreadNullState state;\n");
# g_return macros to check parameters of public methods.
$gReturnMacro = GetGReturnMacro("self", $interfaceName, $returnType);
push(@cBody, $gReturnMacro);
foreach my $param (@{$function->parameters}) {
my $paramName = $param->name;
my $paramIDLType = $param->type;
my $paramTypeIsPrimitive = $codeGenerator->IsPrimitiveType($paramIDLType);
my $paramIsGDOMType = IsGDOMClassType($paramIDLType);
if (!$paramTypeIsPrimitive) {
$gReturnMacro = GetGReturnMacro($paramName, $paramIDLType, $returnType, $functionName);
push(@cBody, $gReturnMacro);
}
}
if ($raisesException) {
$gReturnMacro = GetGReturnMacro("error", "GError", $returnType);
push(@cBody, $gReturnMacro);
}
# The WebKit::core implementations check for null already; no need to duplicate effort.
push(@cBody, " WebCore::${interfaceName}* item = WebKit::core(self);\n");
$returnParamName = "";
foreach my $param (@{$function->parameters}) {
my $paramIDLType = $param->type;
my $paramName = $param->name;
my $paramIsGDOMType = IsGDOMClassType($paramIDLType);
$convertedParamName = "converted" . $codeGenerator->WK_ucfirst($paramName);
if ($paramIDLType eq "DOMString") {
push(@cBody, " WTF::String ${convertedParamName} = WTF::String::fromUTF8($paramName);\n");
} elsif ($paramIDLType eq "CompareHow") {
push(@cBody, " WebCore::Range::CompareHow ${convertedParamName} = static_cast<WebCore::Range::CompareHow>($paramName);\n");
} elsif ($paramIsGDOMType) {
push(@cBody, " WebCore::${paramIDLType}* ${convertedParamName} = WebKit::core($paramName);\n");
}
$returnParamName = $convertedParamName if $param->extendedAttributes->{"CustomReturn"};
}
my $assign = "";
my $assignPre = "";
my $assignPost = "";
# We need to special-case these Node methods because their C++
# signature is different from what we'd expect given their IDL
# description; see Node.h.
my $functionHasCustomReturn = $functionName eq "webkit_dom_node_append_child" ||
$functionName eq "webkit_dom_node_insert_before" ||
$functionName eq "webkit_dom_node_replace_child" ||
$functionName eq "webkit_dom_node_remove_child";
if ($returnType ne "void" && !$functionHasCustomReturn) {
if ($returnValueIsGDOMType) {
$assign = "RefPtr<WebCore::${functionSigType}> gobjectResult = ";
$assignPre = "WTF::getPtr(";
$assignPost = ")";
} else {
$assign = "${returnType} result = ";
}
}
# FIXME: Should we return a default value when isNull == true?
if ($function->signature->isNullable) {
push(@cBody, " bool isNull = false;\n");
push(@callImplParams, "isNull");
}
if ($raisesException) {
push(@cBody, " WebCore::ExceptionCode ec = 0;\n");
push(@callImplParams, "ec");
}
my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $function->signature->name;
if ($functionHasCustomReturn) {
push(@cBody, " bool ok = item->${functionImplementationName}(" . join(", ", @callImplParams) . ");\n");
my $customNodeAppendChild = << "EOF";
if (ok)
return WebKit::kit($returnParamName);
EOF
push(@cBody, $customNodeAppendChild);
if($raisesException) {
my $exceptionHandling = << "EOF";
WebCore::ExceptionCodeDescription ecdesc(ec);
g_set_error_literal(error, g_quark_from_string("WEBKIT_DOM"), ecdesc.code, ecdesc.name);
EOF
push(@cBody, $exceptionHandling);
}
push(@cBody, " return 0;\n");
push(@cBody, "}\n\n");
return;
} elsif ($functionSigType eq "DOMString") {
my $getterContentHead;
if ($prefix) {
my ($functionName, @arguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $function);
push(@arguments, @callImplParams);
if ($function->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
unshift(@arguments, "item");
$functionName = "WebCore::${implementedBy}::${functionName}";
} else {
$functionName = "item->${functionName}";
}
$getterContentHead = "${assign}convertToUTF8String(${functionName}(" . join(", ", @arguments) . "));\n";
} else {
my @arguments = @callImplParams;
if ($function->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
unshift(@arguments, "item");
$getterContentHead = "${assign}convertToUTF8String(WebCore::${implementedBy}::${functionImplementationName}(" . join(", ", @arguments) . "));\n";
} else {
$getterContentHead = "${assign}convertToUTF8String(item->${functionImplementationName}(" . join(", ", @arguments) . "));\n";
}
}
push(@cBody, " ${getterContentHead}");
} else {
my $contentHead;
if ($prefix eq "get_") {
my ($functionName, @arguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $function);
push(@arguments, @callImplParams);
if ($function->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
unshift(@arguments, "item");
$functionName = "WebCore::${implementedBy}::${functionName}";
} else {
$functionName = "item->${functionName}";
}
$contentHead = "${assign}${assignPre}${functionName}(" . join(", ", @arguments) . "${assignPost});\n";
} elsif ($prefix eq "set_") {
my ($functionName, @arguments) = $codeGenerator->SetterExpression(\%implIncludes, $interfaceName, $function);
push(@arguments, @callImplParams);
if ($function->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
unshift(@arguments, "item");
$functionName = "WebCore::${implementedBy}::${functionName}";
$contentHead = "${assign}${assignPre}${functionName}(" . join(", ", @arguments) . "${assignPost});\n";
} else {
$functionName = "item->${functionName}";
$contentHead = "${assign}${assignPre}${functionName}(" . join(", ", @arguments) . "${assignPost});\n";
}
} else {
my @arguments = @callImplParams;
if ($function->signature->extendedAttributes->{"ImplementedBy"}) {
my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
$implIncludes{"${implementedBy}.h"} = 1;
unshift(@arguments, "item");
$contentHead = "${assign}${assignPre}WebCore::${implementedBy}::${functionImplementationName}(" . join(", ", @arguments) . "${assignPost});\n";
} else {
$contentHead = "${assign}${assignPre}item->${functionImplementationName}(" . join(", ", @arguments) . "${assignPost});\n";
}
}
push(@cBody, " ${contentHead}");
if($raisesException) {
my $exceptionHandling = << "EOF";
if (ec) {
WebCore::ExceptionCodeDescription ecdesc(ec);
g_set_error_literal(error, g_quark_from_string("WEBKIT_DOM"), ecdesc.code, ecdesc.name);
}
EOF
push(@cBody, $exceptionHandling);
}
}
if ($returnType ne "void" && !$functionHasCustomReturn) {
if ($functionSigType ne "any") {
if ($returnValueIsGDOMType) {
push(@cBody, " return WebKit::kit(gobjectResult.get());\n");
} else {
push(@cBody, " return result;\n");
}
} else {
push(@cBody, " return 0; // TODO: return canvas object\n");
}
}
if ($conditionalString) {
push(@cBody, "#else\n");
push(@cBody, @conditionalWarn) if scalar(@conditionalWarn);
if ($returnType ne "void") {
if ($codeGenerator->IsNonPointerType($functionSigType)) {
push(@cBody, " return static_cast<${returnType}>(0);\n");
} else {
push(@cBody, " return 0;\n");
}
}
push(@cBody, "#endif /* ${conditionalString} */\n");
}
if ($parentConditionalString) {
push(@cBody, "#else\n");
push(@cBody, @parentConditionalWarn) if scalar(@parentConditionalWarn);
if ($returnType ne "void") {
if ($codeGenerator->IsNonPointerType($functionSigType)) {
push(@cBody, " return static_cast<${returnType}>(0);\n");
} else {
push(@cBody, " return 0;\n");
}
}
push(@cBody, "#endif /* ${parentConditionalString} */\n");
}
push(@cBody, "}\n\n");
}
sub ClassHasFunction {
my ($class, $name) = @_;
foreach my $function (@{$class->functions}) {
if ($function->signature->name eq $name) {
return 1;
}
}
return 0;
}
sub GenerateFunctions {
my ($object, $interfaceName, $interface) = @_;
foreach my $function (@{$interface->functions}) {
$object->GenerateFunction($interfaceName, $function, "", $interface);
}
TOP:
foreach my $attribute (@{$interface->attributes}) {
if (SkipAttribute($attribute) ||
$attribute->signature->type eq "EventListener" ||
$attribute->signature->type eq "MediaQueryListListener") {
next TOP;
}
if ($attribute->signature->name eq "type"
# This will conflict with the get_type() function we define to return a GType
# according to GObject conventions. Skip this for now.
|| $attribute->signature->name eq "URL" # TODO: handle this
) {
next TOP;
}
my $attrNameUpper = $codeGenerator->WK_ucfirst($attribute->signature->name);
my $getname = "get${attrNameUpper}";
my $setname = "set${attrNameUpper}";
if (ClassHasFunction($interface, $getname) || ClassHasFunction($interface, $setname)) {
# Very occasionally an IDL file defines getter/setter functions for one of its
# attributes; in this case we don't need to autogenerate the getter/setter.
next TOP;
}
# Generate an attribute getter. For an attribute "foo", this is a function named
# "get_foo" which calls a DOM class method named foo().
my $function = new domFunction();
$function->signature($attribute->signature);
$function->signature->extendedAttributes({%{$attribute->signature->extendedAttributes}});
if ($attribute->signature->extendedAttributes->{"GetterRaisesException"}) {
$function->signature->extendedAttributes->{"RaisesException"} = "VALUE_IS_MISSING";
}
$object->GenerateFunction($interfaceName, $function, "get_", $interface);
# FIXME: We are not generating setters for 'Replaceable'
# attributes now, but we should somehow.
if ($attribute->isReadOnly || $attribute->signature->extendedAttributes->{"Replaceable"}) {
next TOP;
}
# Generate an attribute setter. For an attribute, "foo", this is a function named
# "set_foo" which calls a DOM class method named setFoo().
$function = new domFunction();
$function->signature(new domSignature());
$function->signature->name($attribute->signature->name);
$function->signature->type($attribute->signature->type);
$function->signature->extendedAttributes({%{$attribute->signature->extendedAttributes}});
my $param = new domSignature();
$param->name("value");
$param->type($attribute->signature->type);
my %attributes = ();
$param->extendedAttributes(\%attributes);
my $arrayRef = $function->parameters;
push(@$arrayRef, $param);
if ($attribute->signature->extendedAttributes->{"SetterRaisesException"}) {
$function->signature->extendedAttributes->{"RaisesException"} = "VALUE_IS_MISSING";
} else {
delete $function->signature->extendedAttributes->{"RaisesException"};
}
$object->GenerateFunction($interfaceName, $function, "set_", $interface);
}
}
sub GenerateCFile {
my ($object, $interfaceName, $parentClassName, $parentGObjType, $interface) = @_;
if ($interface->extendedAttributes->{"EventTarget"}) {
$object->GenerateEventTargetIface($interface);
}
my $implContent = "";
my $decamelize = decamelize($interfaceName);
my $clsCaps = uc($decamelize);
my $lowerCaseIfaceName = "webkit_dom_$decamelize";
my $parentImplClassName = GetParentImplClassName($interface);
my $baseClassName = GetBaseClass($parentImplClassName);
# Add a private struct only for direct subclasses of Object so that we can use RefPtr
# for the WebCore wrapped object and make sure we only increment the reference counter once.
if ($parentImplClassName eq "Object") {
my $conditionalString = $codeGenerator->GenerateConditionalString($interface);
push(@cStructPriv, "#define WEBKIT_DOM_${clsCaps}_GET_PRIVATE(obj) G_TYPE_INSTANCE_GET_PRIVATE(obj, WEBKIT_TYPE_DOM_${clsCaps}, ${className}Private)\n\n");
push(@cStructPriv, "typedef struct _${className}Private {\n");
push(@cStructPriv, "#if ${conditionalString}\n") if $conditionalString;
push(@cStructPriv, " RefPtr<WebCore::${interfaceName}> coreObject;\n");
push(@cStructPriv, "#endif // ${conditionalString}\n") if $conditionalString;
push(@cStructPriv, "} ${className}Private;\n\n");
}
$implContent = << "EOF";
${defineTypeMacro}(${className}, ${lowerCaseIfaceName}, ${parentGObjType}${defineTypeInterfaceImplementation}
EOF
push(@cBodyProperties, $implContent);
if ($parentImplClassName eq "Object") {
push(@cBodyPriv, "${className}* kit(WebCore::$interfaceName* obj)\n");
push(@cBodyPriv, "{\n");
push(@cBodyPriv, " if (!obj)\n");
push(@cBodyPriv, " return 0;\n\n");
push(@cBodyPriv, " if (gpointer ret = DOMObjectCache::get(obj))\n");
push(@cBodyPriv, " return WEBKIT_DOM_${clsCaps}(ret);\n\n");
if (IsPolymorphic($interfaceName)) {
push(@cBodyPriv, " return wrap(obj);\n");
} else {
push(@cBodyPriv, " return wrap${interfaceName}(obj);\n");
}
push(@cBodyPriv, "}\n\n");
} else {
push(@cBodyPriv, "${className}* kit(WebCore::$interfaceName* obj)\n");
push(@cBodyPriv, "{\n");
if (!IsPolymorphic($baseClassName)) {
push(@cBodyPriv, " if (!obj)\n");
push(@cBodyPriv, " return 0;\n\n");
push(@cBodyPriv, " if (gpointer ret = DOMObjectCache::get(obj))\n");
push(@cBodyPriv, " return WEBKIT_DOM_${clsCaps}(ret);\n\n");
push(@cBodyPriv, " return wrap${interfaceName}(obj);\n");
} else {
push(@cBodyPriv, " return WEBKIT_DOM_${clsCaps}(kit(static_cast<WebCore::$baseClassName*>(obj)));\n");
}
push(@cBodyPriv, "}\n\n");
}
$implContent = << "EOF";
WebCore::${interfaceName}* core(${className}* request)
{
return request ? static_cast<WebCore::${interfaceName}*>(WEBKIT_DOM_OBJECT(request)->coreObject) : 0;
}
${className}* wrap${interfaceName}(WebCore::${interfaceName}* coreObject)
{
ASSERT(coreObject);
return WEBKIT_DOM_${clsCaps}(g_object_new(WEBKIT_TYPE_DOM_${clsCaps}, "core-object", coreObject, NULL));
}
EOF
push(@cBodyPriv, $implContent);
$object->GenerateProperties($interfaceName, $interface);
$object->GenerateFunctions($interfaceName, $interface);
}
sub GenerateEndHeader {
my ($object) = @_;
#Header guard
my $guard = $className . "_h";
push(@hBody, "G_END_DECLS\n\n");
push(@hPrefixGuardEnd, "#endif /* $guard */\n");
}
sub IsPolymorphic {
my $type = shift;
return scalar(grep {$_ eq $type} qw(Blob Event HTMLCollection Node StyleSheet));
}
sub GenerateEventTargetIface {
my $object = shift;
my $interface = shift;
my $interfaceName = $interface->name;
my $decamelize = decamelize($interfaceName);
my $conditionalString = $codeGenerator->GenerateConditionalString($interface);
my @conditionalWarn = GenerateConditionalWarning($interface);
$implIncludes{"GObjectEventListener.h"} = 1;
$implIncludes{"WebKitDOMEventTarget.h"} = 1;
$implIncludes{"WebKitDOMEventPrivate.h"} = 1;
push(@cBodyProperties, "static void webkit_dom_${decamelize}_dispatch_event(WebKitDOMEventTarget* target, WebKitDOMEvent* event, GError** error)\n{\n");
push(@cBodyProperties, "#if ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, " WebCore::Event* coreEvent = WebKit::core(event);\n");
push(@cBodyProperties, " WebCore::${interfaceName}* coreTarget = static_cast<WebCore::${interfaceName}*>(WEBKIT_DOM_OBJECT(target)->coreObject);\n\n");
push(@cBodyProperties, " WebCore::ExceptionCode ec = 0;\n");
push(@cBodyProperties, " coreTarget->dispatchEvent(coreEvent, ec);\n");
push(@cBodyProperties, " if (ec) {\n WebCore::ExceptionCodeDescription description(ec);\n");
push(@cBodyProperties, " g_set_error_literal(error, g_quark_from_string(\"WEBKIT_DOM\"), description.code, description.name);\n }\n");
push(@cBodyProperties, "#else\n") if $conditionalString;
push(@cBodyProperties, @conditionalWarn) if scalar(@conditionalWarn);
push(@cBodyProperties, "#endif // ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, "}\n\n");
push(@cBodyProperties, "static gboolean webkit_dom_${decamelize}_add_event_listener(WebKitDOMEventTarget* target, const char* eventName, GCallback handler, gboolean bubble, gpointer userData)\n{\n");
push(@cBodyProperties, "#if ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, " WebCore::${interfaceName}* coreTarget = static_cast<WebCore::${interfaceName}*>(WEBKIT_DOM_OBJECT(target)->coreObject);\n");
push(@cBodyProperties, " return WebCore::GObjectEventListener::addEventListener(G_OBJECT(target), coreTarget, eventName, handler, bubble, userData);\n");
push(@cBodyProperties, "#else\n") if $conditionalString;
push(@cBodyProperties, @conditionalWarn) if scalar(@conditionalWarn);
push(@cBodyProperties, " return false;\n#endif // ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, "}\n\n");
push(@cBodyProperties, "static gboolean webkit_dom_${decamelize}_remove_event_listener(WebKitDOMEventTarget* target, const char* eventName, GCallback handler, gboolean bubble)\n{\n");
push(@cBodyProperties, "#if ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, " WebCore::${interfaceName}* coreTarget = static_cast<WebCore::${interfaceName}*>(WEBKIT_DOM_OBJECT(target)->coreObject);\n");
push(@cBodyProperties, " return WebCore::GObjectEventListener::removeEventListener(G_OBJECT(target), coreTarget, eventName, handler, bubble);\n");
push(@cBodyProperties, "#else\n") if $conditionalString;
push(@cBodyProperties, @conditionalWarn) if scalar(@conditionalWarn);
push(@cBodyProperties, " return false;\n#endif // ${conditionalString}\n") if $conditionalString;
push(@cBodyProperties, "}\n\n");
push(@cBodyProperties, "static void webkit_dom_event_target_init(WebKitDOMEventTargetIface* iface)\n{\n");
push(@cBodyProperties, " iface->dispatch_event = webkit_dom_${decamelize}_dispatch_event;\n");
push(@cBodyProperties, " iface->add_event_listener = webkit_dom_${decamelize}_add_event_listener;\n");
push(@cBodyProperties, " iface->remove_event_listener = webkit_dom_${decamelize}_remove_event_listener;\n}\n\n");
$defineTypeMacro = "G_DEFINE_TYPE_WITH_CODE";
$defineTypeInterfaceImplementation = ", G_IMPLEMENT_INTERFACE(WEBKIT_TYPE_DOM_EVENT_TARGET, webkit_dom_event_target_init))";
}
sub Generate {
my ($object, $interface) = @_;
my $parentClassName = GetParentClassName($interface);
my $parentGObjType = GetParentGObjType($interface);
my $interfaceName = $interface->name;
my $parentImplClassName = GetParentImplClassName($interface);
my $baseClassName = GetBaseClass($parentImplClassName);
# Add the default impl header template
@cPrefix = split("\r", $licenceTemplate);
push(@cPrefix, "\n");
$implIncludes{"DOMObjectCache.h"} = 1;
$implIncludes{"WebKitDOMPrivate.h"} = 1;
$implIncludes{"gobject/ConvertToUTF8String.h"} = 1;
$implIncludes{"${className}Private.h"} = 1;
$implIncludes{"JSMainThreadExecState.h"} = 1;
$implIncludes{"ExceptionCode.h"} = 1;
$implIncludes{"CSSImportRule.h"} = 1;
if ($parentImplClassName ne "Object" and IsPolymorphic($baseClassName)) {
$implIncludes{"WebKitDOM${baseClassName}Private.h"} = 1;
}
$hdrIncludes{"webkitdom/${parentClassName}.h"} = 1;
$object->GenerateHeader($interfaceName, $parentClassName);
$object->GenerateCFile($interfaceName, $parentClassName, $parentGObjType, $interface);
$object->GenerateEndHeader();
}
sub WriteData {
my $object = shift;
my $interface = shift;
my $outputDir = shift;
mkdir $outputDir;
# Write a private header.
my $interfaceName = $interface->name;
my $filename = "$outputDir/" . $className . "Private.h";
my $guard = "${className}Private_h";
# Add the guard if the 'Conditional' extended attribute exists
my $conditionalString = $codeGenerator->GenerateConditionalString($interface);
open(PRIVHEADER, ">$filename") or die "Couldn't open file $filename for writing";
print PRIVHEADER split("\r", $licenceTemplate);
print PRIVHEADER "\n";
my $text = << "EOF";
#ifndef $guard
#define $guard
#include "${interfaceName}.h"
#include <webkitdom/${className}.h>
EOF
print PRIVHEADER $text;
print PRIVHEADER "#if ${conditionalString}\n" if $conditionalString;
print PRIVHEADER map { "#include \"$_\"\n" } sort keys(%hdrPropIncludes);
print PRIVHEADER "\n";
$text = << "EOF";
namespace WebKit {
${className}* wrap${interfaceName}(WebCore::${interfaceName}*);
${className}* kit(WebCore::${interfaceName}*);
WebCore::${interfaceName}* core(${className}*);
EOF
print PRIVHEADER $text;
$text = << "EOF";
} // namespace WebKit
EOF
print PRIVHEADER $text;
print PRIVHEADER "#endif /* ${conditionalString} */\n\n" if $conditionalString;
print PRIVHEADER "#endif /* ${guard} */\n";
close(PRIVHEADER);
my $basename = FileNamePrefix . $interfaceName;
$basename =~ s/_//g;
# Write public header.
my $fullHeaderFilename = "$outputDir/" . $basename . ".h";
my $installedHeaderFilename = "${basename}.h";
open(HEADER, ">$fullHeaderFilename") or die "Couldn't open file $fullHeaderFilename";
print HEADER @hPrefix;
print HEADER @hPrefixGuard;
print HEADER "#include <glib-object.h>\n";
print HEADER map { "#include <$_>\n" } sort keys(%hdrIncludes);
print HEADER "#include <webkitdom/webkitdomdefines.h>\n\n";
print HEADER @hBodyPre;
print HEADER @hBody;
print HEADER @hPrefixGuardEnd;
close(HEADER);
# Write the implementation sources
my $implFileName = "$outputDir/" . $basename . ".cpp";
open(IMPL, ">$implFileName") or die "Couldn't open file $implFileName";
print IMPL @cPrefix;
print IMPL "#include \"config.h\"\n";
print IMPL "#include \"$installedHeaderFilename\"\n\n";
# Remove the implementation header from the list of included files.
%includesCopy = %implIncludes;
print IMPL map { "#include \"$_\"\n" } sort keys(%includesCopy);
print IMPL "#include <wtf/GetPtr.h>\n";
print IMPL "#include <wtf/RefPtr.h>\n\n";
print IMPL @cStructPriv;
print IMPL "#if ${conditionalString}\n\n" if $conditionalString;
print IMPL "namespace WebKit {\n\n";
print IMPL @cBodyPriv;
print IMPL "} // namespace WebKit\n\n";
print IMPL "#endif // ${conditionalString}\n\n" if $conditionalString;
print IMPL @cBodyProperties;
print IMPL @cBody;
close(IMPL);
%implIncludes = ();
%hdrIncludes = ();
@hPrefix = ();
@hBody = ();
@cPrefix = ();
@cBody = ();
@cBodyPriv = ();
@cBodyProperties = ();
@cStructPriv = ();
}
sub GenerateInterface {
my ($object, $interface, $defines) = @_;
# Set up some global variables
$className = GetClassName($interface->name);
$object->Generate($interface);
}
1;
| shinate/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/scripts/CodeGeneratorGObject.pm | Perl | bsd-3-clause | 61,061 |
use Win32::OLE 'in';
use Win32::OLE::Const 'Microsoft WMI Scripting ';
my $ComputerName = ".";
my $NameSpace = "root/cimv2";
my $ClassName = "Win32_Share";
my $WbemServices = Win32::OLE->GetObject("winmgmts://$ComputerName/$NameSpace");
my $Share = $WbemServices->Get($ClassName,wbemFlagUseAmendedQualifiers);
my $Methods=$Share->Methods_;
my %CreateReturnValues=maakHash_method_qualifier($Methods->Item("Create"));
#direct methode
$ReturnValue=$Share->Create( 'C:\examen',"Directexs share",0);
print $CreateReturnValues{$ReturnValue};
#formele methode
my $InParameters = $Methods->Item("Create")->InParameters;
$InParameters->{Description} = "New Share Description";
$InParameters->{Name} = "New bis Name";
$InParameters->{Path} = 'C:\DELL';
$InParameters->{Type} = 0;
$IntRc=$Share->ExecMethod_("Create", $InParameters);
print $CreateReturnValues{$IntRc->{ReturnValue}};
sub maakHash_method_qualifier{
my $Method=shift;
my %hash=();
@hash{@{$Method->Qualifiers_(ValueMap)->{Value}}}
=@{$Method->Qualifiers_(Values)->{Value}};
return %hash;
}
| VDBBjorn/Besturingssystemen-III | Labo/reeks4/Reeks4_46.pl | Perl | mit | 1,077 |
#
# $Header: svn://svn/SWM/trunk/web/Seasons.pm 11617 2014-05-20 05:57:52Z sliu $
#
package Seasons;
require Exporter;
@ISA = qw(Exporter);
@EXPORT=qw(handleSeasons insertMemberSeasonRecord memberSeasonDuplicateResolution viewDefaultAssocSeasons getDefaultAssocSeasons syncAllowSeasons checkForMemberSeasonRecord seasonRollver isMemberInSeason);
@EXPORT_OK=qw(handleSeasons insertMemberSeasonRecord memberSeasonDuplicateResolution viewDefaultAssocSeasons getDefaultAssocSeasons syncAllowSeasons checkForMemberSeasonRecord seasonRollver isMemberInSeason);
use lib ".","..","comp";
use strict;
use Reg_common;
use Utils;
use HTMLForm;
use AuditLog;
use CGI qw(unescape param);
use FormHelpers;
use MemberPackages;
use GenAgeGroup;
use GridDisplay;
require AgeGroups;
require Transactions;
sub handleSeasons {
my ($action, $Data)=@_;
my $seasonID = param('seasonID') || 0;
my $memberSeasonID = param('msID') || 0;
my $resultHTML = '';
my $title = '';
if($action eq 'SN_L_U') {
$resultHTML = setDefaultAssocSeasonConfig($Data);
}
if ($action =~/^SN_DT/) {
#Season Details
($resultHTML,$title)=season_details($action, $Data, $seasonID);
}
elsif ($action =~/^SN_L/) {
#List Seasons
my $tempResultHTML = '';
($tempResultHTML,$title)=listSeasons($Data);
$resultHTML .= $tempResultHTML;
}
elsif ($action =~/^SN_MSview/) {
#List Seasons
($resultHTML,$title)=memberSeason_details($Data, $memberSeasonID, $action);
}
return ($resultHTML,$title);
}
sub checkMSRecordExistance {
my ($Data, $seasonID, $memberID) = @_;
my $MStablename = "tblMember_Seasons_$Data->{'Realm'}";
my $st = qq[
SELECT
COUNT(*) as MSCount
FROM
$MStablename
WHERE
intMSRecStatus=1
AND intAssocID = $Data->{'clientValues'}{'assocID'}
AND intClubID=0
AND intSeasonID=$seasonID
AND intMemberID = $memberID
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my $count = $query->fetchrow_array() || 0;
if (! $count) {
insertMemberSeasonRecord($Data, $memberID, $seasonID, $Data->{'clientValues'}{'assocID'}, 0, 0, undef());
}
}
sub checkForMemberSeasonRecord {
my ($Data, $compID, $teamID, $memberID) = @_;
$compID ||= 0;
$teamID ||= 0;
$memberID ||= 0;
## In List.pm, if logged in as a TEAM, you can roll all players INTO a Comp using the green tick.
## When this happens, we will set the Data variable so the below works
# ## Check List.pm line
return '' if (! $Data->{'memberListIntoComp'});
$Data->{'memberListIntoComp'}=0; ## Reset it back. USE THIS LINE AS WELL.
my $st = qq[
SELECT intNewSeasonID
FROM tblAssoc_Comp
WHERE intAssocID = $Data->{'clientValues'}{'assocID'} AND intCompID = $compID
];
my $q=$Data->{'db'}->prepare($st);
$q->execute();
my($seasonID)=$q->fetchrow_array() || 0;
$st = qq[
SELECT T.intClubID
FROM tblTeam as T
INNER JOIN tblMember_Clubs as MC ON (MC.intMemberID = ? AND MC.intClubID = T.intClubID AND MC.intStatus = $Defs::RECSTATUS_ACTIVE)
WHERE T.intTeamID = $teamID
];
my $qClub=$Data->{'db'}->prepare($st);
my $assocSeasons = getDefaultAssocSeasons($Data);
$seasonID ||= $assocSeasons->{'currentSeasonID'};
my %types = ();
if (!$types{'intPlayerStatus'} and !$types{'intCoachStatus'} and !$types{'intUmpireStatus'} and !$types{'intOfficialStatus'}
and !$types{'intMiscStatus'} and !$types{'intVolunteerStatus'} and !$types{'intOther1Status'} and !$types{'intOther2Status'}) {
$types{'intPlayerStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_PLAYER);
$types{'intCoachStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_COACH);
$types{'intUmpireStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_UMPIRE);
$types{'intOfficialStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_OFFICIAL);
$types{'intMiscStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_MISC);
$types{'intVolunteerStatus'} = 1 if ($assocSeasons->{'defaultMemberType'} == $Defs::MEMBER_TYPE_VOLUNTEER);
}
$types{'intMSRecStatus'} = 1;
my $genAgeGroup ||=new GenAgeGroup ($Data->{'db'},$Data->{'Realm'}, $Data->{'RealmSubType'}, $Data->{'clientValues'}{'assocID'});
if ($memberID) {
my $st_member = qq[
SELECT DATE_FORMAT(dtDOB, "%Y%m%d") as DOBAgeGroup, intGender
FROM tblMember
WHERE intMemberID = $memberID
];
my $qry_member=$Data->{'db'}->prepare($st_member);
$qry_member->execute();
my ($DOBAgeGroup, $Gender)=$qry_member->fetchrow_array();
my $ageGroupID=$genAgeGroup->getAgeGroup($Gender, $DOBAgeGroup) || 0;
## FOR A SINGLE MEMBER IN TEAM
insertMemberSeasonRecord($Data, $memberID, $seasonID, $Data->{'clientValues'}{'assocID'}, 0, $ageGroupID, \%types);
insertMemberSeasonRecord($Data, $memberID, $assocSeasons->{'newRegoSeasonID'}, $Data->{'clientValues'}{'assocID'}, 0, $ageGroupID, \%types) if (! $assocSeasons->{'allowSeasons'});
$qClub->execute($memberID);
my($clubID)=$qClub->fetchrow_array() || 0;
$clubID = 0 if ($clubID == $Defs::INVALID_ID);
### INSERT SEASON CLUB RECORD IF MEMBER_CLUB RECORD EXISTS
insertMemberSeasonRecord($Data, $memberID, $seasonID, $Data->{'clientValues'}{'assocID'}, $clubID, $ageGroupID, \%types) if $clubID;
insertMemberSeasonRecord($Data, $memberID, $assocSeasons->{'newRegoSeasonID'}, $Data->{'clientValues'}{'assocID'}, $clubID, $ageGroupID, \%types) if ($clubID and ! $assocSeasons->{'allowSeasons'});
}
else {
## FOR A ENTIRE TEAM
$st = qq[
SELECT MT.intMemberID, DATE_FORMAT(M.dtDOB, "%Y%m%d") as DOBAgeGroup, intGender
FROM tblMember_Teams as MT
INNER JOIN tblMember as M ON (M.intMemberID = MT.intMemberID AND M.intStatus <> $Defs::RECSTATUS_DELETED)
WHERE MT.intTeamID = $teamID AND MT.intCompID = $compID AND MT.intStatus = $Defs::RECSTATUS_ACTIVE
];
my $q=$Data->{'db'}->prepare($st);
$q->execute();
while (my ($memberID, $DOBAgeGroup, $Gender)=$q->fetchrow_array()) {
my $ageGroupID=$genAgeGroup->getAgeGroup($Gender, $DOBAgeGroup) || 0;
insertMemberSeasonRecord($Data, $memberID, $seasonID, $Data->{'clientValues'}{'assocID'}, 0, $ageGroupID, \%types);
insertMemberSeasonRecord($Data, $memberID, $assocSeasons->{'newRegoSeasonID'}, $Data->{'clientValues'}{'assocID'}, 0, $ageGroupID, \%types) if ! $assocSeasons->{'allowSeasons'};
$qClub->execute($memberID);
my($clubID)=$qClub->fetchrow_array() || 0;
$clubID = 0 if ($clubID == $Defs::INVALID_ID);
### INSERT SEASON CLUB RECORD IF MEMBER_CLUB RECORD EXISTS
insertMemberSeasonRecord($Data, $memberID, $seasonID, $Data->{'clientValues'}{'assocID'}, $clubID, $ageGroupID, \%types) if $clubID;
insertMemberSeasonRecord($Data, $memberID, $assocSeasons->{'newRegoSeasonID'}, $Data->{'clientValues'}{'assocID'}, $clubID, $ageGroupID, \%types) if ($clubID and ! $assocSeasons->{'allowSeasons'});
}
}
}
sub syncAllowSeasons {
my ($db, $intAssocID, $SWC_AppVer) = @_;
$intAssocID || return;
$SWC_AppVer || return;
if ($SWC_AppVer =~ /^7/) {
$db->do(qq[UPDATE tblAssoc SET intAllowSeasons=1 WHERE intAssocID=$intAssocID]);
}
}
sub memberSeason_details {
my($Data, $memberSeasonID, $action) = @_;
my $txt_Name = $Data->{'SystemConfig'}{'txtSeason'} || 'Season';
my $txt_Names = $Data->{'SystemConfig'}{'txtSeasons'} || 'Seasons';
my $txt_AgeGroupName = $Data->{'SystemConfig'}{'txtAgeGroup'} || 'Age Group';
my $txt_AgeGroupsNames = $Data->{'SystemConfig'}{'txtAgeGroups'} || 'Age Groups';
my $tablename = "tblMember_Seasons_$Data->{'Realm'}";
my $db=$Data->{'db'} || undef;
my $client = setClient($Data->{'clientValues'}) || '';
my $target = $Data->{'target'} || '';
my $option = ($action =~ /EDIT$/) ? 'edit' : 'display';
$option = 'add' if $action =~ /ADD$/;# and allowedAction($Data, 'sn_a');
my $subType = $Data->{'RealmSubType'} || 0;
my $resultHTML = '';
my %DataVals=();
my $strWhere = '';
$strWhere .= qq[ AND MS.intSeasonID = ] . param("d_intSeasonID") if param("d_intSeasonID");
$strWhere .= param("d_intClubID") ? qq[ AND MS.intClubID = ] . param("d_intClubID") : qq[ AND MS.intClubID=0];
$strWhere = qq[ AND MS.intMemberSeasonID = $memberSeasonID] if ($memberSeasonID);
if (! param("d_intSeasonID") and ! $memberSeasonID) {
$strWhere = qq[ AND MS.intMemberSeasonID = 0];
}
my $statement=qq[
SELECT
MS.*,
S.strSeasonName,
C.strName as ClubName,
DATE_FORMAT(MS.dtInPlayer, "%d-%M-%Y") as DateInPlayer,
DATE_FORMAT(MS.dtInCoach, "%d-%M-%Y") as DateInCoach,
DATE_FORMAT(MS.dtInUmpire, "%d-%M-%Y") as DateInUmpire,
DATE_FORMAT(MS.dtInOfficial, "%d-%M-%Y") as DateInOfficial,
DATE_FORMAT(MS.dtInMisc, "%d-%M-%Y") as DateInMisc,
DATE_FORMAT(MS.dtInVolunteer, "%d-%M-%Y") as DateInVolunteer,
DATE_FORMAT(MS.dtInOther1, "%d-%M-%Y") as DateInOther1,
DATE_FORMAT(MS.dtInOther2, "%d-%M-%Y") as DateInOther2
FROM
$tablename as MS
INNER JOIN tblSeasons as S ON (S.intSeasonID = MS.intSeasonID)
LEFT JOIN tblClub as C ON (C.intClubID = MS.intClubID)
WHERE
MS.intAssocID = $Data->{'clientValues'}{'assocID'}
AND MS.intMemberID = $Data->{'clientValues'}{'memberID'}
$strWhere
];
my $query = $db->prepare($statement);
my $RecordData={};
$query->execute();
my $dref=$query->fetchrow_hashref();
$memberSeasonID = $dref->{intMemberSeasonID} if ! $memberSeasonID and $dref->{intMemberSeasonID};
if ($memberSeasonID and $action =~ /ADD/) {
$option = 'edit';
$action =~ s/ADD/EDIT/;
}
if (param('d_intSeasonID') and $action =~ /ADD/) {
$dref->{intSeasonID} = param('d_intSeasonID') || 0;
my $genAgeGroup ||=new GenAgeGroup ($Data->{'db'},$Data->{'Realm'}, $Data->{'RealmSubType'}, $Data->{'clientValues'}{'assocID'});
my $st = qq[
SELECT intGender, DATE_FORMAT(dtDOB, "%Y%m%d") as DOBAgeGroup
FROM tblMember
WHERE intMemberID = $Data->{'clientValues'}{'memberID'}
];
my $query = $db->prepare($st);
$query->execute();
my ($Gender, $DOBAgeGroup) = $query->fetchrow_array();
my $ageGroupID=$genAgeGroup->getAgeGroup ($Gender, $DOBAgeGroup) || 0;
$dref->{intPlayerAgeGroupID} = $ageGroupID || 0;
}
my $msupdate = qq[
UPDATE $tablename
SET
--VAL--,
dtInPlayer = IF(intPlayerStatus = 1 and (dtInPlayer IS NULL or dtInPlayer = '0000-00-00'), CURDATE(), dtInPlayer),
dtInCoach = IF(intCoachStatus = 1 and (dtInCoach IS NULL or dtInCoach = '0000-00-00'), CURDATE(), dtInCoach),
dtInUmpire = IF(intUmpireStatus = 1 and (dtInUmpire IS NULL or dtInUmpire = '0000-00-00'), CURDATE(), dtInUmpire),
dtInOfficial = IF(intOfficialStatus = 1 and (dtInOfficial IS NULL or dtInOfficial = '0000-00-00'), CURDATE(), dtInOfficial),
dtInMisc = IF(intMiscStatus = 1 and (dtInMisc IS NULL or dtInMisc = '0000-00-00'), CURDATE(), dtInMisc),
dtInVolunteer = IF(intVolunteerStatus = 1 and (dtInVolunteer IS NULL or dtInVolunteer = '0000-00-00'), CURDATE(), dtInVolunteer),
dtInOther1 = IF(intOther1Status = 1 and (dtInOther1 IS NULL or dtInOther1 = '0000-00-00'), CURDATE(), dtInOther1),
dtInOther2 = IF(intOther2Status = 1 and (dtInOther2 IS NULL or dtInOther2 = '0000-00-00'), CURDATE(), dtInOther2)
WHERE
intMemberSeasonID = $memberSeasonID
AND intAssocID = $Data->{'clientValues'}{'assocID'}
AND intMemberID = $Data->{'clientValues'}{'memberID'}
];
my $msadd = qq[
INSERT IGNORE INTO $tablename (
intAssocID,
intMemberID,
dtInPlayer,
dtInCoach,
dtInUmpire,
dtInOfficial,
dtInMisc,
dtInVolunteer,
dtInOther1,
dtInOther2,
--FIELDS--
)
VALUES (
$Data->{'clientValues'}{'assocID'},
$Data->{'clientValues'}{'memberID'},
IF(intPlayerStatus = 1, CURDATE(), NULL),
IF(intCoachStatus = 1, CURDATE(), NULL),
IF(intUmpireStatus = 1, CURDATE(), NULL),
IF(intOfficialStatus = 1, CURDATE(), NULL),
IF(intMiscStatus = 1, CURDATE(), NULL),
IF(intVolunteerStatus = 1, CURDATE(), NULL),
IF(intOther1Status = 1, CURDATE(), NULL),
IF(intOther2Status = 1, CURDATE(), NULL),
--VAL--
)
];
my $st_seasons=qq[
SELECT intSeasonID, strSeasonName
FROM tblSeasons
WHERE intRealmID = $Data->{'Realm'}
AND (intAssocID=$Data->{'clientValues'}{'assocID'} OR intAssocID =0)
AND (intRealmSubTypeID = $subType OR intRealmSubTypeID= 0)
AND intArchiveSeason <> 1
AND intLocked <> 1
ORDER BY intSeasonOrder, strSeasonName
];
#AND (intRealmSubTypeID = $Data->{'RealmSubType'} OR intRealmSubTypeID= 0)
my ($seasons_vals,$seasons_order)=getDBdrop_down_Ref($Data->{'db'},$st_seasons,'');
my $defaultClubID = $Data->{'clientValues'}{'clubID'} || 0;
$defaultClubID= 0 if ($defaultClubID == $Defs::INVALID_ID);
my $clubWHERE = ($Data->{'clientValues'}{'authLevel'} == $Defs::LEVEL_CLUB and $defaultClubID) ? qq[ WHERE C.intClubID = $defaultClubID] : '';
my $st_clubs=qq[
SELECT C.intClubID, strName
FROM tblClub as C
INNER JOIN tblAssoc_Clubs as AC ON (AC.intClubID = C.intClubID
AND AC.intAssocID = $Data->{'clientValues'}{'assocID'})
INNER JOIN tblMember_Clubs as MC ON (MC.intClubID = C.intClubID
AND MC.intMemberID = $Data->{'clientValues'}{'memberID'}
AND MC.intStatus <> $Defs::RECSTATUS_DELETED)
$clubWHERE
ORDER BY C.strName
];
my ($clubs_vals,$clubs_order)=getDBdrop_down_Ref($Data->{'db'},$st_clubs,'');
my $AgeGroups=AgeGroups::getAgeGroups($Data);
my $st_ageGroups=qq[
SELECT intAgeGroupID, IF(intRecStatus<1, CONCAT(strAgeGroupDesc, ' (Inactive)'), strAgeGroupDesc) as strAgeGroupDesc
FROM tblAgeGroups
WHERE intRealmID = $Data->{'Realm'}
AND (intAssocID=$Data->{'clientValues'}{'assocID'} OR intAssocID =0)
AND (intRealmSubTypeID = $subType OR intRealmSubTypeID = 0)
AND intRecStatus<>-1
ORDER BY strAgeGroupDesc
];
my ($ageGroups_vals,$ageGroups_order) = getDBdrop_down_Ref($Data->{'db'},$st_ageGroups,'');
my $levelName = ($action =~ /CADD$/ or $dref->{intClubID})
? $Data->{'LevelNames'}{$Defs::LEVEL_CLUB}
: $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC};
my $MemberPackages=getMemberPackages($Data) || '';
if (! $memberSeasonID and $action =~ /ADD/ and $Data->{'SystemConfig'}{'checkLastSeasonTypesFilter'}) {
my $clubWHERE = ($Data->{'clientValues'}{'clubID'} and $Data->{'clientValues'}{'clubID'} != $Defs::INVALID_ID)
? qq[ AND intClubID = $Data->{'clientValues'}{'clubID'}]
: qq[ AND intClubID=0];
my $st = qq[
SELECT
intPlayerStatus,
intCoachStatus,
intUmpireStatus,
intOfficialStatus,
intMiscStatus,
intVolunteerStatus
FROM
$tablename
WHERE
intMemberID = $Data->{'clientValues'}{'memberID'}
AND intAssocID = $Data->{'clientValues'}{'assocID'}
$clubWHERE
AND intSeasonID IN ($Data->{'SystemConfig'}{'checkLastSeasonTypes'})
AND intMSRecStatus =1
ORDER BY intSeasonID DESC
LIMIT 1
];
my $query = $db->prepare($st);
$query->execute();
my $lastref=$query->fetchrow_hashref();
$dref->{intPlayerStatus} = 1 if ($lastref->{intPlayerStatus});
$dref->{intCoachStatus} = 1 if ($lastref->{intCoachStatus});
$dref->{intUmpireStatus} = 1 if ($lastref->{intUmpireStatus});
$dref->{intOfficialStatus} = 1 if ($lastref->{intOfficialStatus});
$dref->{intMiscStatus} = 1 if ($lastref->{intMiscStatus});
$dref->{intVolunteerStatus} = 1 if ($lastref->{intVolunteerStatus});
}
my $txt_SeasonName= $Data->{'SystemConfig'}{'txtSeason'} || 'Season';
my %FieldDefs = (
fields => {
SeasonName => {
label => "$txt_Name Name",
value => $dref->{strSeasonName},
type => 'text',
readonly => 1,
sectionname => 'main',
},
intMSRecStatus=> {
label => qq[Participated in this $txt_SeasonName?],
value => $dref->{intMSRecStatus},
type => 'checkbox',
default => 1,
displaylookup => {1 => 'Yes', -1 => 'No'},
sectionname => 'main',
},
intSeasonID => {
label => $option eq 'add' ? "$txt_Name Name" : '',
value => $dref->{intSeasonID},
type => 'lookup',
options => $seasons_vals,
firstoption => ['',"Choose $txt_Name"],
compulsory => $option eq 'add' ? 1 : 0,
},
ClubName => {
label => $dref->{intClubID} ? "$Data->{'LevelNames'}{$Defs::LEVEL_CLUB} Name" : '',
value => $dref->{ClubName},
type => 'text',
readonly =>1,
sectionname => 'main',
},
intClubID => {
label => ($action =~ /CADD$/) ? "$Data->{'LevelNames'}{$Defs::LEVEL_CLUB} Name" : '',
value => $dref->{intClubID} || (($Data->{'clientValues'}{'clubID'} and $Data->{'clientValues'}{'clubID'} != $Defs::INVALID_ID) ? $Data->{'clientValues'}{'clubID'} : 0),
type => 'lookup',
options => $clubs_vals,
firstoption => ['',"Choose $Data->{'LevelNames'}{$Defs::LEVEL_CLUB} (from list of $Data->{'LevelNames'}{$Defs::LEVEL_CLUB.'_P'} registered to)"],
compulsory => ($option eq 'add' and $action =~ /CADD$/) ? 1 : 0,
},
intSeasonMemberPackageID=> {
label => "$levelName $txt_Name Member Package",
value => $dref->{intSeasonMemberPackageID},
type => 'lookup',
options => $MemberPackages,
firstoption => [''," "],
},
intPlayerAgeGroupID => {
label => "$txt_AgeGroupName",
value => $dref->{intPlayerAgeGroupID},
type => 'lookup',
options => $ageGroups_vals,
firstoption => ['',"Choose $txt_AgeGroupName"],
},
intPlayerStatus => {
label => "Player in $levelName?",
value => $dref->{intPlayerStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname => 'main',
readonly =>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
},
intPlayerFinancialStatus=> {
label => "Player Financial in $levelName?",
value => $dref->{intPlayerFinancialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
DateInPlayer=> {
label => "Date Player created in $levelName",
value => $dref->{DateInPlayer},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intCoachStatus => {
label => "Coach in $levelName?",
value => $dref->{intCoachStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intCoachFinancialStatus=> {
label => "Coach Financial in $levelName?",
value => $dref->{intCoachFinancialStatus},
type => 'checkbox',
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname => 'main',
},
DateInCoach=> {
label => "Date Coach created in $levelName",
value => $dref->{DateInCoach},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intUmpireStatus => {
label => "Match Official in $levelName?",
value => $dref->{intUmpireStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intUmpireFinancialStatus=> {
label => "Match Official Financial in $levelName?",
value => $dref->{intUmpireFinancialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
DateInUmpire=> {
label => "Date Match Official created in $levelName",
value => $dref->{DateInUmpire},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intOfficialStatus => {
label => "Official in $levelName?",
value => $dref->{intOfficialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intOfficialFinancialStatus=> {
label => "Official Financial in $levelName?",
value => $dref->{intOfficialFinancialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
DateInOfficial=> {
label => "Date Official created in $levelName",
value => $dref->{DateInOfficial},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intMiscStatus => {
label => "Misc in $levelName?",
value => $dref->{intMiscStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intMiscFinancialStatus=> {
label => "Misc Financial in $levelName?",
value => $dref->{intMiscFinancialStatus},
type => 'checkbox',
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname => 'main',
},
DateInMisc=> {
label => "Date Misc created in $levelName",
value => $dref->{DateInMisc},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intVolunteerStatus => {
label => "Volunteer in $levelName?",
value => $dref->{intVolunteerStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intVolunteerFinancialStatus=> {
label => "Volunteer Financial in $levelName?",
value => $dref->{intVolunteerFinancialStatus},
type => 'checkbox',
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname => 'main',
},
DateInVolunteer=> {
label => "Date Volunteer created in $levelName",
value => $dref->{DateInVolunteer},
type => 'date',
readonly=>1,
sectionname => 'main',
},
intOther1Status => {
label => $Data->{'SystemConfig'}{'Seasons_Other1'} ? "$Data->{'SystemConfig'}{'Seasons_Other1'} in $levelName?" : '',
value => $dref->{intOther1Status},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
intOther1FinancialStatus=> {
label => $Data->{'SystemConfig'}{'Seasons_Other1'} ? "$Data->{'SystemConfig'}{'Seasons_Other1'} Financial in $levelName?" : '',
value => $dref->{intOther1FinancialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
DateInOther1 => {
label => $Data->{'SystemConfig'}{'Seasons_Other1'} ? "Date $Data->{'SystemConfig'}{'Seasons_Other1'} created in $levelName?" : '',
value => $dref->{DateInOther1},
type => 'date',
readonly => 1,
sectionname => 'main',
},
intOther2Status => {
label => $Data->{'SystemConfig'}{'Seasons_Other2'} ? "$Data->{'SystemConfig'}{'Seasons_Other2'} in $levelName?" : '',
value => $dref->{intOther2Status},
type => 'checkbox',
readonly => ($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname => 'main',
},
intOther2FinancialStatus=> {
label => $Data->{'SystemConfig'}{'Seasons_Other2'} ? "$Data->{'SystemConfig'}{'Seasons_Other2'} Financial in $levelName?" : '',
value => $dref->{intOther2FinancialStatus},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
readonly=>($option eq 'edit' and $Data->{'SystemConfig'}{'LockSeasons'}) ? 1 : 0,
sectionname => 'main',
},
DateInOther2 => {
label => $Data->{'SystemConfig'}{'Seasons_Other2'} ? "Date $Data->{'SystemConfig'}{'Seasons_Other2'} created in $levelName?" : '',
value => $dref->{DateInOther2},
type => 'date',
readonly=>1,
sectionname => 'main',
},
},
order => [
qw(
SeasonName
intSeasonID
intMSRecStatus
ClubName
intClubID
intSeasonMemberPackageID
intPlayerAgeGroupID
intPlayerStatus
intPlayerFinancialStatus
DateInPlayer
intCoachStatus
intCoachFinancialStatus
DateInCoach
intUmpireStatus
intUmpireFinancialStatus
DateInUmpire
intOfficialStatus
intOfficialFinancialStatus
DateInOfficial
intMiscStatus
intMiscFinancialStatus
DateInMisc
intVolunteerStatus
intVolunteerFinancialStatus
DateInVolunteer
intOther1Status
intOther1FinancialStatus
DateInOther1
intOther2Status
intOther2FinancialStatus
DateInOther2
)
],
options => {
labelsuffix => ':',
hideblank => 1,
target => $Data->{'target'},
formname => 'ms_form',
submitlabel => "Update $txt_Name Summary",
introtext => 'auto',
buttonloc => 'bottom',
updateSQL => $msupdate,
addSQL => $msadd,
afteraddFunction => \&postMemberSeasonAdd,
afteraddParams => [$option,$Data,$Data->{'db'}, $memberSeasonID],
afterupdateFunction => \&postMemberSeasonUpdate,
afterupdateParams => [$option,$Data,$Data->{'db'}, $memberSeasonID],
updateOKtext => qq[
<div class="OKmsg">Record updated successfully</div> <br>
<a href="$Data->{'target'}?client=$client&a=M_HOME">Return to Member Record</a>
],
addOKtext => qq[
<div class="OKmsg">Record added successfully</div> <br>
<a href="$Data->{'target'}?client=$client&a=M_HOME">Return to Member Record</a>
],
addBADtext => qq[
<div class="OKmsg">Record was not inserted</div> <br>
<a href="$Data->{'target'}?client=$client&a=M_HOME">Return to Member Record</a>
],
updateBADtext => qq[
<div class="OKmsg">Record was not updated</div> <br>
<a href="$Data->{'target'}?client=$client&a=M_HOME">Return to Member Record</a>
],
auditFunction=> \&auditLog,
auditAddParams => [
$Data,
'Add Season',
'Member'
],
auditEditParams => [
$memberSeasonID,
$Data,
'Update Season',
'Member'
],
},
sections => [ ['main','Details'], ],
carryfields => {
client => $client,
a => $action,
msID => $memberSeasonID,
},
);
($resultHTML, undef ) = handleHTMLForm(\%FieldDefs, undef, $option, '',$db);
if (! $resultHTML) {
$resultHTML .= qq[
<div class="warningmsg">$txt_Name record may already exist</div> <br>
<a href="$Data->{'target'}?client=$client&a=M_HOME">Return to Member Record</a>
];
}
my $editDetailsLink = '';
if (!$Data->{'ReadOnlyLogin'} and $option eq 'display' and ! ($Data->{'clientValues'}{'authLevel'} <= $Defs::LEVEL_CLUB and ! $dref->{intClubID})) {
$editDetailsLink .= qq[ <a href="$target?a=SN_MSviewEDIT&msID=$memberSeasonID&client=$client">Edit details</a> ];
}
$editDetailsLink = '' if ($Data->{'clientValues'}{'authLevel'} == $Defs::LEVEL_CLUB and $Data->{'SystemConfig'}{'Club_MemberEditOnly'});
$editDetailsLink = '' if $Data->{'SystemConfig'}{'LockSeasonsFullEditLock'};
# if LockSeasonsCRL is set all levels above club can edit season record.
$editDetailsLink = '' if ($Data->{'SystemConfig'}{'LockSeasonsCRL'} and $Data->{'clientValues'}{'authLevel'} <$Defs::LEVEL_ASSOC);
$resultHTML .= $editDetailsLink;
$resultHTML=qq[<div>Cannot find Member $txt_Name record.</div>] if !ref $dref;
$resultHTML = qq[<div>$resultHTML</div>];
return ($resultHTML, "$txt_Name Summary");
}
sub postMemberSeasonAdd {
my ($id, $params, $action, $Data, $db, $memberSeasonID) = @_;
my $nationalSeasonID = getNationalReportingPeriod($Data->{db}, $Data->{'Realm'}, $Data->{'RealmSubType'});
my $st = qq[
UPDATE tblMember_Seasons_$Data->{'Realm'}
SET intNatReportingGroupID = ?
WHERE intMemberSeasonID = ?
];
my $q = $Data->{db}->prepare($st);
$q->execute($nationalSeasonID, $id);
postMemberSeasonUpdate($id,$params, $action,$Data,$db, $memberSeasonID);
}
sub postMemberSeasonUpdate {
my ($id,$params, $action,$Data,$db, $memberSeasonID) = @_;
$memberSeasonID||=0;
my $tablename = "tblMember_Seasons_$Data->{'Realm'}";
$id ||= $memberSeasonID;
my $st =qq[
SELECT MS.intSeasonID, DATE_FORMAT(M.dtDOB, "%Y%m%d") as DOBAgeGroup, M.intGender, MS.intClubID
FROM $tablename as MS
INNER JOIN tblMember as M ON (M.intMemberID = MS.intMemberID)
WHERE MS.intMemberID = $Data->{'clientValues'}{'memberID'}
AND MS.intAssocID = $Data->{'clientValues'}{'assocID'}
AND MS.intMemberSeasonID = $id
];
my $query = $db->prepare($st);
$query->execute();
my ($seasonID, $DOBAgeGroup, $Gender, $intClubID) =$query->fetchrow_array();
$seasonID ||= 0;
my $assocSeasons = getDefaultAssocSeasons($Data);
if ($seasonID and $Data->{'clientValues'}{'assocID'} and $Data->{'clientValues'}{'memberID'} and $id) {
#Transactions::insertDefaultRegoTXN($db, $Defs::LEVEL_MEMBER, $Data->{'clientValues'}{'memberID'}, $Data->{'clientValues'}{'assocID'});
## I think this is to get Member.Interests updated
my $genAgeGroup ||=new GenAgeGroup ($Data->{'db'},$Data->{'Realm'}, $Data->{'RealmSubType'}, $Data->{'clientValues'}{'assocID'});
my $ageGroupID=$genAgeGroup->getAgeGroup ($Gender, $DOBAgeGroup) || 0;
my %types=();
$types{'intPlayerStatus'} = $params->{'d_intPlayerStatus'} if ($params->{'d_intPlayerStatus'});
$types{'intCoachStatus'} = $params->{'d_intCoachStatus'} if ($params->{'d_intCoachStatus'});
$types{'intUmpireStatus'} = $params->{'d_intUmpireStatus'} if ($params->{'d_intUmpireStatus'});
$types{'intOfficialStatus'} = $params->{'d_intOfficialStatus'} if ($params->{'d_intOfficialStatus'});
$types{'intMiscStatus'} = $params->{'d_intMiscStatus'} if ($params->{'d_intMiscStatus'});
$types{'intVolunteerStatus'} = $params->{'d_intVolunteerStatus'} if ($params->{'d_intVolunteerStatus'});
$types{'intOther1Status'} = $params->{'d_intOther1Status'} if ($params->{'d_intOther1Status'});
$types{'intOther2Status'} = $params->{'d_intOther2Status'} if ($params->{'d_intOther2Status'});
$types{'intMSRecStatus'} = $params->{'d_intMSRecStatus'} == 1 ? 1 : -1;
$types{'userselected'}=1;
insertMemberSeasonRecord($Data, $Data->{'clientValues'}{'memberID'}, $seasonID, $Data->{'clientValues'}{'assocID'}, $intClubID, $ageGroupID, \%types);
## UNREMOVED THIS
if (($intClubID or $Data->{'clientValues'}{'clubID'} > 0) and $types{'intMSRecStatus'} == 1) {
## Lets remove the "types"
if (! $Data->{'SystemConfig'}{'Seasons_StatusClubToAssoc'}) {
delete $types{'intPlayerStatus'};
delete $types{'intCoachStatus'};
delete $types{'intUmpireStatus'};
delete $types{'intOfficialStatus'};
delete $types{'intMiscStatus'};
delete $types{'intVolunteerStatus'};
delete $types{'intOther1Status'};
delete $types{'intOther2Status'};
}
insertMemberSeasonRecord($Data, $Data->{'clientValues'}{'memberID'}, $seasonID, $Data->{'clientValues'}{'assocID'}, 0, $ageGroupID, \%types);
}
if ($assocSeasons->{'newRegoSeasonID'} and $Data->{'SystemConfig'}{'Seasons_activateMembers'} and $types{'intMSRecStatus'} == 1) {
my $st = qq[
UPDATE tblMember_Associations
SET intRecStatus = $Defs::RECSTATUS_ACTIVE
WHERE intMemberID = $Data->{'clientValues'}{'memberID'}
AND intAssocID = $Data->{'clientValues'}{'assocID'}
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute or query_error($st);
}
}
}
sub season_details {
my ($action, $Data, $seasonID)=@_;
my $lang = $Data->{'lang'};
my $option='display';
$option='edit' if $action eq 'SN_DTE' and allowedAction($Data, 'sn_e');
$option='add' if $action eq 'SN_DTA' and allowedAction($Data, 'sn_a');
$seasonID=0 if $option eq 'add';
my $field=loadSeasonDetails($Data->{'db'}, $seasonID, $Data->{'Realm'}, $Data->{'RealmSubType'}, $Data->{'clientValues'}{'assocID'}) || ();
my $intAssocID = $Data->{'clientValues'}{'assocID'} >= 0 ? $Data->{'clientValues'}{'assocID'} : 0;
my $txt_Name= $lang->txt($Data->{'SystemConfig'}{'txtSeason'}) || $lang->txt('Season');
my $txt_Names= $lang->txt($Data->{'SystemConfig'}{'txtSeasons'}) || $lang->txt('Seasons');
my $client=setClient($Data->{'clientValues'}) || '';
my $lockedlabel = "$txt_Name Locked";
my $archivelabel = "$txt_Name Archived";
$lockedlabel = '' if !$seasonID;
$archivelabel = '' if !$seasonID;
my %FieldDefinitions=(
fields=> {
strSeasonName => {
label => "$txt_Name Name",
value => $field->{strSeasonName},
type => 'text',
size => '40',
maxsize => '100',
compulsory => 1,
sectionname=>'details',
},
intSeasonOrder=> {
label => "$txt_Name Order",
value => $field->{intSeasonOrder},
type => 'text',
size => '15',
maxsize => '15',
validate => 'NUMBER',
sectionname=>'details',
},
intArchiveSeason=> {
label => $archivelabel,
value => $field->{intArchiveSeason},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname=>'details',
},
intLocked => {
label => $lockedlabel,
value => $field->{intLocked},
type => 'checkbox',
displaylookup => {1 => 'Yes', 0 => 'No'},
sectionname=>'details',
},
},
order => [qw(strSeasonName intSeasonOrder intArchiveSeason intLocked)],
sections => [
['details',"$txt_Name Details"],
],
options => {
labelsuffix => ':',
hideblank => 1,
target => $Data->{'target'},
formname => 'n_form',
submitlabel => "Update $txt_Name",
introtext => 'auto',
NoHTML => 1,
updateSQL => qq[
UPDATE tblSeasons
SET --VAL--
WHERE intSeasonID = $seasonID AND intAssocID = $intAssocID
],
addSQL => qq[
INSERT INTO tblSeasons
(intRealmID, intRealmSubTypeID, intAssocID, dtAdded, --FIELDS-- )
VALUES
($Data->{'Realm'}, $Data->{'RealmSubType'}, $intAssocID, SYSDATE(), --VAL-- )
],
auditFunction=> \&auditLog,
auditAddParams => [
$Data,
'Add',
'Seasons'
],
auditEditParams => [
$seasonID,
$Data,
'Update',
'Seasons'
],
LocaleMakeText => $Data->{'lang'},
},
carryfields => {
client => $client,
a => $action,
seasonID => $seasonID,
},
);
my $resultHTML='';
($resultHTML, undef )=handleHTMLForm(\%FieldDefinitions, undef, $option, '',$Data->{'db'});
my $title=qq[$txt_Name - $field->{strSeasonName}];
if($option eq 'display') {
my $chgoptions='';
$chgoptions.=qq[<span class = "button-small generic-button"><a href="$Data->{'target'}?client=$client&a=SN_DTE&seasonID=$seasonID">Edit $txt_Name</a></span> ] if allowedAction($Data, 'sn_e');
$chgoptions=qq[<div class="changeoptions">$chgoptions</div>] if $chgoptions;
$chgoptions= '' if ($Data->{'clientValues'}{'authLevel'} != $Defs::LEVEL_NATIONAL and ! $field->{intAssocID});
$chgoptions= '' if ($Data->{'clientValues'}{'authLevel'} != $Defs::LEVEL_NATIONAL and $Data->{'SystemConfig'}{'Seasons_NationalOnly'});
$title=$chgoptions.$title;
}
$title="Add New $txt_Name" if $option eq 'add';
my $text = qq[<p><a href="$Data->{'target'}?client=$client&a=SN_L">Click here</a> to return to list of $txt_Names</p>];
$resultHTML = $text.qq[<br><br>].$resultHTML.qq[<br><br>$text];
return ($resultHTML,$title);
}
sub loadSeasonDetails {
my($db, $id, $realmID, $realmSubType, $assocID) = @_;
return {} if !$id;
$realmID ||= 0;
$realmSubType ||=0;
$assocID ||= 0;
my $statement=qq[
SELECT *
FROM tblSeasons
WHERE intSeasonID = $id
AND intRealmID = $realmID
AND (intAssocID = $assocID OR intAssocID = 0)
AND (intRealmSubTypeID = $realmSubType OR intRealmSubTypeID= 0)
];
my $query = $db->prepare($statement);
$query->execute();
my $field=$query->fetchrow_hashref();
$query->finish;
foreach my $key (keys %{$field}) { if(!defined $field->{$key}) {$field->{$key}='';} }
return $field;
}
sub insertMemberSeasonRecord {
# The following columns are handled via $types hash:
# intPlayerAgeGroupID,
# intPlayerStatus,
# intPlayerFinancialStatus,
# intCoachStatus,
# intCoachFinancialStatus,
# intUmpireStatus,
# intUmpireFinancialStatus,
# intOfficialStatus,
# intOfficialFinancialStatus,
# intMiscStatus,
# intMiscFinancialStatus,
# intVolunteerStatus,
# intVolunteerFinancialStatus,
my ($Data, $intMemberID, $intSeasonID, $intAssocID, $intClubID, $intPlayerAgeGroupID, $types, $update_time, $rereg) = @_;
$intMemberID || return;
$intSeasonID || return;
$intAssocID || return;
$intClubID ||= 0;
$intClubID = 0 if ($intClubID == $Defs::INVALID_ID);
$intPlayerAgeGroupID ||= 0;
my $tablename = "tblMember_Seasons_$Data->{'Realm'}";
## -- GET NATIONAL REPORTING SEASON ID
my $nationalSeasonID = getNationalReportingPeriod($Data->{db}, $Data->{'Realm'}, $Data->{'RealmSubType'}, $intSeasonID);
## --
my ($insert_cols, $insert_vals, $update_status, $update_financials, $update_dates) = ('', '', '', '', '');
my $recStatus = '';
$types->{'intMSRecStatus'} = 1 if ! defined $types->{'intMSRecStatus'};
$types->{'userselected'} ||= 0;
## Don't run from screen where the user can actually affect the results
if (!$types->{'userselected'} and $intSeasonID == $Data->{'SystemConfig'}{'Seasons_defaultNewRegoSeason'} and $Data->{'SystemConfig'}{'checkLastSeasonTypesFilter'}) {
my $clubWHERE = ($intClubID>0) ? qq[ AND intClubID = $intClubID] : qq[ AND intClubID=0];
my $st = qq[
SELECT
intPlayerStatus,
intCoachStatus,
intUmpireStatus,
intOfficialStatus,
intMiscStatus,
intVolunteerStatus
FROM
$tablename
WHERE
intMemberID = $intMemberID
AND intAssocID = $intAssocID
$clubWHERE
AND intSeasonID IN ($Data->{'SystemConfig'}{'checkLastSeasonTypes'})
AND intMSRecStatus = 1
ORDER BY
intSeasonID DESC
LIMIT 1
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my $lastref=$query->fetchrow_hashref();
$types->{intPlayerStatus} = 2 if ($lastref->{intPlayerStatus} and !$types->{intPlayerStatus});
$types->{intCoachStatus} = 2 if ($lastref->{intCoachStatus} and !$types->{intCoachStatus});
$types->{intUmpireStatus} = 2 if ($lastref->{intUmpireStatus} and !$types->{intUmpireStatus});
$types->{intOfficialStatus} = 2 if ($lastref->{intOfficialStatus} and !$types->{intOfficialStatus});
$types->{intMiscStatus} = 2 if ($lastref->{intMiscStatus} and !$types->{intMiscStatus});
$types->{intVolunteerStatus} = 2 if ($lastref->{intVolunteerStatus} and !$types->{intVolunteerStatus});
}
foreach my $type (keys %{$types}) {
next if ($type eq 'intOfficial'); #should this still be the case?
next if ($type eq 'intMisc'); #should this? and if so, why not volunteer as well?
next if ($type eq 'userselected');
$types->{$type} ||= 0;
if ($type ne 'intMSRecStatus') {
$insert_cols .= qq[, $type];
my $value = $types->{$type};
$value = 1 if ($value =~/1/ and $type =~ /Status/);
$value=1 if ($value==2);
$insert_vals .= qq[, $value];
}
if ($type eq 'intPlayerStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInPlayer];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInPlayer= IF(dtInPlayer > '0000-00-00', dtInPlayer, CURDATE())];
}
}
if ($type eq 'intCoachStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInCoach];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInCoach= IF(dtInCoach > '0000-00-00', dtInCoach, CURDATE())];
}
}
if ($type eq 'intUmpireStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInUmpire];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInUmpire= IF(dtInUmpire > '0000-00-00', dtInUmpire, CURDATE())];
}
}
if ($type eq 'intOfficialStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInOfficial];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInOfficial= IF(dtInOfficial > '0000-00-00', dtInOfficial, CURDATE())];
}
}
if ($type eq 'intMiscStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInMisc];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInMisc= IF(dtInMisc > '0000-00-00', dtInMisc, CURDATE())];
}
}
if ($type eq 'intVolunteerStatus' and $types->{$type} >= 1) {
$insert_cols .= qq[, dtInVolunteer];
$insert_vals .= qq[, CURDATE()];
if ($types->{$type} == 1) {
$update_dates.= qq[, dtInVolunteer= IF(dtInVolunteer > '0000-00-00', dtInVolunteer, CURDATE())];
}
}
if ($type eq 'intOther1Status' and $types->{$type} == 1) {
$insert_cols .= qq[, dtInOther1];
$insert_vals .= qq[, CURDATE()];
$update_dates.= qq[, dtInOther1= IF(dtInOther1 > '0000-00-00', dtInOther1, CURDATE())];
}
if ($type eq 'intOther2Status' and $types->{$type} == 1) {
$insert_cols .= qq[, dtInOther2];
$insert_vals .= qq[, CURDATE()];
$update_dates.= qq[, dtInOther2= IF(dtInOther2 > '0000-00-00', dtInOther2, CURDATE())];
}
if ($type eq 'intMSRecStatus') {
$recStatus = qq[, intMSRecStatus = $types->{$type}];
}
if ($type !~ /Financial|intMSRecStatus|userselected/) {
my $value = $types->{$type};
$types->{$type}= 1 if ($value =~/1/ and $type =~ /Status/);
$update_status .= qq[, $type = $types->{$type}] if ($value < 2 and $type ne 'intSeasonMemberPackageID');
$update_status .= qq[, $type = $types->{$type}] if ($type eq 'intSeasonMemberPackageID');
}
$update_financials .= qq[, $type = $types->{$type}] if ($type =~ /Financial/);
}
if ($intPlayerAgeGroupID) {
$insert_cols .= qq[, intPlayerAgeGroupID];
$insert_vals .= qq[, $intPlayerAgeGroupID];
}
my $timeStamp = qq[ tTimeStamp=NOW() ];
$timeStamp = qq[ tTimeStamp = "$update_time" ] if $update_time;
if (exists $Data->{'fromsync'} and $Data->{'fromsync'} and exists $Data->{'fromsync_memberID'} and $Data->{'fromsync_memberID'} =~ /^S/) {
$update_status='';
$update_financials='';
$update_dates='';
}
my $status = 1;
my $pending = 0;
my $update_pending = '';
if ($Data->{'SystemConfig'}{'AllowPendingRegistration'} and defined $rereg and !$rereg) {
my $pendingTypes = getPendingTypes($Data->{'SystemConfig'});
foreach my $type (keys %{$types}) {
#there is only one pending field; set it to 1 if any of the types coming thru allow pending.
if (exists $pendingTypes->{$type} and $pendingTypes->{$type}) {
$status = 0;
$pending = 1;
$insert_cols .= qq[, intPlayerPending];
$insert_vals .= qq[, $pending];
$recStatus = qq[, intMSRecStatus=$status];
$update_pending = qq[, intPlayerPending=$pending];
last;
}
}
}
if (!$pending) {
if($Data->{'SystemConfig'}{'AllowPendingRegistration'} and $rereg == 2) {
$recStatus = '';
}
}
my $st = qq[
INSERT INTO $tablename (
intMSRecStatus,
intMemberID,
intAssocID,
intClubID,
intSeasonID,
intNatReportingGroupID
$insert_cols
)
VALUES (
$status,
$intMemberID,
$intAssocID,
$intClubID,
$intSeasonID,
$nationalSeasonID
$insert_vals
)
ON DUPLICATE KEY
UPDATE $timeStamp $update_status $update_financials $update_dates $update_pending $recStatus
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my $ID = 0;
if (exists $Data->{'fromsync'}) {
$st = qq[
SELECT
intMemberSeasonID
FROM
$tablename
WHERE
intMemberID=$intMemberID
AND intAssocID=$intAssocID
AND intClubID=$intClubID
AND intSeasonID=$intSeasonID
];
$query = $Data->{'db'}->prepare($st);
$query->execute();
$ID = $query->fetchrow_array() || 0;
}
if ($types->{'intMSRecStatus'} and $types->{'intMSRecStatus'} == -1 and $intClubID == 0) {
## The Assoc record was being marked as deleted, so do all club records aswell
$st = qq[
UPDATE
$tablename
SET
intMSRecStatus=-1
WHERE
intMemberID=$intMemberID
AND intAssocID=$intAssocID
AND intSeasonID=$intSeasonID
AND intClubID>0
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
}
### Now lets go update the interest flags
$st = qq[
SELECT
MAX(intPlayerStatus) as PlayerStatus,
MAX(intCoachStatus) as CoachStatus,
MAX(intUmpireStatus) as UmpireStatus,
MAX(intOfficialStatus) as OfficialStatus,
MAX(intMiscStatus) as MiscStatus,
MAX(intVolunteerStatus) as VolunteerStatus
FROM
$tablename
WHERE
intMemberID = $intMemberID
AND intMSRecStatus=1
];
$query = $Data->{'db'}->prepare($st);
$query->execute();
my ($PlayerStatus, $CoachStatus, $UmpireStatus, $OfficialStatus, $MiscStatus, $VolunteerStatus ) = $query->fetchrow_array();
$PlayerStatus ||= 0;
$CoachStatus ||= 0;
$UmpireStatus ||= 0;
$OfficialStatus ||= 0;
$MiscStatus ||= 0;
$VolunteerStatus ||= 0;
$st = qq[
UPDATE tblMember
SET
intPlayer = $PlayerStatus,
intCoach = $CoachStatus,
intUmpire = $UmpireStatus,
intOfficial = $OfficialStatus,
intMisc = $MiscStatus,
intVolunteer = $VolunteerStatus
WHERE
intMemberID = $intMemberID
];
$Data->{'db'}->do($st);
if ($Data->{'SystemConfig'}{'Seasons_StatusClubToAssoc'} or $Data->{'SystemConfig'}{'Seasons_FinancialsClubToAssoc'}) {
$update_status = '';
$st = qq[
SELECT
COUNT(intMemberID) as Count,
MAX(intPlayerStatus) as PlayerStatus,
MAX(intCoachStatus) as CoachStatus,
MAX(intUmpireStatus) as UmpireStatus,
MAX(intOfficialStatus) as OfficialStatus,
MAX(intMiscStatus) as MiscStatus,
MAX(intVolunteerStatus) as VolunteerStatus,
MAX(intOther1Status) as Other1Status,
MAX(intOther2Status) as Other2Status,
MAX(intPlayerFinancialStatus) as PlayerFinancialStatus,
MAX(intCoachFinancialStatus) as CoachFinancialStatus,
MAX(intUmpireFinancialStatus) as UmpireFinancialStatus,
MAX(intOfficialFinancialStatus) as OfficialFinancialStatus,
MAX(intMiscFinancialStatus) as MiscFinancialStatus,
MAX(intVolunteerFinancialStatus) as VolunteerFinancialStatus,
MAX(intOther1FinancialStatus) as Other1FinancialStatus,
MAX(intOther2FinancialStatus) as Other2FinancialStatus
FROM
$tablename
WHERE
intMemberID=$intMemberID
AND intAssocID=$intAssocID
AND intClubID>0
AND intSeasonID=$intSeasonID
AND intMSRecStatus=1
];
$query = $Data->{'db'}->prepare($st);
$query->execute();
my ($count, $PlayerStatus, $CoachStatus, $UmpireStatus, $OfficialStatus, $MiscStatus, $VolunteerStatus,
$Other1Status, $Other2Status, $PFStatus, $CFStatus, $UFStatus, $OFStatus, $MFStatus, $VFStatus, $O1FStatus, $O2FStatus) = $query->fetchrow_array();
$PlayerStatus ||= 0;
$CoachStatus ||= 0;
$UmpireStatus ||= 0;
$OfficialStatus ||= 0;
$MiscStatus ||= 0;
$VolunteerStatus ||= 0;
$Other1Status ||= 0;
$Other2Status ||= 0;
my $timeStamp = qq[NOW()];
if (exists $Data->{'fromsync'}) {
$timeStamp = qq[tTimeStamp ];
}
if ($Data->{'SystemConfig'}{'Seasons_StatusClubToAssoc'}) {
$update_status .= qq[ , intPlayerStatus = $PlayerStatus];
$update_status .= qq[ , intCoachStatus = $CoachStatus];
$update_status .= qq[ , intUmpireStatus = $UmpireStatus];
$update_status .= qq[ , intOfficialStatus = $OfficialStatus];
$update_status .= qq[ , intMiscStatus = $MiscStatus];
$update_status .= qq[ , intVolunteerStatus = $VolunteerStatus];
$update_status .= qq[ , intOther1Status = $Other1Status];
$update_status .= qq[ , intOther2Status = $Other2Status];
}
if ($Data->{'SystemConfig'}{'Seasons_FinancialsClubToAssoc'}) {
$update_status .= qq[ , intPlayerFinancialStatus = 1] if $PFStatus;
$update_status .= qq[ , intCoachFinancialStatus = 1] if $CFStatus;
$update_status .= qq[ , intUmpireFinancialStatus = 1] if $UFStatus;
$update_status .= qq[ , intOfficialFinancialStatus = 1] if $OFStatus;
$update_status .= qq[ , intMiscFinancialStatus = 1] if $MFStatus;
$update_status .= qq[ , intVolunteerFinancialStatus = 1] if $VFStatus;
$update_status .= qq[ , intOther1FinancialStatus = 1] if $O1FStatus;
$update_status .= qq[ , intOther2FinancialStatus = 1] if $O2FStatus;
}
$st = qq[
UPDATE
$tablename
SET
tTimeStamp=$timeStamp
$update_status
WHERE
intMemberID=$intMemberID
AND intAssocID=$intAssocID
AND intClubID=0
AND intSeasonID=$intSeasonID
];
$Data->{'db'}->do($st) if $count;
}
if ($Data->{'RegoFormID'} and $Data->{'RegoFormID'} > 0) {
$st = qq[
UPDATE
$tablename
SET
intUsedRegoForm=1,
dtLastUsedRegoForm = NOW(),
intUsedRegoFormID=$Data->{'RegoFormID'}
WHERE
intMemberID = $intMemberID
AND intAssocID = $intAssocID
AND intClubID IN (0, $intClubID)
AND intSeasonID = $intSeasonID
];
$Data->{'db'}->do($st);
}
if ($Data->{'SystemConfig'}{'Seasons_rolloverDateRegistered'}) {
my $st = qq[
UPDATE tblMember_Associations
SET
dtLastRegistered=NOW()
WHERE
intMemberID = $intMemberID
AND intAssocID = $intAssocID
LIMIT 1
];
$Data->{'db'}->do($st);
}
return $ID;
}
sub getPendingTypes {
my ($systemConfig) = @_;
my @allowPendingTypes = (
['intPlayerStatus', 'Player' ],
['intCoachStatus', 'Coach' ],
['intUmpireStatus', 'Umpire' ],
['intOfficialStatus', 'Official' ],
['intMiscStatus', 'Misc' ],
['intVolunteer', 'Volunteer' ],
);
my %pendingTypes = ();
foreach my $item (@allowPendingTypes) {
my $fieldName = @$item[0];
my $configName = 'AllowPending_'.@$item[1];
$pendingTypes{$fieldName} = (exists $systemConfig->{$configName}) ? $systemConfig->{$configName} : 1;
}
return \%pendingTypes;
}
sub memberSeasonDuplicateResolution {
my ($Data, $assocID, $fromID, $toID) = @_;
my $realmID = $Data->{'Realm'} || 0;
my $tablename = "tblMember_Seasons_$realmID";
$Data->{'db'}->do(qq[UPDATE IGNORE $tablename SET intMemberID = $toID WHERE intMemberID=$fromID AND intAssocID = $assocID]);
my $assocSeasons = getDefaultAssocSeasons($Data);
my %types=();
$types{'intMSRecStatus'} = 1;
insertMemberSeasonRecord($Data, $toID, $assocSeasons->{'newRegoSeasonID'}, $assocID, 0, 0, undef) if ! $assocSeasons->{'allowSeasons'};
## Now lets handle the remaining duplicate records
my $st = qq[
SELECT
intClubID, intSeasonID, intPlayerAgeGroupID,
intPlayerStatus, intPlayerFinancialStatus,
intCoachStatus, intCoachFinancialStatus,
intUmpireStatus, intUmpireFinancialStatus,
intOfficialStatus, intOfficialFinancialStatus,
intMiscStatus, intMiscFinancialStatus,
intVolunteerStatus, intVolunteerFinancialStatus,
intOther1Status, intOther2Status,
intOther1FinancialStatus, intOther2FinancialStatus
FROM
$tablename
WHERE
intMemberID = $fromID
AND intAssocID=$assocID
];
my $query = $Data->{'db'}->prepare($st) or query_error($st);
$query->execute or query_error($st);
my @MemberSeasons = qw(
intPlayerAgeGroupID
intPlayerStatus intPlayerFinancialStatus
intCoachStatus intCoachFinancialStatus
intUmpireStatus intUmpireFinancialStatus
intOfficialStatus intOfficialFinancialStatus
intMiscStatus intMiscFinancialStatus
intVolunteerStatus intVolunteerFinancialStatus
intOther1Status intOther2Status
intOther1FinancialStatus intOther2FinancialStatus
);
while(my $dref = $query->fetchrow_hashref()) {
my $update_vals='';
for my $type (@MemberSeasons) {
if ($dref->{$type}) {
$update_vals .= qq[, ] if $update_vals;
$update_vals .= qq[ $type=$dref->{$type}];
}
}
if ($update_vals) {
$Data->{'db'}->do(qq[
UPDATE IGNORE $tablename
SET
$update_vals
WHERE
intAssocID = $assocID
AND intMemberID = $toID
AND intClubID = $dref->{intClubID}
AND intSeasonID = $dref->{intSeasonID}
]);
}
}
$st = qq[
SELECT
MAX(intPlayerStatus) as PlayerStatus,
MAX(intCoachStatus) as CoachStatus,
MAX(intUmpireStatus) as UmpireStatus,
MAX(intOfficialStatus) as OfficialStatus,
MAX(intMiscStatus) as MiscStatus,
MAX(intVolunteerStatus) as VolunteerStatus
FROM
$tablename
WHERE
intMemberID = $toID
];
$query = $Data->{'db'}->prepare($st);
$query->execute();
my ($PlayerStatus, $CoachStatus, $UmpireStatus, $OfficialStatus, $MiscStatus, $VolunteerStatus) = $query->fetchrow_array();
$PlayerStatus ||= 0;
$CoachStatus ||= 0;
$UmpireStatus ||= 0;
$OfficialStatus ||= 0;
$MiscStatus ||= 0;
$VolunteerStatus ||= 0;
$st = qq[
UPDATE tblMember
SET
intPlayer = $PlayerStatus,
intCoach = $CoachStatus,
intUmpire = $UmpireStatus,
intOfficial = $OfficialStatus,
intMisc = $MiscStatus,
intVolunteer = $VolunteerStatus
WHERE
intMemberID = $toID
];
$Data->{'db'}->do($st);
}
sub viewDefaultAssocSeasons {
my ($Data) = @_;
my $realmID=$Data->{'Realm'} || 0;
my $assocID=$Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID;
my ($Seasons, $maxSeasonID) =getSeasons($Data);
my $cl = setClient($Data->{'clientValues'});
my $st = qq[
SELECT intCurrentSeasonID, intNewRegoSeasonID
FROM tblAssoc
WHERE intAssocID = $assocID
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my ($currentSeasonID, $newRegoSeasonID) = $query->fetchrow_array();
$currentSeasonID ||= 0;
$newRegoSeasonID ||= 0;
if ($maxSeasonID and (! $currentSeasonID or ! $newRegoSeasonID)) {
## Don't allow blank currentSeason or new RegoSeason
$currentSeasonID ||= $Data->{'SystemConfig'}{'Seasons_defaultCurrentSeason'} || $maxSeasonID;
$newRegoSeasonID ||= $Data->{'SystemConfig'}{'Seasons_defaultNewRegoSeason'} || $maxSeasonID;
$Data->{'db'}->do(qq[UPDATE tblAssoc SET intCurrentSeasonID = $currentSeasonID, intNewRegoSeasonID = $newRegoSeasonID WHERE intAssocID = $assocID]);
}
my $txt_Name= $Data->{'SystemConfig'}{'txtSeason'} || 'Season';
my $txt_Names= $Data->{'SystemConfig'}{'txtSeasons'} || 'Seasons';
my $subBody='';
if (! $Data->{'SystemConfig'}{'Seasons_NationalOnly'}) {
$subBody .= qq[
<div class="sectionheader">Default $txt_Name Settings</div>
<p>Choose your default <b>CURRENT $txt_Name</b> for the $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC}. Press the 'Update' button to save your selection.</p>
<form action="$Data->{'target'}" method="post">
].drop_down('currentSeasonID',$Seasons,undef,$currentSeasonID,1,0).qq[
<p>Choose your default <b>NEW REGISTRATION $txt_Name</b> for the $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC}. Press the 'Update' button to save your selection.</p>
].drop_down('newregoSeasonID',$Seasons,undef,$newRegoSeasonID,1,0).qq[
<input type="hidden" name="a" value="SN_L_U">
<input type="hidden" name="client" value="
].unescape($cl).qq[">
<br><br><input type="submit" value=" Update " class = "button proceed-button">
</form>
];
}
else {
$subBody .= qq[
<div class="sectionheader">Default $txt_Name Settings</div>
<p><b>These are locked, and set by National body only</b></p>
<p><b>CURRENT $txt_Name</b> for the $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC}.</p>
].drop_down('currentSeasonID',$Seasons,undef,$currentSeasonID,1,0).qq[
<p><b>NEW REGISTRATION $txt_Name</b> for the $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC}. </p>
].drop_down('newregoSeasonID',$Seasons,undef,$newRegoSeasonID,1,0);
}
return $subBody;
}
sub getSeasons {
my($Data, $allseason, $blankseason)=@_;
$allseason ||= 0;
$blankseason ||= 0;
my $assocID=$Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID;
my $subType = $Data->{'RealmSubType'} || 0;
my $checkLocked = $Data->{'HideLocked'} ? qq[ AND intLocked <> 1] : '';
my $subTypeSeasonOnly = $Data->{'SystemConfig'}->{'OnlyUseSubRealmSeasons'} ? '' : 'OR intRealmSubTypeID= 0';
my $st=qq[
SELECT
intSeasonID, strSeasonName, intArchiveSeason
FROM
tblSeasons
WHERE
intRealmID = $Data->{'Realm'}
$checkLocked
ORDER BY intSeasonOrder
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my $body='';
my %Seasons=();
my $maxID = 0;
while (my ($id,$name)=$query->fetchrow_array()) {
$maxID = $id;
$Seasons{$id}=$name||'';
}
my $txt_SeasonName= $Data->{'SystemConfig'}{'txtSeason'} || 'Season';
my $txt_SeasonNames= $Data->{'SystemConfig'}{'txtSeasons'} || 'Seasons';
if ($Data->{'BlankSeason'} || $blankseason) {
$Seasons{-1} = join(
q{},
'--',
$Data->{lang}->txt("No $txt_SeasonName"),
'/',
$Data->{lang}->txt($Data->{'LevelNames'}{$Defs::LEVEL_COMP}),
'--',
);
}
else {
$Seasons{-2} = join(
q{},
'--',
$Data->{lang}->txt("No $txt_SeasonName"),
'--',
);
}
if ($Data->{'AllSeasons'} || $allseason) {
$Seasons{-99} = join(
q{},
'--',
$Data->{lang}->txt("All $txt_SeasonNames"),
'--',
);
}
return (\%Seasons, $maxID);
}
sub setDefaultAssocSeasonConfig {
my ($Data) = @_;
my $currentSeasonID = param('currentSeasonID') || 0;
my $newregoSeasonID = param('newregoSeasonID') || 0;
if ($Data->{'clientValues'}{'assocID'} and $Data->{'clientValues'}{'assocID'} != $Defs::INVALID_ID) {
my $txt_Name= $Data->{'SystemConfig'}{'txtSeason'} || 'Season';
my $txt_Names= $Data->{'SystemConfig'}{'txtSeasons'} || 'Seasons';
my $st = qq[
UPDATE tblAssoc
SET intCurrentSeasonID = $currentSeasonID, intNewRegoSeasonID = $newregoSeasonID
WHERE intAssocID =$Data->{'clientValues'}{'assocID'}
];
$Data->{'db'}->do($st);
return qq[ <div class="OKmsg"> $txt_Name Settings updated successfully</div><br>];
}
return '';
}
sub getDefaultAssocSeasons {
my ($Data) = @_;
my $assocID=$Data->{'OverrideAssocID'} || $Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID;
my ($Seasons, $maxSeasonID) =getSeasons($Data);
my $st = qq[
SELECT intCurrentSeasonID, intNewRegoSeasonID, intAllowSeasons, intDefaultMemberTypeID
FROM tblAssoc
WHERE intAssocID = $assocID
];
my $query = $Data->{'db'}->prepare($st);
$query->execute();
my ($currentSeasonID, $newRegoSeasonID, $allowSeasons, $defaultMemberType) = $query->fetchrow_array();
$currentSeasonID ||= $Data->{'SystemConfig'}{'Seasons_defaultCurrentSeason'} || $maxSeasonID;
$newRegoSeasonID ||= $Data->{'SystemConfig'}{'Seasons_defaultNewRegoSeason'} || $maxSeasonID;
my %values = ();
$values{'currentSeasonID'} = $currentSeasonID;
$values{'currentSeasonName'} = $Seasons->{$currentSeasonID} || '';
$values{'newRegoSeasonID'} = $newRegoSeasonID;
$values{'newRegoSeasonName'} = $Seasons->{$newRegoSeasonID} || '';
$values{'allowSeasons'} = $allowSeasons;
$values{'defaultMemberType'} = $defaultMemberType || 0;
return (\%values);
}
sub seasonRollover {
my($Data, $update_type, $members_ref)=@_;
my $cgi=new CGI;
my %params=$cgi->Vars();
my $assocID=$Data->{'clientValues'}{'assocID'} || '';
$assocID ='' if $assocID == $Defs::INVALID_ID;
my $clubID=$Data->{'clientValues'}{'clubID'} || '';
$clubID = 0 if $clubID == $Defs::INVALID_ID;
my $teamID=$Data->{'clientValues'}{'teamID'} || '';
$teamID = 0 if $teamID == $Defs::INVALID_ID;
my $level=$Data->{'clientValues'}{'currentLevel'};
return if !$assocID and $level <=$Defs::LEVEL_ASSOC;
my %Rollover=();
my $assocSeasons = getDefaultAssocSeasons($Data);
my $genAgeGroup ||=new GenAgeGroup ($Data->{'db'},$Data->{'Realm'}, $Data->{'RealmSubType'}, $assocID);
my $fromSeasonID = $params{'Seasons_rolloverFrom'} || 0;
my $MStablename = "tblMember_Seasons_$Data->{'Realm'}";
my $count=0;
for my $mID (@{$members_ref}) {
next if ! $mID;
my $st = qq[
SELECT
DATE_FORMAT(M.dtDOB, "%Y%m%d"), M.intGender, MS.intPlayerStatus, MS.intCoachStatus, MS.intUmpireStatus,
MS.intOfficialStatus, MS.intMiscStatus, MS.intVolunteerStatus, MS.intOther1Status, MS.intOther2Status
FROM
tblMember as M
LEFT JOIN
$MStablename as MS ON (
MS.intMemberID = M.intMemberID
AND MS.intSeasonID = $fromSeasonID
AND MS.intClubID = 0
AND MS.intAssocID = $assocID
AND MS.intMSRecStatus = 1
)
WHERE M.intMemberID = $mID
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute or query_error($st);
my ($DOBAgeGroup, $Gender, $PlayerStatus, $CoachStatus, $UmpireStatus, $OfficialStatus, $MiscStatus, $VolunteerStatus, $Other1Status, $Other2Status) = $qry->fetchrow_array();
my %types=();
$types{'intPlayerStatus'} = 1 if ($PlayerStatus);
$types{'intCoachStatus'} = 1 if ($CoachStatus);
$types{'intUmpireStatus'} = 1 if ($UmpireStatus);
$types{'intOfficialStatus'} = 1 if ($OfficialStatus);
$types{'intMiscStatus'} = 1 if ($MiscStatus);
$types{'intVolunteerStatus'} = 1 if ($VolunteerStatus);
$types{'intOther1Status'} = 1 if ($Other1Status);
$types{'intOther2Status'} = 1 if ($Other2Status);
$types{'intMSRecStatus'} = 1;
$DOBAgeGroup ||= '';
$Gender ||= 0;
my $ageGroupID =$genAgeGroup->getAgeGroup($Gender, $DOBAgeGroup) || 0;
insertMemberSeasonRecord($Data, $mID, $params{'Seasons_rolloverTo'}, $assocID, 0, $ageGroupID, \%types) if ($mID);
$count++;
if ($params{'Seasons_includeClubs'} or $clubID or $teamID) {
my $club_WHERE = $clubID ? qq[ AND MC.intClubID = $clubID] : '';
my $season_WHERE = ($params{'Seasons_rolloverFrom'} > 0) ? qq[ AND MS.intSeasonID = $params{'Seasons_rolloverFrom'} ] : '';
my $team_JOIN = $teamID ? qq[ INNER JOIN tblTeam as T ON (T.intTeamID = $teamID and MC.intClubID = T.intClubID)] : '';
my $st = qq[
SELECT DISTINCT
MC.intClubID, MS.intPlayerStatus, MS.intCoachStatus, MS.intUmpireStatus, MS.intOfficialStatus,
MS.intMiscStatus, MS.intVolunteerStatus, MS.intOther1Status, MS.intOther2Status
FROM tblMember_Clubs as MC
LEFT JOIN $MStablename as MS ON (MS.intMemberID = MC.intMemberID
AND MS.intClubID = MC.intClubID
AND MS.intAssocID = $assocID
AND MS.intMSRecStatus = 1)
$team_JOIN
WHERE MC.intMemberID = $mID
AND MC.intStatus <> $Defs::RECSTATUS_DELETED
$club_WHERE
$season_WHERE
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute or query_error($st);
while (my $dref = $qry->fetchrow_hashref()) {
my %types=();
$types{'intPlayerStatus'} = 1 if ($dref->{intPlayerStatus});
$types{'intCoachStatus'} = 1 if ($dref->{intCoachStatus});
$types{'intUmpireStatus'} = 1 if ($dref->{intUmpireStatus});
$types{'intOfficialStatus'} = 1 if ($dref->{intOfficialStatus});
$types{'intMiscStatus'} = 1 if ($dref->{intMiscStatus});
$types{'intVolunteerStatus'} = 1 if ($dref->{intVolunteerStatus});
$types{'intOther1Status'} = 1 if ($dref->{intOther1Status});
$types{'intOther2Status'} = 1 if ($dref->{intOther2Status});
insertMemberSeasonRecord($Data, $mID, $params{'Seasons_rolloverTo'}, $assocID, $dref->{'intClubID'}, $ageGroupID, \%types);
}
}
if (($params{'Seasons_activateMembers'}) or ($assocSeasons->{'newRegoSeasonID'} and $Data->{'SystemConfig'}{'Seasons_activateMembers'})) {
my $st = qq[
UPDATE tblMember_Associations
SET intRecStatus = $Defs::RECSTATUS_ACTIVE
WHERE intMemberID = $mID
AND intAssocID = $assocID
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute or query_error($st);
}
if ($Data->{'SystemConfig'}{'Seasons_rolloverDateRegistered'}) {
my $st = qq[
UPDATE
tblMember_Associations
SET
dtLastRegistered=NOW()
WHERE
intMemberID = $mID
AND intAssocID = $assocID
LIMIT 1
];
$Data->{'db'}->do($st);
}
if ( $Data->{'Realm'} == 2 and $Data->{'RealmSubType'} == 2 ) {
my $st = qq[
SELECT
SG.intNextGradeID
FROM
tblSchoolGrades AS SG
INNER JOIN tblMember AS M ON ( M.intGradeID=SG.intGradeID AND M.intMemberID=$mID )
];
my $q = $Data->{'db'}->prepare($st);
$q->execute();
my $nextGradeID = $q->fetchrow_array() || 0;
$st = qq[
UPDATE tblMember
SET intGradeID=$nextGradeID
WHERE intMemberID=$mID
];
$Data->{'db'}->do($st);
}
}
return $count;
}
sub seasonToClubRollover {
my($Data, $rolloverClubID, $members_ref)=@_;
my $cgi=new CGI;
my %params=$cgi->Vars();
my ($assocToID, $rolloverAssocName, $clubToID, $rolloverClubName, $toSeasonID) = ListMembers::getRolloverClub($Data, $rolloverClubID);
return if ! $assocToID or ! $clubToID;
my $assocID=$Data->{'clientValues'}{'assocID'} || '';
$assocID ='' if $assocID == $Defs::INVALID_ID;
my $clubID=$Data->{'clientValues'}{'clubID'} || '';
$clubID = 0 if $clubID == $Defs::INVALID_ID;
my $assocSeasons = getDefaultAssocSeasons($Data);
my $genAgeGroup ||=new GenAgeGroup ($Data->{'db'},$Data->{'Realm'}, $Data->{'RealmSubType'}, $assocID);
my $fromSeasonID = $params{'Seasons_rolloverFrom'} || 0;
my $MStablename = "tblMember_Seasons_$Data->{'Realm'}";
my $count=0;
for my $mID (@{$members_ref}) {
next if ! $mID;
my $st = qq[
SELECT
DATE_FORMAT(M.dtDOB, "%Y%m%d"), M.intGender, MS.intPlayerStatus, MS.intCoachStatus, MS.intUmpireStatus,
MS.intOfficialStatus, MS.intMiscStatus, MS.intVolunteerStatus, MS.intOther1Status, MS.intOther2Status
FROM tblMember as M
LEFT JOIN $MStablename as MS ON (MS.intMemberID = M.intMemberID
AND MS.intSeasonID = $fromSeasonID
AND MS.intClubID = 0
AND MS.intAssocID = $assocID
AND MS.intMSRecStatus = 1
)
WHERE M.intMemberID = $mID
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute or query_error($st);
my ($DOBAgeGroup, $Gender, $PlayerStatus, $CoachStatus, $UmpireStatus, $OfficialStatus, $MiscStatus, $VolunteerStatus, $Other1Status, $Other2Status) = $qry->fetchrow_array();
my %types=();
$types{'intPlayerStatus'} = 1 if ($PlayerStatus);
$types{'intCoachStatus'} = 1 if ($CoachStatus);
$types{'intUmpireStatus'} = 1 if ($UmpireStatus);
$types{'intOfficialStatus'} = 1 if ($OfficialStatus);
$types{'intMiscStatus'} = 1 if ($MiscStatus);
$types{'intVolunteerStatus'} = 1 if ($VolunteerStatus);
$types{'intOther1Status'} = 1 if ($Other1Status);
$types{'intOther2Status'} = 1 if ($Other2Status);
$types{'intMSRecStatus'} = 1;
$DOBAgeGroup ||= '';
$Gender ||= 0;
my $ageGroupID =$genAgeGroup->getAgeGroup($Gender, $DOBAgeGroup) || 0;
if ($Data->{'SystemConfig'}{'allowMS_to_Club_rollover_ToSeason'}) {
insertMemberSeasonRecord($Data, $mID, $toSeasonID, $assocToID, 0, $ageGroupID, \%types) if ($mID);
insertMemberSeasonRecord($Data, $mID, $toSeasonID, $assocToID, $clubToID, $ageGroupID, \%types) if ($mID);
}
my $upd_st = qq[
UPDATE
tblMember_Associations
SET
intRecStatus=1
WHERE
intMemberID= $mID
AND intAssocID = $assocToID
LIMIT 1
];
$Data->{'db'}->do($upd_st);
my $ins_st = qq[
INSERT IGNORE INTO tblMember_Associations
(intMemberID, intAssocID, intRecStatus)
VALUES
($mID, $assocToID, 1)
];
$Data->{'db'}->do($ins_st);
$ins_st = qq[
INSERT INTO tblMember_Types
(intMemberID, intTypeID, intSubTypeID, intActive, intAssocID, intRecStatus)
VALUES
($mID,$Defs::MEMBER_TYPE_PLAYER,0,1,$assocToID, 1)
];
$Data->{'db'}->do($ins_st);
# Transactions::insertDefaultRegoTXN($Data->{'db'}, $Defs::LEVEL_MEMBER, $mID, $assocToID);
$ins_st = qq[
INSERT INTO tblMember_Clubs
(intMemberID, intClubID, intStatus)
VALUES
($mID, $clubToID, 1)
];
$Data->{'db'}->do($ins_st);
if ( $Data->{'Realm'} == 2 and $Data->{'RealmSubType'} == 2 ) {
my $st = qq[
SELECT
SG.intNextGradeID
FROM
tblSchoolGrades AS SG
INNER JOIN tblMember AS M ON ( M.intGradeID=SG.intGradeID AND M.intMemberID=$mID )
];
my $q = $Data->{'db'}->prepare($st);
$q->execute();
my $nextGradeID = $q->fetchrow_array() || 0;
$st = qq[
UPDATE tblMember
SET intPlayer=1, intGradeID=$nextGradeID
WHERE intMemberID=$mID
];
$Data->{'db'}->do($st);
}
else {
my $mem_st = qq[UPDATE tblMember SET intPlayer = 1 WHERE intMemberID = $mID LIMIT 1];
$Data->{'db'}->do($mem_st);
}
$upd_st = qq[UPDATE tblMember_Associations SET intRecStatus=0 WHERE intMemberID= $mID AND intAssocID = $assocID LIMIT 1];
$Data->{'db'}->do($upd_st);
$count++;
}
return $count;
}
sub isMemberInSeason {
my($Data, $memberID, $assocID, $clubID, $seasonID)= @_;
return (0, 0) if !$seasonID or !$memberID or !$assocID;
$clubID = 0 if $clubID == $Defs::INVALID_ID;
$clubID ||= 0;
my $MStablename = "tblMember_Seasons_$Data->{'Realm'}";
my $st=qq[
SELECT intMemberSeasonID, intMSRecStatus
FROM $MStablename
WHERE intMemberID =?
AND intAssocID = ?
AND intClubID = ?
AND intSeasonID = ?
LIMIT 1
];
my $qry= $Data->{'db'}->prepare($st);
$qry->execute($memberID, $assocID, $clubID, $seasonID);
my($id, $status) = $qry->fetchrow_array();
$qry->finish();
return ($id and $status == 1) ? ($id, 1) : ($id, $status);
}
sub listSeasons {
my($Data) = @_;
my $lang = $Data->{'lang'};
my $resultHTML = '';
my $txt_Name = $lang->txt($Data->{'SystemConfig'}{'txtSeason'}) || $lang->txt('Season');
my $txt_Names = $lang->txt($Data->{'SystemConfig'}{'txtSeasons'}) || $lang->txt('Seasons');
my $subTypeSeasonOnly = $Data->{'SystemConfig'}->{'OnlyUseSubRealmSeasons'} ? '' : 'OR intRealmSubTypeID= 0';
my $statement=qq[
SELECT
intSeasonID,
strSeasonName,
DATE_FORMAT(dtAdded, '%d/%m/%Y') AS dtAdded,
dtAdded AS dtAdded_RAW,
intAssocID,
intArchiveSeason
FROM tblSeasons
WHERE intRealmID = ?
AND (intAssocID = ? OR intAssocID =0)
AND (intRealmSubTypeID = ? $subTypeSeasonOnly)
ORDER BY intSeasonOrder, strSeasonName
];
my $query = $Data->{'db'}->prepare($statement);
$query->execute(
$Data->{'Realm'},
$Data->{'clientValues'}{'assocID'},
$Data->{'RealmSubType'},
);
my $client = $Data->{'client'};
my @rowdata = ();
while (my $dref= $query->fetchrow_hashref()) {
$dref->{AddedBy} = $dref->{intAssocID}
? $Data->{'LevelNames'}{$Defs::LEVEL_ASSOC}
: $Data->{'LevelNames'}{$Defs::LEVEL_NATIONAL};
push @rowdata, {
id => $dref->{'intSeasonID'} || 0,
SelectLink => "$Data->{'target'}?client=$client&a=SN_DT&seasonID=$dref->{intSeasonID}",
strSeasonName => $dref->{'strSeasonName'} || '',
AddedBy => $dref->{AddedBy} || '',
dtAdded => $dref->{dtAdded} || '',
dtAdded_RAW => $dref->{dtAdded_RAW} || '',
intArchiveSeason => ($dref->{intArchiveSeason}==1)?"Yes":"No",
};
}
my $title=$txt_Names;
my $addlink=qq[<span class = "button-small generic-button"><a href="$Data->{'target'}?client=$client&a=SN_DTA">Add</a></span>];
if (($Data->{'SystemConfig'}{'Seasons_NationalOnly'} and $Data->{'clientValues'}{'authLevel'} < $Defs::LEVEL_NATIONAL)
or ($Data->{'SystemConfig'}{'Seasons_CantAddSeasons'} and $Data->{'clientValues'}{'authLevel'} < $Defs::LEVEL_NATIONAL)) {
$addlink = '';
}
my $modoptions=qq[<div class="changeoptions">$addlink</div>];
$title=$modoptions.$title;
my @headers = (
{
type => 'Selector',
field => 'SelectLink',
},
{
name => $txt_Name,
field => 'strSeasonName',
},
{
name => $Data->{'lang'}->txt('Date Added'),
field => 'dtAdded',
},
{
name => $Data->{'lang'}->txt('Added By'),
field => 'AddedBy',
},
{
name => $Data->{'lang'}->txt('Archived'),
field => 'intArchiveSeason',
width => 20,
},
);
$resultHTML .= showGrid(
Data => $Data,
columns => \@headers,
rowdata => \@rowdata,
gridid => 'grid',
height => 500,
);
if ($Data->{'clientValues'}{'assocID'} and $Data->{'clientValues'}{'assocID'} != $Defs::INVALID_ID) {
$resultHTML = Seasons::viewDefaultAssocSeasons($Data) . "<br><br>$resultHTML";
}
return ($resultHTML,$title);
}
sub getNationalReportingPeriod {
my ($db, $realmID, $subRealmID) = @_;
$subRealmID ||= 0;
my $st = qq[
SELECT
intNationalPeriodID
FROM
tblNationalPeriod
WHERE
intRealmID = ?
AND (intSubRealmID = ? or intSubRealmID = 0)
AND (dtStart < now() AND dtEnd > now())
];
my $q = $db->prepare($st);
$q->execute($realmID, $subRealmID);
my $nationalPeriodID = $q->fetchrow_array();
$nationalPeriodID ||= 0;
return $nationalPeriodID;
}
1;
| facascante/slimerp | fifs/web/Seasons.pm | Perl | mit | 86,495 |
name(ape).
version('6.7.180715').
% see http://www.swi-prolog.org/howto/PackInfo.html
download('https://github.com/Attempto/APE/releases/*.zip').
title('Parser for Attempto Controlled English (ACE)').
author('Kaarel Kaljurand','kaljurand@gmail.com').
author('Norbert E. Fuchs','fuchs@ifi.uzh.ch').
author('Tobias Kuhn','kuhntobias@gmail.com').
home('https://github.com/Attempto/APE').
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/ape/pack.pl | Perl | mit | 389 |
/* Part of LogicMOO Base Logicmoo Path Setups
% ===================================================================
% File '$FILENAME.pl'
% Purpose: An Implementation in SWI-Prolog of certain debugging tools
% Maintainer: Douglas Miles
% Contact: $Author: dmiles $@users.sourceforge.net ;
% Version: '$FILENAME.pl' 1.0.0
% Revision: $Revision: 1.1 $
% Revised At: $Date: 2002/07/11 21:57:28 $
% Licience: LGPL
% ===================================================================
*/
% File: /opt/PrologMUD/pack/logicmoo_base/prolog/logicmoo/util/logicmoo_util_body_nauts.pl
:- module(logicmoo_util_body_nauts,
[ enable_nautifiers/0,
do_nautifier/4,
disable_nautifiers/0]).
:- style_check(+singleton).
:- style_check(+discontiguous).
% :- style_check(-atom).
% :- style_check(-naut).
/*
delete_eq([],Item,[]):-!,dmsg(warn(delete_eq([],Item,[]))).
delete_eq([L|List],Item,List):-Item==L,!.
delete_eq([L|List],Item,[L|ListO]):-delete_eq(List,Item,ListO),!.
% user:term_expansion(I,O):- current_predicate(logicmoo_bugger_loaded/0),not(t_l:into_form_code),e2c_term_expansion(I,O).
*/
:- ensure_loaded(logicmoo_util_body_file_scope).
:-meta_predicate(do_nautifier(+,+,+,-)).
do_nautifier(_,_ ,A,A):- ( \+ compound(A) ; is_list(A)),!.
do_nautifier(Head,Vars ,(DECL,BodI),BodO):- compound(DECL),DECL=cycnaut(StrVar), !,
do_nautifier(Head,Vars,nautArg(StrVar,BodI),BodO).
do_nautifier(_,_ ,call(H),call(H)):-!.
do_nautifier(Head,Vars,nautArg(StrVar,BodI),nautArgUC(StrVar,NewVar,OOO)):- !, vsubst(BodI,StrVar,NewVar,BodO),
do_nautifier(Head,Vars,BodO,OOO).
do_nautifier(Head,[StrVar|Vars],BodI,BodO):- !, do_nautifier(Head,Vars,nautArg(StrVar,BodI),BodO).
do_nautifier(Head,Vars,V^(H),V^(HO)):- !,do_nautifier(Head,Vars,H,HO).
:- enable_body_reorder.
do_nautifier(Head,Vars,BodI,BodO):- compound(BodI),functor(BodI,F, _),
reorderBody(cyckb_t_e2c(argIsa,F,N,NAUTType),fail,ttNAUTType(NAUTType)),arg(N,BodI,StrVar),!,
do_nautifier(Head,Vars,nautArg(StrVar,BodI),BodO).
/*
do_nautifier(Head,Vars,(H,L),(HO,LO)):-!, do_nautifier(Head,Vars,H,HO),do_nautifier(Head,Vars,L,LO).
do_nautifier(Head,Vars,(C->H;L),(CO->HO;LO)):-!, do_nautifier(Head,Vars,C,CO),do_nautifier(Head,Vars,H,HO),do_nautifier(Head,Vars,L,LO).
do_nautifier(Head,Vars,(H->L),(HO->LO)):-!, do_nautifier(Head,Vars,H,HO),do_nautifier(Head,Vars,L,LO).
do_nautifier(Head,Vars,(H;L),(HO;LO)):-!, do_nautifier(Head,Vars,H,HO),do_nautifier(Head,Vars,L,LO).
do_nautifier(Head,Vars,'{}'(H),'{}'(HO)):- !,do_nautifier(Head,Vars,H,HO).
*/
do_nautifier(Head,Vars,H,HO):- H=..HL, must_maplist(do_nautifier(Head,Vars),HL,HOL),HO=..HOL.
ttNAUTType('CharacterNAUT').
ttNAUTType('SubLNAUT').
ttNAUTType('SubLListOfNAUTs').
% ttNAUTType(['ListOfTypeFn', X]):-atom(X),ttNAUTType(X).
nautArg(User,CallWithUser):- dtrace,vsubst(no_repeats(CallWithUser),User,Cyc,CallWithCyc),!, (ground(User) -> (ssz(User,Cyc),CallWithCyc) ; (CallWithCyc, ssz(User,Cyc))).
nautArgUC(User,Cyc,CallWithCyc):- must_det(var(Cyc)),!,nautArgUC2(User,Cyc,CallWithCyc).
nautArgUC2(User,Cyc,CallWithCyc):- var(User),!,CallWithCyc,cycNAUTToNAUT(Cyc,User).
nautArgUC2([User,U2|MORE],Cyc,CallWithCyc):- Cyc=[User,U2|MORE],!,CallWithCyc.
nautArgUC2([User],Cyc,CallWithCyc):- Cyc=User,!,CallWithCyc,atom(Cyc).
cycNAUTToNAUT(Cyc,User):- (atom(Cyc)->User=[Cyc];User=Cyc),!.
:- set_prolog_flag(do_nautifier,false).
enable_nautifiers:- enable_in_file(do_nautifier).
disable_nautifiers:- disable_in_file(do_nautifier).
:- if(true).
% some tests
:- endif.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_utils/prolog/body_reordering/logicmoo_util_body_nauts.pl | Perl | mit | 3,530 |
#!/usr/bin/env perl
# Shashwat Deepali Nagar, 2016
# Jordan Lab, Georgia Tech
# Perl script to find and replace words/phrases in a Docx document
use strict;
my @fileList = ("SampleDoc.docx"); # Populate this list with filenames
my $find = "TestWord"; # Substitute with word to be replaced
my $replace = "Genius"; # Substitute with replacement
foreach my $file (@fileList) {
system("cp $file sample.zip");
system("unzip sample.zip");
system("sed -i 's/$find/$replace/g' word/document.xml");
system("zip -r opFile.zip word/ docProps/ \[Content_Types\].xml _rels/");
system("cp opFile.zip $file");
# Delete all generated files
system("rm -r _rels/");
system("rm -r docProps/");
system("rm opFile.zip");
system("rm sample.zip");
system("rm -r word/");
system("rm \[Content_Types\].xml");
}
| ShashwatDNagar/FindReplace_Docx | FindReplace_docx.pl | Perl | mit | 816 |
#############################################################################
#
# Apache::Session::Store::DBI
# A base class for the MySQL, Postgres, and other DBI stores
# Copyright(c) 2000, 2004 Jeffrey William Baker (jwbaker@acm.org)
# Distribute under the Perl License
#
############################################################################
package Apache::Session::Store::DBI;
use strict;
use DBI;
use vars qw($VERSION);
$VERSION = '1.02';
$Apache::Session::Store::DBI::TableName = "sessions";
sub new {
my $class = shift;
return bless { table_name => $Apache::Session::Store::DBI::TableName }, $class;
}
sub insert {
my $self = shift;
my $session = shift;
$self->connection($session);
local $self->{dbh}->{RaiseError} = 1;
if (!defined $self->{insert_sth}) {
$self->{insert_sth} =
$self->{dbh}->prepare_cached(qq{
INSERT INTO $self->{'table_name'} (id, a_session) VALUES (?,?)});
}
$self->{insert_sth}->bind_param(1, $session->{data}->{_session_id});
$self->{insert_sth}->bind_param(2, $session->{serialized});
$self->{insert_sth}->execute;
$self->{insert_sth}->finish;
}
sub update {
my $self = shift;
my $session = shift;
$self->connection($session);
local $self->{dbh}->{RaiseError} = 1;
if (!defined $self->{update_sth}) {
$self->{update_sth} =
$self->{dbh}->prepare_cached(qq{
UPDATE $self->{'table_name'} SET a_session = ? WHERE id = ?});
}
$self->{update_sth}->bind_param(1, $session->{serialized});
$self->{update_sth}->bind_param(2, $session->{data}->{_session_id});
$self->{update_sth}->execute;
$self->{update_sth}->finish;
}
sub materialize {
my $self = shift;
my $session = shift;
$self->connection($session);
local $self->{dbh}->{RaiseError} = 1;
if (!defined $self->{materialize_sth}) {
$self->{materialize_sth} =
$self->{dbh}->prepare_cached(qq{
SELECT a_session FROM $self->{'table_name'} WHERE id = ?});
}
$self->{materialize_sth}->bind_param(1, $session->{data}->{_session_id});
$self->{materialize_sth}->execute;
my $results = $self->{materialize_sth}->fetchrow_arrayref;
if (!(defined $results)) {
die "Object does not exist in the data store";
}
$self->{materialize_sth}->finish;
$session->{serialized} = $results->[0];
}
sub remove {
my $self = shift;
my $session = shift;
$self->connection($session);
local $self->{dbh}->{RaiseError} = 1;
if (!defined $self->{remove_sth}) {
$self->{remove_sth} =
$self->{dbh}->prepare_cached(qq{
DELETE FROM $self->{'table_name'} WHERE id = ?});
}
$self->{remove_sth}->bind_param(1, $session->{data}->{_session_id});
$self->{remove_sth}->execute;
$self->{remove_sth}->finish;
}
1;
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/Apache/Session/Store/DBI.pm | Perl | mit | 2,961 |
#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use XML::Parser;
use FindBin;
use Image::SVG::Path 'extract_path_info';
use utf8;
my $dir = "$FindBin::Bin/kanjivg";
# The grep only allows the "normal" files from the complete list of
# files.
my @files = grep /\/[0-9a-f]+\.svg$/, <$dir/*.svg>;
my %stroke_types;
my %global;
my %angles;
# List of errors which are known to come from bad information about
# stroke types.
my @known_bad_elements = qw/冬 羽 尽 辛 手 羊 冫 半/;
my %known_bad_elements = map {$_ => 1} @known_bad_elements;
#print keys %known_bad_elements;
$global{known_bad_elements} = \%known_bad_elements;
my $parser = XML::Parser->new (
Handlers => {
Start => sub { &{handle_start} (\%global, @_) },
},
);
# This doesn't let us use current_line.
#$global{parser} = $parser;
for my $file (@files) {
#for my $file (qw!kanjivg/087bd.svg!) {
$global{file} = $file;
$global{bad_element} = undef;
$parser->parsefile ($file);
}
#for my $t (sort keys %stroke_types) {
# print "$t\n";
#}
my %average;
for my $t (sort keys %angles) {
if ($t eq 'None') {
next;
}
my $total_angle = 0;
my $n = 0;
for my $se (@{$angles{$t}}) {
my ($start, $end) = @$se;
my $angle = atan2 ($end->[1] - $start->[1], $end->[0] - $start->[0]);
$total_angle += $angle;
$n++;
}
$average{$t} = $total_angle / $n;
# The following line prints out the "type" field and the average angle
# in radians.
# print "$t $average{$t}\n";
}
my $limit = 1.0;
for my $t (sort keys %angles) {
if ($t eq 'None') {
next;
}
for my $se (@{$angles{$t}}) {
my ($start, $end, $location) = @$se;
my $angle = atan2 ($end->[1] - $start->[1], $end->[0] - $start->[0]);
if ($angle - $average{$t} > $limit) {
print $location, "more than $limit radian from average.\n"
}
}
}
exit;
sub handle_start
{
my ($global_ref, $parser, $element, %attr) = @_;
if ($global_ref->{bad_element}) {
return;
}
# Use the expat parser so we can use current_line.
$global_ref->{parser} = $parser;
if ($element eq 'path') {
gather_path_info ($global_ref, \%attr);
}
elsif ($element eq 'g') {
if ($attr{id} =~ /^([0-9a-f]+)$/) {
$global_ref->{kanji_id} = $attr{id};
}
my $el = $attr{"kanjivg:element"};
# print "element $el\n";
if (defined $el) {
if ($global_ref->{known_bad_elements}->{$el}) {
# print "Known bad element $el in $global_ref->{file}.\n";
$global_ref->{bad_element} = 1;
}
}
}
}
# Get the location for warning messages.
sub location
{
my ($global) = @_;
my $l = '';
$l .= $global->{file};
$l .= ":";
$l .= $global->{parser}->current_line ();
$l .= ": ";
return $l;
}
sub gather_path_info
{
my ($global_ref, $attr_ref) = @_;
my $type = $attr_ref->{'kanjivg:type'};
if (! $type) {
warn location ($global_ref), "no type.\n";
return;
}
$type =~ s/([^[:ascii:]])/"{" . sprintf ("%X", ord $1) . "}"/ge;
$stroke_types{$type}++;
my $d = $attr_ref->{d};
if (! $d) {
warn location ($global_ref), "no path.\n";
return;
}
my @info = extract_path_info ($d, {absolute => 1, no_shortcuts => 1});
my $start = $info[0]->{point};
my $end = $info[-1]->{end};
if (! $start || ! $end) {
warn location ($global_ref), "parse failed for '$d': no start/end";
return;
}
push @{$angles{$type}}, [$start, $end, location ($global_ref)];
}
| Belxjander/Perception-IME | Resources/KanjiVG/check-all-strokes.pl | Perl | mit | 3,674 |
package PrefixRC::Status;
use strict;
use warnings;
use Moo;
has pid_dir => ( is => 'rw' );
has program => ( is => 'rw' );
sub BUILD {
my $self = shift;
}
sub run {
my $self = shift;
my $action = shift;
$action = '' unless $action;
if ( $action eq 'start' ) {
$self->_print_process($action);
}
elsif ( $action eq 'stop' ) {
$self->_print_process( $action, shift );
}
elsif ( $action eq 'pid' ) {
return $self->_read_pid;
}
elsif ( $action eq 'check' ) {
return $self->_check_okay;
}
else {
$self->_print_system;
}
}
sub get_pid {
my $self = shift;
return $self->_read_pid;
}
sub _print_system {
my $self = shift;
opendir( my $dh, $self->pid_dir );
while ( readdir($dh) ) {
next if $_ =~ /^\./;
$self->_print_status($_);
}
close($dh);
}
sub _print_status {
my $self = shift;
$self->program(shift);
if ( !$self->_read_pid ) {
$self->_pretty_print( 33, 'stopped' );
}
else {
my $okay = $self->_check_okay;
my $code = $okay ? 32 : 31;
my $status = $okay ? 'started' : 'crashed';
$self->_pretty_print( $code, $status );
}
}
sub _print_process {
my $self = shift;
my $action = shift;
my $okay = shift;
$okay = $self->_check_okay unless $okay;
my $code = $okay ? 32 : 31;
$action .= $okay ? ' success' : ' failed';
$self->_pretty_print( $code, $action );
}
sub _pretty_print {
my $self = shift;
my $code = shift;
my $action = shift;
printf( "%-49s %30s\n",
$self->program, "\033[$code" . "m[$action]\033[0m" );
}
sub _read_pid {
my $self = shift;
if ( -f $self->pid_dir . $self->program ) {
open my $rh, '<', $self->pid_dir . $self->program or die "$!";
my $pid = <$rh>;
close($rh);
return $pid;
}
else {
$self->_pretty_print( 31, "no process found" );
exit 1;
}
}
sub _check_okay {
my $self = shift;
my $pid = $self->_read_pid;
return kill 0, $pid;
}
1;
| adjust/PrefixRC | lib/PrefixRC/Status.pm | Perl | mit | 2,111 |
use strict;
use Data::Dumper;
use Carp;
#
# This is a SAS Component
#
=head1 NAME
aliases_to_fids
=head1 SYNOPSIS
aliases_to_fids [arguments] < input > output
=head1 DESCRIPTION
aliases_to_fids is used to search for the feature ids that a set of given
aliases maps to.
Example:
aliases_to_fids [arguments] < input > output
The standard input should be a tab-separated table (i.e., each line
is a tab-separated set of fields). Normally, the last field in each
line would contain the identifer. If another column contains the identifier
use
-c N
where N is the column (from 1) that contains the subsystem.
This is a pipe command. The input is taken from the standard input,
and the output is to the standard output. For each input line, there
can be many output lines, one per feature. The feature id is added to
the end of the line.
=head1 COMMAND-LINE OPTIONS
Usage: aliases_to_fids [arguments] < input > output
-source Only pull aliases with the given source
-c num Select the identifier from column num
-i filename Use filename rather than stdin for input
=head1 AUTHORS
L<The SEED Project|http://www.theseed.org>
=cut
our $usage = "usage: aliases_to_fids [-c column] [-source source] < input > output";
use Bio::KBase::CDMI::CDMIClient;
use Bio::KBase::Utilities::ScriptThing;
my $column;
my $input_file;
my $source;
my $kbO = Bio::KBase::CDMI::CDMIClient->new_for_script('c=i' => \$column,
'source=s' => \$source,
'i=s' => \$input_file);
if (! $kbO) { print STDERR $usage; exit }
my $ih;
if ($input_file)
{
open $ih, "<", $input_file or die "Cannot open input file $input_file: $!";
}
else
{
$ih = \*STDIN;
}
while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, 10, $column)) {
my @h = map { $_->[0] } @tuples;
my $h;
if ($source)
{
$h = $kbO->aliases_to_fids_by_source(\@h, $source);
}
else
{
$h = $kbO->aliases_to_fids(\@h);
}
for my $tuple (@tuples) {
#
# Process output here and print.
#
my ($id, $line) = @$tuple;
my $v = $h->{$id};
if (! defined($v))
{
print STDERR $line,"\n";
}
elsif (ref($v) eq 'ARRAY')
{
foreach $_ (@$v)
{
print "$line\t$_\n";
}
}
else
{
print "$line\t$v\n";
}
}
}
__DATA__
| kbase/kb_seed | scripts/aliases_to_fids.pl | Perl | mit | 2,450 |
#!/usr/local/bin/perl
#-------------------------------------
# MakeDB4
# (C)1999 Harvard University
#
# W. S. Lane/P. Djeu
#
# v3.1a
#
# licensed to Finnigan
#-------------------------------------
################################################
# Created: 7/18/00 by Peter Djeu
# Description: A web wrapper around the makedb4.exe indexing program. Writes the parameters selected on the web
# page to the parameters file, and then calls the script runmakedb4.pl (via SeqComm when using a remote makedb4
# machine, and directly otherwise) to actually run the .exe.
#
# CGI Parameters:
# Database - the name of the database
# proceed - 0 for stay on first page, one for execute makedb4.exe
################################################
# find and read in standard include file
{
$0 =~ m!(.*)\\([^\\]*)$!;
do ("$1/development.pl");
my $path = $0;
$path =~ s!\\!/!g;
$path =~ s!^(.*)/[^/]+/.*$!$1/etc!;
unshift (@INC, "$path");
require "microchem_include.pl";
require "microchem_form_defaults.pl";
require "html_bio_include.pl";
require "html_include.pl";
}
#################################################
# Default Settings
# size_estimate_constants
#
#
# N.B. To force the indexing to run, lower these values so that diskspace error checking doesn't kick in.
#
# Still under testing because haven't thought of an algorithm to determine the size of the final index.
# Based on the number of internal cleavage sites, multiply the actual db's size by this constant to
# get the amount of disk space makedb4 believes it needs. The peptide mass range and peptide size range
# should also be factored in later.
# This estimate is for the final size of the index, which is multiplied by 3 to determine the total disk space (the
# factor of 3 is not included in these constants, it is hard coded below)
# -- 8-25-00, P.Djeu
%size_estimate_constants = (
"0" => $DEFS_MAKEDB{"Growth Constant 0"},
"1" => $DEFS_MAKEDB{"Growth Constant 1"},
"2" => $DEFS_MAKEDB{"Growth Constant 2"},
"3" => $DEFS_MAKEDB{"Growth Constant 3"},
"4" => $DEFS_MAKEDB{"Growth Constant 4"},
"5" => $DEFS_MAKEDB{"Growth Constant 5"}
);
$paramsfile_name = "makedb.params";
$webserver_dbdir = $dbdir;
$auto_distribute = $DEFS_MAKEDB{"Auto-distribute"} eq "yes" ? "checked" : "";
# This must be done before multiple sequest hosts is done, or else $dbdir will be incorrect
&get_dbases;
if ($multiple_sequest_hosts) {
require "seqcomm_include.pl";
$runOnServer = $DEFAULT_MAKEDB_AND_DOWNLOAD_SERVER;
#remote run. Note that this script is always run on the webserver => $ENV{'COMPUTERNAME'} = $webserver
if ($DEFAULT_MAKEDB_AND_DOWNLOAD_SERVER ne $webserver)
{
# Set $dbdir with include file on remote host, must use -e conditional or else error won't appear (due to 'require' short-circuiting?)
if (-e "\\\\$runOnServer$remote_webseqcommdir/seqcomm_var_$runOnServer.pl") {
require "\\\\$runOnServer$remote_webseqcommdir/seqcomm_var_$runOnServer.pl";
} else {
&error("Cannot find \\\\$runOnServer$remote_webseqcommdir/seqcomm_var_$runOnServer.pl: $!", 1);
}
}
#local run on the webserver
else
{
# Set $dbdir with include file on remote host, must use -e conditional or else error won't appear (due to 'require' short-circuiting?)
if (-e "$seqcommdir/seqcomm_var_$runOnServer.pl") {
require "$seqcommdir/seqcomm_var_$runOnServer.pl";
} else {
&error("Cannot find $seqcommdir/seqcomm_var_$runOnServer.pl: $!", 1);
}
}
$remote_db = "\\\\$runOnServer/Database";
$out_params = "$remote_db/makedb/$paramsfile_name";
if (!(defined $makedb_dir)) {
&error("SeqComm params file for the MakeDB4 machine needs to define \$makedb_dir", 1);
} elsif ($makedb_dir eq "") {
&error("No MakeDB4 output dir specified in the SeqComm params file for $runOnServer; $runOnServer is most likely NOT a MakeDB4 machine", 1);
}
} else {
# Use local $dbdir from standard include file
$runOnServer = $ENV{'COMPUTERNAME'};
$out_params = "$dbdir/makedb/$paramsfile_name";
$scratch_dbdir = "$dbdir";
}
################################################
# end Defailt Settings
#######################################
# Initial output
# this may or may not be appropriate; you might prefer to put a separate call to the header
# subroutine in each control branch of your program (e.g. in &output_form)
&cgi_receive;
&MS_pages_header("DB Indexer","#8800FF", "tabvalues=MakeDB4&MakeDB4:\"$makedb4\"&FastaIdx:\"$fastaidx_web\"");
$db = $FORM{"Database"};
#######################################
# Fetching defaults values
#
# The defaults for the web page are found in either:
# 1. The form defaults file (see Site Administration on the home page)
# 2. The makedb template file (see microchem_var.pl).
#
# In cases of redundancy, the order of precedence is 1., followed by 2.
#######################################
# Flow control
&output_form unless (defined $FORM{"Database"} && $FORM{"proceed"});
&launch_remote;
exit 0;
######################################
# Main action
# Use the default template to make a new copy before executing makedb4.exe. Also, prepare the command line args for proper
# input (i.e. strip unspecified args).
sub launch_remote {
# Check to see if ftp_fastadb.pl is running, if it is, postpone indexing
$stamp = "$webserver_dbdir/.ftp_fastadb_running";
if (open(STAMP, ">$stamp")) {
if (!(flock STAMP, ($LOCK_EX | $LOCK_NB))) {
# File locked by ftp_fastadb.pl, which means it is running
&error("Database Autodownload is currently running. Unable to launch MakeDB4.");
close STAMP;
} else {
close STAMP;
unlink "$stamp";
}
}
# Check to see if itself is running, if it is, postpone indexing
$stamp = "$webserver_dbdir/.runmakedb_running";
if (open(STAMP, ">$stamp")) {
unless (flock STAMP, ($LOCK_EX | $LOCK_NB)) {
# File locked by ftp_fastadb.pl, which means it is running
&error("Another instance of MakeDB4 is already running. Please wait until it finishes.");
}
close STAMP;
}
# Check to make sure database exits on the indexing server
if ($multiple_sequest_hosts) {
if (!(-e "$remote_db/$db")) {
&error("The remote database $remote_db/$db could not be found");
}
} else {
if (!(-e "$dbdir/$db")) {
&error("The database $dbdir/$db could not be found");
}
}
# Make checks for diskspace
$cmdline = ($runOnServer eq $ENV{'COMPUTERNAME'}) ? "$dbdir" : "\\\\$runOnServer\\Database";
$cmdline =~ s!/!\\!gi; #make sure directory paths are properly formated
$_ = `dir $cmdline`;
($bytes_free) = /([\d,]+) bytes free/;
$bytes_free =~ s/,//g;
$temp_path = ($multiple_sequest_hosts) ? "$remote_db/$db" : "$dbdir/$db";
$dbsize = &dos_file_size("$temp_path");
if ($dbsize <= 0) {
&error("Could not check the size of $temp_path. MakeDB4 halted.");
}
$growth_constant = $size_estimate_constants{"$FORM{'max_num_internal_cleavage_sites'}"};
# The hard coded 3 is for: the final index itself, the sort files, and alltryptic.txt, each about the size
# of the final index. (3/01) wsl changed to 2.8 for trials)
$total_needed = &precision($dbsize * $growth_constant * 2.8, 0);
if ($total_needed > $bytes_free) {
# If this form value is specified, run regardless of diskspace failure. Just print a warning message
if ($FORM{"diskspace_override"}) {
print <<EOF;
<br>Warning: Not enough disk space to index $temp_path.<br><br>
Using the growth factor of <b>$size_estimate_constants{"$FORM{'max_num_internal_cleavage_sites'}"}</b> (corresponding
to <b>$FORM{'max_num_internal_cleavage_sites'}</b> max internal cleavage site(s)),
an estimated <b>$total_needed</b> bytes were needed, and only <b>$bytes_free</b> bytes were available.<br><br>
Running MakeDB4 anyways.
EOF
# Now, proceed to altering the params file
} else {
$err_msg = <<EOF;
Not enough disk space to index $temp_path.<br><br>
Using the growth factor of <b>$size_estimate_constants{"$FORM{'max_num_internal_cleavage_sites'}"}</b> (corresponding
to <b>$FORM{'max_num_internal_cleavage_sites'}</b> max internal cleavage site(s)),
an estimated <b>$total_needed</b> bytes were needed, and only <b>$bytes_free</b> bytes were available. MakeDB4 halted.<br><br>
The growth factor can be changed in the Form Defaults Editor.
EOF
&error($err_msg); # Stop the script
}
}
open (PARAMS, "<$default_makedbparams") || &error ("Could not open $paramsfile_name template. $!");
@lines = <PARAMS>;
close (PARAMS);
$whole = join("",@lines);
# Alter new params file if default is not picked, else make an exact copy of the template (don't do s/// modifications)
if ($db ne "$paramsfile_name") {
($seq_info,$enz_info) = split(/\[SEQUEST_ENZYME_INFO\]*.\n/, $whole);
# get rid of base pathname if it exists
if (defined $FORM{"temp_dir"}) {
$temp_dir = $FORM{"temp_dir"};
# remove shell meta-characters
$temp_dir =~ tr/A-Za-z0-9\/-_//cd;
} else {
$temp_dir = $DEFS_MAKEDB{"Temp Directory"};
}
# Remove terminating slash in the directory path since it will be added in this file
$temp_dir =~ s!(/$|\\$)!!;
if (defined $FORM{"out_dir"}) {
$out_dir = $FORM{"out_dir"};
# remove shell meta-characters
$out_dir =~ tr/A-Za-z0-9\/-_//cd;
} else {
$out_dir = $DEFS_MAKEDB{"Index Output Directory"};
}
# Remove terminating slash in the directory path since it will be added in this file
$out_dir =~ s!(/$|\\$)!!;
if (!$multiple_sequest_hosts) {
if (!(-d "$temp_dir")) {
&error("The temp directory $temp_dir could not be found.");
}
if (!(-d "$out_dir")) {
&error("The index output directory $out_dir could not be found.");
}
}
# For multiple sequest hosts, some of the drives are not web-accessible, so there is no real
# way to check if they exist or not -- we will just have to assume the user-specified paths
# are accurate
# Get popup settings from hidden form elements, do for all 3 windows
# input from add-mass pop-up window
$add_Cterm = $FORM{"add_Cterm"};
$add_Nterm = $FORM{"add_Nterm"};
$add_G = $FORM{"add_G"};
$add_A = $FORM{"add_A"};
$add_S = $FORM{"add_S"};
$add_P = $FORM{"add_P"};
$add_V = $FORM{"add_V"};
$add_T = $FORM{"add_T"};
$add_C = $FORM{"add_C"};
$add_L = $FORM{"add_L"};
$add_I = $FORM{"add_I"};
$add_X = $FORM{"add_X"};
$add_N = $FORM{"add_N"};
$add_O = $FORM{"add_O"};
$add_B = $FORM{"add_B"};
$add_D = $FORM{"add_D"};
$add_Q = $FORM{"add_Q"};
$add_K = $FORM{"add_K"};
$add_Z = $FORM{"add_Z"};
$add_E = $FORM{"add_E"};
$add_M = $FORM{"add_M"};
$add_H = $FORM{"add_H"};
$add_F = $FORM{"add_F"};
$add_R = $FORM{"add_R"};
$add_Y = $FORM{"add_Y"};
$add_W = $FORM{"add_W"};
# input from enzyme-info pop-up window
# find maximum enzyme number provided in form input
$max_enznum = 0;
foreach (keys %FORM) {
if (/^enz_.*?(\d+)$/) {
$max_enznum = $1 if ($1 > $max_enznum);
}
}
foreach $num (1..$max_enznum)
{
$enz_name[$num] = $FORM{"enz_name$num"};
$enz_name[$num] =~ s/ /_/g; # spaces are allowed in form input, but in sequest.params they must be _
$enz_offset[$num] = $FORM{"enz_offset$num"};
$enz_sites[$num] = $FORM{"enz_sites$num"};
$enz_no_sites[$num] = $FORM{"enz_no_sites$num"};
}
# end of getting form info
# autodetect the database type
if ($FORM{"protein_or_nucleotide_dbase"} == 2) {
$FORM{"protein_or_nucleotide_dbase"} = &get_dbtype("$webserver_dbdir/$db");
}
# If the database is protein, than there is no need for a nucleotide reading frame
if (!$FORM{"protein_or_nucleotide_dbase"}) {
$FORM{"nucleotide_reading_frames"} = 0;
}
# if certain diff mods are not specified, use the default placeholders:
# Mod AA: 0.0000 M
# Mod AA2: 0.0000 C
# Mod AA3: 0.0000 X
if ((!(defined $FORM{"ModifiedAA1"})) || ($FORM{"ModifiedAA1"} =~ /^\s*$/)) {
$FORM{"ModifiedAA1"} = "M";
$FORM{"ModifiedAA1Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA2"})) || ($FORM{"ModifiedAA2"} =~ /^\s*$/)) {
$FORM{"ModifiedAA2"} = "C";
$FORM{"ModifiedAA2Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA3"})) || ($FORM{"ModifiedAA3"} =~ /^\s*$/)) {
$FORM{"ModifiedAA3"} = "X";
$FORM{"ModifiedAA3Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA4"})) || ($FORM{"ModifiedAA4"} =~ /^\s*$/)) {
$FORM{"ModifiedAA4"} = "X";
$FORM{"ModifiedAA4Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA5"})) || ($FORM{"ModifiedAA5"} =~ /^\s*$/)) {
$FORM{"ModifiedAA5"} = "X";
$FORM{"ModifiedAA5Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA6"})) || ($FORM{"ModifiedAA6"} =~ /^\s*$/)) {
$FORM{"ModifiedAA6"} = "X";
$FORM{"ModifiedAA6Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA7"})) || ($FORM{"ModifiedAA7"} =~ /^\s*$/)) {
$FORM{"ModifiedAA7"} = "X";
$FORM{"ModifiedAA7Num"} = "0.0000";
}
if (!((defined $FORM{"ModifiedAA8"})) || ($FORM{"ModifiedAA8"} =~ /^\s*$/)) {
$FORM{"ModifiedAA8"} = "X";
$FORM{"ModifiedAA8Num"} = "0.0000";
}
$_ = $seq_info;
# Begin editing makedb.params file. Most directory paths come from the Machine-specific SeqComm var file
s/^(database_name\s*=\s*)(.+?)(\s*;|\s*$)/$1$dbdir\\$db$3/m;
s/^(sort_directory\s*=\s*)(.+?)(\s*;|\s*$)/$1$temp_dir$3/m;
s/^(sort_program\s*=\s*)(.+?)(\s*;|\s*$)/$1$makedb_dir\\sort.exe$3/m;
s/^(enzyme_number\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"Enzyme"}$3/m;
s/^(protein_or_nucleotide_dbase\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"protein_or_nucleotide_dbase"}$3/m;
s/^(nucleotide_reading_frames\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"nucleotide_reading_frames"}$3/m;
s/^(use_mono\/avg_masses\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"use_mono\/avg_masses"}$3/m;
s/^(min_peptide_mass\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"min_peptide_mass"}$3/m;
s/^(max_peptide_mass\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"max_peptide_mass"}$3/m;
s/^(min_peptide_size\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"min_peptide_size"}$3/m;
s/^(max_peptide_size\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"max_peptide_size"}$3/m;
s/^(max_num_internal_cleavage_sites\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"max_num_internal_cleavage_sites"}$3/m;
s/^(max_num_differential_AA_per_mod\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"max_num_diff_aa_per_mod"}$3/m;
s/^(diff_search_options\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"ModifiedAA1Num"} $FORM{"ModifiedAA1"} $FORM{"ModifiedAA2Num"} $FORM{"ModifiedAA2"} $FORM{"ModifiedAA3Num"} $FORM{"ModifiedAA3"} $FORM{"ModifiedAA4Num"} $FORM{"ModifiedAA4"} $FORM{"ModifiedAA5Num"} $FORM{"ModifiedAA5"} $FORM{"ModifiedAA6Num"} $FORM{"ModifiedAA6"}$3/m;
# This has been added recently, so if it doesn't exist, add it to the sequest.params file.
if (m/^term_diff_search_options\s*=\s*.+?(\s*;|\s*$)/m) {
s/^(term_diff_search_options\s*=\s*)(.+?)(\s*;|\s*$)/$1$FORM{"ModifiedAA8Num"} $FORM{"ModifiedAA7Num"}$3/m;
} else {
s/^(diff_search_options.*?\n)/${1}term_diff_search_options = $FORM{"ModifiedAA8Num"} $FORM{"ModifiedAA7Num"}; c term, n term diff mods\n/m;
}
# replace parameters in add-mass portion of sequest.params
s/^(add_Cterm_peptide\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_Cterm$3/m;
s/^(add_Nterm_peptide\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_Nterm$3/m;
s/^(add_G_Glycine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_G$3/m;
s/^(add_A_Alanine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_A$3/m;
s/^(add_S_Serine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_S$3/m;
s/^(add_P_Proline\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_P$3/m;
s/^(add_V_Valine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_V$3/m;
s/^(add_T_Threonine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_T$3/m;
s/^(add_C_Cysteine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_C$3/m;
s/^(add_L_Leucine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_L$3/m;
s/^(add_I_Isoleucine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_I$3/m;
s/^(add_X_LorI\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_X$3/m;
s/^(add_N_Asparagine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_N$3/m;
s/^(add_O_Ornithine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_O$3/m;
s/^(add_B_avg_NandD\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_B$3/m;
s/^(add_D_Aspartic_Acid\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_D$3/m;
s/^(add_Q_Glutamine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_Q$3/m;
s/^(add_K_Lysine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_K$3/m;
s/^(add_Z_avg_QandE\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_Z$3/m;
s/^(add_E_Glutamic_Acid\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_E$3/m;
s/^(add_M_Methionine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_M$3/m;
s/^(add_H_Histidine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_H$3/m;
s/^(add_F_Phenylalanine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_F$3/m;
s/^(add_R_Arginine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_R$3/m;
s/^(add_Y_Tyrosine\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_Y$3/m;
s/^(add_W_Tryptophan\s*=\s*)(.+?)(\s*;|\s*$)/$1$add_W$3/m;
$seq_info = $_;
# replace parameters in enzyme-info portion of sequest.params
$_ = $enz_info;
# find out the width of each field in the file
($num,$name,$offset,$sites,$no_sites) = /^(\d+\.\s*)(.+?\s+)(\d\s+)([A-Z\-]+\s+)([A-Z\-])/m;
$len[0] = length($num) - 1;
$len[1] = length($name) - 1;
$len[2] = length($offset) - 1;
$len[3] = length($sites) - 1;
# we already know the right-most field can only have width 1
# construct variable $new_enz_info as text to replace old $enz_info
$new_enz_info = "";
foreach $num (1..$#enz_name)
{
$new_enz_info .= sprintf("%-$len[0].$len[0]s %-$len[1].$len[1]s %-$len[2].$len[2]s %-$len[3].$len[3]s %1.1s\n",
"$num.", $enz_name[$num], $enz_offset[$num], $enz_sites[$num], $enz_no_sites[$num]);
}
# delete all numbered lines of $enz_info after 0., and add $new_enz_info after 0.
s/^[1-9].*\n//gm;
s/^(0.*\n)/$1$new_enz_info/m;
$enz_info = $_;
$whole = join("[SEQUEST_ENZYME_INFO]\n", $seq_info, $enz_info);
}
# write to the file itself
open (PARAMS, ">$out_params") || &error ("Could not write to $out_params. $!");
print PARAMS "$whole";
close PARAMS;
if ($FORM{'print_params_only'}) {
# Print out the params file
$whole =~ s/\n/<br>\n/g;
print "$whole";
print "</body></html>";
} else {
# Run makedb4
#### cmd line
# -Ostring -- the indexed database to be created, where string is the name
# -F -- if specified, use multiple temp files during indexing
# -I -- if specified, display additional information about indexing
# -U -- if specified, use a unique sequence sort (database will be smaller, but no duplicates)
# -C -- if specified, the database will ne considered to be chromosome data
# -T -- if specified, timestamps will be printed during each step
# -Bnumber -- number can be 1-4, inclusive; if specified, certain stages of the makedb4 process will be bypassed
# -B1 - skip generating the digest header
# -B2 - skip generating the digest index
# -B3 - skip generating the peptide txt files
# -B4 - skip sorting the peptide txt files
# Get the name of the temp file to do scratch work (with .tmp extension), if sepecified on the form, use it, otherwise
# use the name of the selected database
if (defined $FORM{"indexed_db"}) {
$indexed_db = $FORM{"indexed_db"};
} else { # Use name of the selected database
$indexed_db = $db . ".hdr";
}
# Output the index to the new repository in $scratch_dbdir (machine specific dir) instead of the regular fastadb dir
# because the indexed db's are so large
$indexed_db = "$out_dir\\$indexed_db";
# if an optional arg is unspecified, leave it out
# -O must always be specified for log creation / renaming puposes in runmakedb4.pl
$args = qq(-O$indexed_db -F -I -T);
$args .= qq( -U) if ($FORM{"unique_seq_sort"});
$args .= qq( -C) if ($FORM{"chromosome_data"});
$args .= qq( -B$FORM{"bypass"}) unless (($FORM{"bypass"} == 0) || (!(defined $FORM{"bypass"})));
$args .= qq( -D) if ($FORM{"auto_distribute"});
if ($runOnServer eq $ENV{'COMPUTERNAME'}) {
$args .= qq( stayon=0); #for a local run shut down runmakedb4.pl as soon as it's done since no console will pop-up
} else {
$args .= qq( stayon=1);
# If we're running remotely, we want the hdr to be moved over to the webserver automatically when the index is made
$args .= qq( webcopy=1);
}
# Code adapted from seqindex.pl
print "<div><p>";
if ($runOnServer eq $ENV{'COMPUTERNAME'}) {
# run locally
print "<BR>Running locally, on machine $runOnServer<BR><BR>\n";
print "Command line: runmakedb4.pl $args . . .<BR>\n";
print "The indexed database will appear in <b>$out_dir</b>.<BR>\n";
&run_in_background("$perl $cgidir/runmakedb4.pl $args");
} else {
print "<BR>Running remotely, on server $runOnServer<BR><BR>\n";
print "Command line: runmakedb4.pl $args . . .<BR>\n";
print "The indexed database will appear in <b>$out_dir</b>.<BR>\n";
&seqcomm_send($runOnServer, "run_in_background&\$perl \$cgidir/runmakedb4.pl $args", "\$seqcommdir_local");
}
print <<EOF;
</body></html>
EOF
}
exit 0;
}
#######################################
# subroutines (other than &output_form and &error, see below)
#######################################
# Main form subroutine
# Most of the params parsing is adapted from sequest_launcher.pl
sub output_form {
@enz_name = ();
open (PARAMS, "<$default_makedbparams") || &error ("Could not open $paramsfile_name template. $!");
@lines = <PARAMS>;
close (PARAMS);
$whole = join("",@lines);
($seq_info,$enz_info) = split(/\[SEQUEST_ENZYME_INFO\]*.\n/, $whole);
$_ = $seq_info;
# add-mass portion
($add_Cterm) = /^add_Cterm_peptide\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_Cterm);
($add_Nterm) = /^add_Nterm_peptide\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_Nterm);
($add_G) = /^add_G_Glycine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_G);
($add_A) = /^add_A_Alanine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_A);
($add_S) = /^add_S_Serine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_S);
($add_P) = /^add_P_Proline\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_P);
($add_V) = /^add_V_Valine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_V);
($add_T) = /^add_T_Threonine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_T);
($add_C) = /^add_C_Cysteine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_C);
($add_L) = /^add_L_Leucine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_L);
($add_I) = /^add_I_Isoleucine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_I);
($add_X) = /^add_X_LorI\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_X);
($add_N) = /^add_N_Asparagine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_N);
($add_O) = /^add_O_Ornithine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_O);
($add_B) = /^add_B_avg_NandD\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_B);
($add_D) = /^add_D_Aspartic_Acid\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_D);
($add_Q) = /^add_Q_Glutamine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_Q);
($add_K) = /^add_K_Lysine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_K);
($add_Z) = /^add_Z_avg_QandE\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_Z);
($add_E) = /^add_E_Glutamic_Acid\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_E);
($add_M) = /^add_M_Methionine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_M);
($add_H) = /^add_H_Histidine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_H);
($add_F) = /^add_F_Phenylalanine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_F);
($add_R) = /^add_R_Arginine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_R);
($add_Y) = /^add_Y_Tyrosine\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_Y);
($add_W) = /^add_W_Tryptophan\s*=\s*(.*?)(\s*;|\s*$)/m unless (defined $add_W);
# enzyme info portion
@enz_lines = ($enz_info =~ /^\d.*$/mg);
foreach (@enz_lines)
{
($num,$name,$offset,$sites,$no_sites) = split(/\s+/);
chop($num); # remove trailing dot
$enz_name[$num] = $name unless (defined $enz_name[$num]);
$enz_offset[$num] = $offset unless (defined $enz_offset[$num]);
$enz_sites[$num] = $sites unless (defined $enz_sites[$num]);
$enz_no_sites[$num] = $no_sites unless (defined $enz_no_sites[$num]);
}
# advanced setting portion
$def_out_dir = $DEFS_MAKEDB{"Index Output Directory"};
$def_temp_dir = $DEFS_MAKEDB{"Temp Directory"};
$def_min_pep_size = $DEFS_MAKEDB{"Minimum Peptide Size"};
$def_max_pep_size = $DEFS_MAKEDB{"Maximum Peptide Size"};
$def_unique_seq_sort = ($DEFS_MAKEDB{"Unique Sequence Sort"} eq "yes") ? "1" : "0";
$def_chromosome_data = ($DEFS_MAKEDB{"Chromosome Data"} eq "yes") ? "1" : "0";
# main page's defaults
# For database, order of precedence is form, then form_defaults, then nr.fasta
$def_database = (defined $FORM{"Database"}) ? $FORM{"Database"} : $DEFS_MAKEDB{"Database"};
$def_database = (grep /$def_database/, @ordered_db_names) ? $def_database : "nr.fasta";
$def_enzyme = (defined $FORM{"Enzyme"}) ? $FORM{"Enzyme"} : $DEFS_MAKEDB{"Enzyme"};
$def_enzyme = (grep /$def_enzyme/, @enz_name) ? $def_enzyme : "Trypsin Strict";
%def_selected = ();
$def_selected{$DEFS_MAKEDB{"Database Type"}} = " checked";
$def_selected{$DEFS_MAKEDB{"Nucleotide Reading Frame"}} = " checked";
$def_selected{$DEFS_MAKEDB{"Monoisotopic or Average Mass"}} = " checked";
$def_min_pep_mass = $DEFS_MAKEDB{"Minimum Peptide Mass"};
$def_max_pep_mass = $DEFS_MAKEDB{"Maximum Peptide Mass"};
$def_selected{"max_internal$DEFS_MAKEDB{'Max Internal Cleavage Sites'}"} = " selected";
$def_max_diff_aa = $DEFS_MAKEDB{"Max Diff AAs per Mod"};
$def_ModifiedAA1 = $DEFS_MAKEDB{"Modified AA"};
$def_ModifiedAA1Num = $DEFS_MAKEDB{"Modified AA num"};
$def_ModifiedAA2 = $DEFS_MAKEDB{"2nd Modified AA"};
$def_ModifiedAA2Num = $DEFS_MAKEDB{"2nd Modified AA num"};
$def_ModifiedAA3 = $DEFS_MAKEDB{"3rd Modified AA"};
$def_ModifiedAA3Num = $DEFS_MAKEDB{"3rd Modified AA num"};
$def_ModifiedAA4 = $DEFS_MAKEDB{"4th Modified AA"};
$def_ModifiedAA4Num = $DEFS_MAKEDB{"4th Modified AA num"};
$def_ModifiedAA5 = $DEFS_MAKEDB{"5th Modified AA"};
$def_ModifiedAA5Num = $DEFS_MAKEDB{"5th Modified AA num"};
$def_ModifiedAA6 = $DEFS_MAKEDB{"6th Modified AA"};
$def_ModifiedAA6Num = $DEFS_MAKEDB{"6th Modified AA num"};
$def_ModifiedAA7Num = $DEFS_MAKEDB{"C-term mod num"};
$def_ModifiedAA8Num = $DEFS_MAKEDB{"N-term mod num"};
# Convert the strings from form defaults into numbers, which are used on the forms
if ($DEFS_MAKEDB{"Bypass"} eq "None") {
# To allow for multiple radio buttons to have a "None" feature specified in %DEFS_MAKEDB, use "Bypass_None"
$def_bypass = 0;
} elsif ($DEFS_MAKEDB{"Bypass"} eq "Digest Header") {
$def_bypass = 1;
} elsif ($DEFS_MAKEDB{"Bypass"} eq "Digest Index") {
$def_bypass = 2;
} elsif ($DEFS_MAKEDB{"Bypass"} eq "Peptide Files") {
$def_bypass = 3;
} elsif ($DEFS_MAKEDB{"Bypass"} eq "Sorting Peptide Files") {
$def_bypass = 4;
} else {
# Default to no bypass
$def_bypass = 0;
}
# reading of default values ends here
&load_java_dbnames;
&load_java_popups;
my $databaseEnzymeTable = &createDatabaseEnzymeTable();
my $optionsTable = &createOptionsTable();
# Now create the mod table box
my @chars = ($def_ModifiedAA1, $def_ModifiedAA2, $def_ModifiedAA3, $def_ModifiedAA4, $def_ModifiedAA5, $def_ModifiedAA6, $def_ModifiedAA7, $def_ModifiedAA8);
my @values= ($def_ModifiedAA1Num, $def_ModifiedAA2Num, $def_ModifiedAA3Num, $def_ModifiedAA4Num, $def_ModifiedAA5Num, $def_ModifiedAA6Num, $def_modifiedAA7Num, $def_modifiedAA8Num);
my $modTable = &create_mod_box("characters" => \@chars, "masses" => \@values);
my $helpLink = &create_link();
print <<EOF;
<div>
<BR>
<form method="POST" action="$ourname">
<TABLE cellspacing=0 cellpadding=0 border=0>
<TR>
<TD>
<TABLE cellspacing=0 cellpadding=0>
<TR><TD>
$databaseEnzymeTable<BR>$optionsTable
</TD></TR>
</TABLE>
</TD>
<TD width=40></TD>
<TD align=left valign=top>$modTable
<BR>
<input type="submit" class="outlinebutton" style="cursor:hand;" value="MakeDB4">
$helpLink
</TD>
</TR>
</TABLE>
<TR><TD><input type ="hidden" name="proceed" value="1"> </TD></TR>
<!-- <INPUT TYPE=checkbox NAME="print_params_only" VALUE="1">Test (for programmer's use only)-->
</TR>
</TABLE>
<HR>
<TABLE WIDTH=100%><TR><TD WIDTH=33%>
<CENTER><INPUT TYPE=button class="outlinebutton" style="cursor:hand;" VALUE="Edit Add-Mass" onClick="addmass_open()"></CENTER>
</TD><TD WIDTH=34%>
<CENTER><INPUT TYPE=button class="outlinebutton" style="cursor:hand;" VALUE="Edit Enzyme Info" onClick="enzymes_open()"></CENTER>
</TD><TD WIDTH=33%>
<CENTER><INPUT TYPE=button class="outlinebutton" style="cursor:hand;" VALUE="Edit Advanced" onClick="advanced_open()"></CENTER>
</TD></TR>
</TABLE>
<!-- hidden CGI-info for editing the middle and bottom parts of sequest.params
these values can be altered by the Javascript pop-up windows //-->
<!-- AddMass window -->
<INPUT TYPE=hidden NAME="add_Cterm" VALUE="$add_Cterm">
<INPUT TYPE=hidden NAME="add_Nterm" VALUE="$add_Nterm">
<INPUT TYPE=hidden NAME="add_G" VALUE="$add_G">
<INPUT TYPE=hidden NAME="add_A" VALUE="$add_A">
<INPUT TYPE=hidden NAME="add_S" VALUE="$add_S">
<INPUT TYPE=hidden NAME="add_P" VALUE="$add_P">
<INPUT TYPE=hidden NAME="add_V" VALUE="$add_V">
<INPUT TYPE=hidden NAME="add_T" VALUE="$add_T">
<INPUT TYPE=hidden NAME="add_C" VALUE="$add_C">
<INPUT TYPE=hidden NAME="add_L" VALUE="$add_L">
<INPUT TYPE=hidden NAME="add_I" VALUE="$add_I">
<INPUT TYPE=hidden NAME="add_X" VALUE="$add_X">
<INPUT TYPE=hidden NAME="add_N" VALUE="$add_N">
<INPUT TYPE=hidden NAME="add_O" VALUE="$add_O">
<INPUT TYPE=hidden NAME="add_B" VALUE="$add_B">
<INPUT TYPE=hidden NAME="add_D" VALUE="$add_D">
<INPUT TYPE=hidden NAME="add_Q" VALUE="$add_Q">
<INPUT TYPE=hidden NAME="add_K" VALUE="$add_K">
<INPUT TYPE=hidden NAME="add_Z" VALUE="$add_Z">
<INPUT TYPE=hidden NAME="add_E" VALUE="$add_E">
<INPUT TYPE=hidden NAME="add_M" VALUE="$add_M">
<INPUT TYPE=hidden NAME="add_H" VALUE="$add_H">
<INPUT TYPE=hidden NAME="add_F" VALUE="$add_F">
<INPUT TYPE=hidden NAME="add_R" VALUE="$add_R">
<INPUT TYPE=hidden NAME="add_Y" VALUE="$add_Y">
<INPUT TYPE=hidden NAME="add_W" VALUE="$add_W">
<!-- Enzyme window -->
EOF
# enzymes window
foreach $num (1..$#enz_name)
{
print <<EOF;
<INPUT TYPE=hidden NAME="enz_name$num" VALUE="$enz_name[$num]">
<INPUT TYPE=hidden NAME="enz_offset$num" VALUE="$enz_offset[$num]">
<INPUT TYPE=hidden NAME="enz_sites$num" VALUE="$enz_sites[$num]">
<INPUT TYPE=hidden NAME="enz_no_sites$num" VALUE="$enz_no_sites[$num]">
EOF
}
# advanced window
print <<EOF;
<!-- Advanced window -->
<INPUT TYPE=hidden NAME="out_dir" VALUE="$def_out_dir">
<INPUT TYPE=hidden NAME="temp_dir" VALUE="$def_temp_dir">
<INPUT TYPE=hidden NAME="min_peptide_size" VALUE="$def_min_pep_size">
<INPUT TYPE=hidden NAME="max_peptide_size" VALUE="$def_max_pep_size">
<INPUT TYPE=hidden NAME="unique_seq_sort" VALUE="$def_unique_seq_sort">
<INPUT TYPE=hidden NAME="diskspace_override" VALUE="0">
EOF
print "</FORM></div></body></html>";
exit 0;
}
sub createOptionsTable {
my $table = <<EOF;
<table cellspacing=0 cellpadding=0 border=0>
<tr>
<td colspan=2>
<table cellspacing=0 cellpadding=0 bgcolor="#e8e8fa" height=20 width=100%><tr>
<td width=20><img src="${webimagedir}/ul-corner.gif" width=10 height=20></td>
<td width=100% class=smallheading> Options</td>
<td width=20><img src="${webimagedir}/ur-corner.gif" width=10 height=20></td>
</tr></table>
</td>
</tr>
<tr><td colspan=2><table cellspacing=0 cellpadding=0 width=100% style="border: solid #000099; border-width:1px">
<tr><td bgcolor=#e8e8fa style="font-size:2"> </td><td bgcolor=#f2f2f2 style="font-size:2"> </td></tr>
<TR height=25>
<TD class=title>Indexed Database Name: </TD>
<TD class=data>
<input type="text" name="indexed_db" value="" size="30" maxlength="1024">
</TD>
</TR>
<TR height=25>
<TD class=title>Nucleotide Reading Frames: </TD>
<TD class=data>
<input type="radio" name="nucleotide_reading_frames" value="1"$def_selected{"3 Foward"}>3 Foward
<input type="radio" name="nucleotide_reading_frames" value="2"$def_selected{"3 Reverse"}>3 Reverse
<input type="radio" name="nucleotide_reading_frames" value="3"$def_selected{"Both"}>Both
</TD>
</TR>
<TR height=25>
<TD class=title>Mass: </TD>
<TD class=data>
<input type="radio" name="use_mono/avg_masses" value="0"$def_selected{"Average"}>Average
<input type="radio" name="use_mono/avg_masses" value="1"$def_selected{"Monoisotopic"}>Monoisotopic
</TD>
</TR>
<TR height=25>
<TD class=title>Peptide Mass: </TD>
<TD class=data>
Min <input type="text" name="min_peptide_mass" size="10" maxlength="20" value=$def_min_pep_mass>
Max <input type="text" name="max_peptide_mass" size="10" maxlength="20" value=$def_max_pep_mass>
</TD>
</TR>
<TR height=25>
<TD class=title>Max Internal Cleavage Sites: </TD>
<TD class=data>
<span class="dropbox"><select name="max_num_internal_cleavage_sites">
<option value="0"$def_selected{"max_internal0"}>0
<option value="1"$def_selected{"max_internal1"}>1
<option value="2"$def_selected{"max_internal2"}>2
<option value="3"$def_selected{"max_internal3"}>3
<option value="4"$def_selected{"max_internal4"}>4
<option value="5"$def_selected{"max_internal5"}>5
</select></span>
</TD>
</TR>
<TR height=25>
<TD class=title>Max Diff AA\'s per Mod: </TD>
<TD class=data>
<input type="text" name="max_num_diff_aa_per_mod" size="2" maxlength="2" value=$def_max_diff_aa>
</TD>
</TR>
<tr height=25>
<td class=title>Auto-Distribute: </td>
<td class=data> <input type=checkbox name="auto_distribute" $auto_distribute>
</td>
</tr>
</TABLE>
</TABLE>
EOF
return $table;
}
sub createDatabaseEnzymeTable {
my $table = <<EOF;
<table cellspacing=0 cellpadding=0 border=0>
<tr>
<td colspan=2>
<table cellspacing=0 cellpadding=0 bgcolor="#e8e8fa" height=20 width=100%><tr>
<td width=20><img src="${webimagedir}/ul-corner.gif" width=10 height=20></td>
<td width=100% class=smallheading> Database & Enzyme</td>
<td width=20><img src="${webimagedir}/ur-corner.gif" width=10 height=20></td>
</tr></table>
</td>
</tr>
<tr><td colspan=2>
<table cellspacing=0 cellpadding=0 width=100% style="border: solid #000099; border-width:1px">
<tr><td class=title style="font-size:2"> </td><td class=data style="font-size:2"> </td></tr>
<TR height=25>
<TD class=title width=119 NOWRAP>Database: </TD>
<TD class=data>
<span class="dropbox"><SELECT NAME="Database" onChange="generateindexname()">
EOF
foreach $database (@ordered_db_names) {
$table .= "<OPTION VALUE=\"$database\"";
$table .= " selected" if ($database eq $def_database);
$table .= ">$database\n";
}
$table .= <<EOF;
</SELECT></span>
</TD>
</TR>
<TR height=25>
<TD class=title NOWRAP>Database Type: </TD>
<TD class=data NOWRAP>
<INPUT TYPE=radio NAME="protein_or_nucleotide_dbase" VALUE="2"$def_selected{"Auto"}>Auto
<INPUT TYPE=radio NAME="protein_or_nucleotide_dbase" VALUE="0"$def_selected{"Protein"}>Protein
<INPUT TYPE=radio NAME="protein_or_nucleotide_dbase" VALUE="1"$def_selected{"Nucleotide"}>Nucleotide<BR>
</TD>
</TR>
<TD class=title NOWRAP>Enzyme: </TD>
<TD class=data NOWRAP> <span class="dropbox"><select name="Enzyme">
<OPTION $enz_sel{"0"} VALUE=0>None
EOF
foreach $num (1..$#enz_name)
{
$name = $enz_name[$num];
$name =~ s/_/ /g;
$selected = ($name eq $def_enzyme) ? " selected" : "";
$table .= "<OPTION VALUE=$num$selected>$name\n";
}
$table .= <<EOF;
</select></span>
</TD>
</TR>
</TABLE>
</TABLE>
EOF
return $table;
}
####################################### Start Javascript ##############################################
# Functions involved with the additional popup boxes
# Adapted from sequest_launcher.pl
sub load_java_popups {
$unique_window_name = "$$\_$^T";
print <<EOF;
<script language="Javascript">
<!--
var addmass;
var enzymes;
var advanced;
var defaults = new Array();
var enz_defaults = new Array();
// experience shows, optimal pop-up window heights are different in IE than in Netscape, thus:
var am_height = (navigator.appName == "Microsoft Internet Explorer") ? 540 : 590;
var ez_height = (navigator.appName == "Microsoft Internet Explorer") ? 600 : 650;
var adv_height = (navigator.appName == "Microsoft Internet Explorer") ? 370 : 400;
// retrieve form values from hidden values in main window
// and display in pop-up window
function getValues(popup)
{
window.status = "Retrieving values, please wait...";
for (i = 0; i < popup.document.forms[0].elements.length; i++)
{
if (popup.document.forms[0].elements[i]) {
elt = popup.document.forms[0].elements[i];
if (document.forms[0][elt.name]) {
if (elt.type == "checkbox" || elt.type == "radio") {
// Always define the actual checkboxes in the pop-up as value="1", put the real value in
// the hidden form element on the main page
// For radio buttons, check all pop-up radios against the one hidden form element to see if
// it matches, if so, check the current one
elt.checked = (document.forms[0][elt.name].value == elt.value);
} else {
elt.value = document.forms[0][elt.name].value;
}
}
}
}
window.status = "Done";
}
// opposite of getValues(): save values from form elements in a pop-up window
// as values of hidden elements in main window, and update enzyme dropbox
function saveValues(popup)
{
window.status = "Saving values, please wait...";
for (i = 0; i < popup.document.forms[0].elements.length; i++)
{
elt = popup.document.forms[0].elements[i];
if (document.forms[0][elt.name]) {
if (elt.type == "checkbox") {
document.forms[0][elt.name].value = (elt.checked) ? elt.value : 0;
} else if (elt.type == "radio") {
// only overwrite the hidden form element on the main page on checked, else it is overwritten
// whenever the last radio option is not selected
if (elt.checked) {
document.forms[0][elt.name].value = elt.value;
}
} else {
document.forms[0][elt.name].value = elt.value;
}
}
// update Enzyme list in dropbox on main form if necessary
if (elt.name.substring(0,8) == "enz_name")
{
var enz_num = elt.name.substring(8,elt.name.length);
var enz_text = elt.value;
// replace all underscores in enz_text with spaces
textlength = enz_text.length;
for (j = 0; j < textlength; j++)
{
if (enz_text.charAt(j) == "_")
enz_text = enz_text.substring(0,j) + " " + enz_text.substring(j+1,textlength);
}
document.forms[0].Enzyme.options[enz_num].text = enz_text;
}
}
window.status = "Done";
}
// create pop-up window for editing add-mass parameters
function addmass_open()
{
if (addmass && !addmass.closed)
addmass.focus();
else
{
addmass = open("","addmass_$unique_window_name","width=240,height=" + am_height + ",resizable,screenX=20,screenY=20,left=20,top=20");
addmass.document.open();
addmass.document.writeln('<HTML>');
addmass.document.writeln('<!-- this is the code for the add-mass pop-up window -->');
addmass.document.writeln('');
addmass.document.writeln('<HEAD><TITLE>Add Masses</TITLE>$stylesheet_javascript</HEAD>');
addmass.document.writeln('');
addmass.document.writeln('<BODY BGCOLOR=#FFFFFF>');
addmass.document.writeln('<CENTER>');
addmass.document.writeln('');
addmass.document.writeln('<H4>Add Masses</H4>');
addmass.document.writeln('');
addmass.document.writeln('<FORM>');
addmass.document.writeln('');
addmass.document.writeln('<tt>C-terminus:</tt> <INPUT NAME="add_Cterm" MAXLENGTH=7 SIZE=7><BR>');
addmass.document.writeln('<tt>N-terminus:</tt> <INPUT NAME="add_Nterm" MAXLENGTH=7 SIZE=7><P>');
var ABC = "GASPVTCLIXNOBDQKZEMHFRYW";
addmass.document.writeln('<TABLE WIDTH=200><TR><TD>');
addmass.document.writeln('<TABLE WIDTH=100>');
for (i = 0; i < 12; i++)
{
var A = ABC.charAt(i);
addmass.document.writeln('<TR>');
addmass.document.writeln(' <TD ALIGN=right><tt>' + A + ':</tt></TD>');
addmass.document.writeln(' <TD><INPUT NAME="add_' + A + '" MAXLENGTH=7 SIZE=7"></TD>');
addmass.document.writeln('</TR>');
}
addmass.document.writeln('</TABLE>');
addmass.document.writeln('</TD><TD>');
addmass.document.writeln('<TABLE WIDTH=100>');
for (i = 12; i < 24; i++)
{
var A = ABC.charAt(i);
addmass.document.writeln('<TR>');
addmass.document.writeln(' <TD ALIGN=right><tt>' + A + ':</tt></TD>');
addmass.document.writeln(' <TD><INPUT NAME="add_' + A + '" MAXLENGTH=7 SIZE=7></TD>');
addmass.document.writeln('</TR>');
}
addmass.document.writeln('</TABLE>');
addmass.document.writeln('</TD></TR></TABLE>');
addmass.document.writeln('<br>');
addmass.document.writeln('<INPUT TYPE=button class="button" NAME="saveAddmass" VALUE="Save" onClick="opener.saveValues(self); self.close()"> ');
addmass.document.writeln('<INPUT TYPE=button class="button" NAME="cancelAddmass" VALUE="Cancel" onClick="self.close()">');
addmass.document.writeln('</FORM>');
addmass.document.writeln('</CENTER>');
addmass.document.writeln('</BODY>');
addmass.document.writeln('</HTML>');
getValues(addmass);
addmass.document.close();
}
}
// create pop-up window for editing enzyme-info parameters
function enzymes_open()
{
if (enzymes && !enzymes.closed)
enzymes.focus();
else
{
enzymes = open("","enzymes_$unique_window_name","width=520,height=" + ez_height + ",resizable,screenX=220,screenY=30,left=220,top=30");
enzymes.document.open();
enzymes.document.writeln('<HTML>');
enzymes.document.writeln('<!-- this is the code for the enzyme-info pop-up window -->');
enzymes.document.writeln('');
enzymes.document.writeln('<HEAD><TITLE>Enzyme Information</TITLE>$stylesheet_javascript</HEAD>');
enzymes.document.writeln('');
enzymes.document.writeln('<BODY BGCOLOR=#FFFFFF>');
enzymes.document.writeln('<CENTER>');
enzymes.document.writeln('');
enzymes.document.writeln('<H4>Enzyme Information</H4>');
enzymes.document.writeln('');
enzymes.document.writeln('<FORM>');
enzymes.document.writeln('');
enzymes.document.writeln('<TABLE>');
enzymes.document.writeln('<TR><TH></TH><TH ALIGN=left>Name</TH><TH>Offset</TH><TH ALIGN=left>Sites</TH><TH>No-sites</TH></TR>');
enzymes.document.writeln('<TR>');
enzymes.document.writeln(' <TH ALIGN=right>0.</TH>');
enzymes.document.writeln(' <TD>No Enzyme</TD>');
enzymes.document.writeln(' <TD ALIGN=center>0</TD>');
enzymes.document.writeln(' <TD>-</TD>');
enzymes.document.writeln(' <TD ALIGN=center>-</TD>');
enzymes.document.writeln('</TR>');
for (i = 1; i < document.forms[0].Enzyme.options.length; i++)
{
enzymes.document.writeln('<TR>');
enzymes.document.writeln(' <TH ALIGN=right>' + i + '.</TH>');
enzymes.document.writeln(' <TD><INPUT NAME="enz_name' + i + '"></TD>');
enzymes.document.writeln(' <TD ALIGN=center><INPUT NAME="enz_offset' + i + '" SIZE=1 MAXLENGTH=1></TD>');
enzymes.document.writeln(' <TD><INPUT NAME="enz_sites' + i + '"></TD>');
enzymes.document.writeln(' <TD ALIGN=center><INPUT NAME="enz_no_sites' + i + '" SIZE=1 MAXLENGTH=1></TD>');
enzymes.document.writeln('</TR>');
}
enzymes.document.writeln('</TABLE>');
enzymes.document.writeln('<br>');
enzymes.document.writeln('<INPUT TYPE=button class="button" NAME="saveEnzymes" VALUE="Save" onClick="opener.saveValues(self); self.close()"> ');
enzymes.document.writeln('<INPUT TYPE=button class="button" NAME="cancelEnzymes" VALUE="Cancel" onClick="self.close()">');
enzymes.document.writeln('');
enzymes.document.writeln('</FORM>');
enzymes.document.writeln('');
enzymes.document.writeln('</CENTER>');
enzymes.document.writeln('</BODY>');
enzymes.document.writeln('</HTML>');
getValues(enzymes);
enzymes.document.close();
}
}
function advanced_open() {
if (advanced && !advanced.closed) {
advanced.focus();
} else {
advanced = open("","advanced_$unique_window_name","width=520,height=" + adv_height + ",resizable,screenX=440,screenY=40,left=440,top=40");
advanced.document.open();
advanced.document.writeln('<HTML>');
advanced.document.writeln('<!-- this is the code for the advanced settings pop-up window -->');
advanced.document.writeln('');
advanced.document.writeln('<HEAD><TITLE>Advanced Settings</TITLE>$stylesheet_javascript</HEAD>');
advanced.document.writeln('');
advanced.document.writeln('<BODY BGCOLOR=#FFFFFF>');
advanced.document.writeln('<CENTER>');
advanced.document.writeln('');
advanced.document.writeln('<H4>Advanced Settings</H4>');
advanced.document.writeln('');
advanced.document.writeln('<FORM>');
advanced.document.writeln('');
advanced.document.writeln('<TABLE>');
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Index Output Directory:</span>');
advanced.document.writeln('<TD><input type="text" name="out_dir" size="30" maxlength="1023"></TR>');
advanced.document.writeln('');
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Temp Directory:</span>');
advanced.document.writeln('<TD><input type="text" name="temp_dir" size="30" maxlength="1023"></TR>');
advanced.document.writeln('');
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Minimum Peptide Size:</span>');
advanced.document.writeln('<TD><input type="text" name="min_peptide_size" size="4" maxlength="4"></TR>');
advanced.document.writeln('');
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Maximum Peptide Size:</span>');
advanced.document.writeln('<TD><input type="text" name="max_peptide_size" size="4" maxlength="4"></TR>');
advanced.document.writeln('');
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Unique Sequence Sort:</span>');
advanced.document.writeln('<TD><input type="checkbox" name="unique_seq_sort" value="1"></TR>');
EOF
print <<EOF;
advanced.document.writeln('<TR><TD align="right"><span class="smallheading">Diskspace Override:</span>');
advanced.document.writeln('<TD><input type="checkbox" name="diskspace_override" value="1"></TR>');
advanced.document.writeln('</TABLE>');
advanced.document.writeln('');
advanced.document.writeln('<br>');
advanced.document.writeln('<INPUT TYPE=button class="button" NAME="saveAdvanced" VALUE="Save" onClick="opener.saveValues(self); self.close()"> ');
advanced.document.writeln('<INPUT TYPE=button class="button" NAME="cancelAdvanced" VALUE="Cancel" onClick="self.close()">');
advanced.document.writeln('');
advanced.document.writeln('</FORM>');
advanced.document.writeln('');
advanced.document.writeln('</CENTER>');
advanced.document.writeln('</BODY>');
advanced.document.writeln('</HTML>');
getValues(advanced);
advanced.document.close();
}
}
// close all pop-up windows
function closeAll_popups()
{
if (addmass)
if (!addmass.closed)
addmass.close();
if (enzymes)
if (!enzymes.closed)
enzymes.close();
if (advanced)
if (!advanced.closed)
advanced.close();
}
onunload = closeAll_popups;
//-->
</script>
EOF
}
# Causes an autoupdate of the indexed db box
# This code adapted from seqindex.pl
sub load_java_dbnames {
print <<EOF;
<script language = "Javascript">
<!--
function isvaliddatabase(database_name)
{
return(database_name.match(/.fasta\$/i));
}
function generateindexname()
{
var database_name = document.forms[0].Database.options[document.forms[0].Database.selectedIndex].value;
if (isvaliddatabase(database_name)) {
document.forms[0].indexed_db.value = database_name + ".hdr";
} else {
document.forms[0].indexed_db.value = "Not a .fasta database";
}
}
// Continues a previous run for the currently selected database
function continuePrev()
{
var selected = document.forms[0].Database.options.selectedIndex;
var curr_dbase = document.forms[0].Database.options[selected].value;
var paramsfile = escape("C:/Sequest/" + curr_dbase + "/sequest.params");
var gotoURL = "$webcgi/$ourshortname";
location.href=gotoURL;
}
onload = generateindexname;
//-->
</script>
EOF
}
####################################### End Javascript #################################################
# return 1 if the database is a nucleotide database, 0 otherwise
#
# Check if the database is more than 80% ACTG over the first 500 lines. If so, we will assume it is nucleotide.
# Otherwise, assume it is protein.
#
# Adapted from sequest_launcher.pl
sub get_dbtype {
my ($db) = $_[0];
# Count the percentage of nucleotide bases in the first 500 lines, if it is > 80%, assume the database is
# nucleotide. Otherwise, assume the database is protein.
my ($line, $numchars, $numnucs, $numlines);
open (DB, "$db") || &error ("Could not open database $db for auto-detecting database type.");
while ($line = <DB>) {
next if ($line =~ m!^>!);
chomp $line;
$numchars += length ($line);
$numnucs += $line =~ tr/ACTGactg/ACTGactg/;
$numlines++;
last if ($numlines >= 500);
}
close DB;
return (1) if ($numnucs > .8 * $numchars);
return (0);
}
#######################################
# Error subroutine
# prints out a properly formatted error message in case the user did something wrong; also useful for debugging
# If second argument is specified and non-null/non-zero, the standard header is printed as well.
sub error {
if ($_[1]) {
&MS_pages_header("MakeDB4","#8800FF");
print "<hr><p>\n";
}
print "<h3>Error:</h3>\n";
print "<div>$_[0]</div>\n";
print "</body></html>";
exit 1;
}
| wangchulab/CIMAGE | cravatt_web/cgi-bin/flicka/makedb4.pl | Perl | mit | 49,516 |
/* Part of ClioPatria SeRQL and SPARQL server
Author: Jan Wielemaker
E-mail: J.Wielemaker@cs.vu.nl
WWW: http://www.swi-prolog.org
Copyright (C): 2014, University of Amsterdam,
VU University Amsterdam
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
As a special exception, if you link this library with other files,
compiled with a Free Software compiler, to produce an executable, this
library does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
:- module(cliopatria_pengines, []).
:- use_module(library(pengines), []).
:- use_module(pengine_sandbox:library(semweb/rdf_db)).
:- use_module(pengine_sandbox:library(semweb/rdfs)).
:- use_module(library(sandbox), []).
/** <module> Provide pengines Prolog and JavaScript API
This module makes the ClioPatria RDF API available through the pengines
package. Pengines provide an ideal mechanism for accessing the data from
web applications through JavaScript or from other Prolog processes using
pengine_rpc/3.
@see http://www.swi-prolog.org/pldoc/package/pengines.html
*/
| TeamSPoon/logicmoo_workspace | packs_web/ClioPatria/api/pengines.pl | Perl | mit | 1,954 |
package SOAP::Message;
require 5;
use strict;
use vars qw($VERSION);
use XML::XPath;
use XML::XPath::XMLParser;
$VERSION = '0.01';
=head1 NAME
SOAP::Message - Really simple SOAP
=head1 DESCRIPTION
Simple SOAP for the unwashed masses
=head1 SYNOPSIS
use SOAP::Message;
## Procedural interface
# Make SOAP
my $message = SOAP::Message::create(
version => '1.1',
body => $xml_data,
);
# Receive SOAP
my ( $header,$body ) = SOAP::Message::parse( $incoming );
## OO interface
# Set some defaults up...
my $object = SOAP::Message->new( version => '1.2', prefix => 'SOAP' );
# Then just continue as normal...
my $message = $object->create( body => $body, header => $header );
# And for convenience...
my ( $header, $body ) = $object->parse( $incoming );
=head1 OVERVIEW
90% of using SOAP appears to be jumping through many hoops to do something
pretty simple - putting an XML wrapper around another piece of XML, or removing
the XML wrapper around a piece of XML.
That's all this package does. And not particularly cleverly. And that's all it
wants to do. Chances are it handles everything you need it to.
=head1 METHODS
=head2 create
Creates a new SOAP message. Accepts:
B<version> - which can either be C<1.1> or C<1.2>. Defaults to C<1.1>. This affects what the namespace will be:
http://schemas.xmlsoap.org/soap/envelope/ - 1.1
http://www.w3.org/2003/05/soap-envelope - 1.2
Optional.
B<body> - which is the message body, and can be anything you fancy. Optional.
B<header> - which is the header, and can be anything you want. Optional.
B<prefix> - which is the prefix we use. Defaults to 'env'. Common examples
C<soapenv>, C<soap>, C<env> and so on. Optional. We don't perform any validation
on this.
Returns a string containing your SOAP message.
=cut
sub create {
my $self = shift;
my %options;
# Check here to see if we're being called as OO. If the first argument
# is a ref, assume it's an object, and load up the defaults, then any
# arguments to this function. If it's not, stick it back on the list
# passed to the function, and use that list as our options.
if ( ref( $self ) ) {
%options = (%$self, @_);
} else {
%options = ($self, @_);
}
# Default the prefix ( <prefix:Envelope> )
my $prefix = $options{'prefix'} || 'env';
$options{'header'} = '' unless $options{'header'};
$options{'body'} = '' unless $options{'body'};
# Work out the correct namespace
$options{'version'} = '1.1' unless $options{'version'};
my $namespace = "http://schemas.xmlsoap.org/soap/envelope/";
if ( $options{'version'} eq '1.2' ) {
$namespace = "http://www.w3.org/2003/05/soap-envelope";
}
# That's all folks!
return qq!<?xml version='1.0'?>
<$prefix:Envelope xmlns:$prefix = "$namespace">
<$prefix:Header>! . $options{'header'} . qq!</$prefix:Header>
<$prefix:Body>! . $options{'body'} . qq!</$prefix:Body>
</$prefix:Envelope>
!;
}
=head2 parse
Parses a SOAP message in a string. Returns a list containing the
header and the body as strings.
=cut
sub parse {
my $data = shift;
# This method isn't enhanced by OO, so if the first argument was a ref,
# silently drop it and grab the next.
$data = shift if ref( $data ); # Handle OO calls
# Open up our parser...
my $xp = XML::XPath->new( xml => $data );
# This means that when the namespace is set to X, we can assume the prefix
# is going to be Y... This simplifies our XPath expressions a little.
$xp->set_namespace( ver1 => 'http://schemas.xmlsoap.org/soap/envelope/');
$xp->set_namespace( ver2 => 'http://www.w3.org/2003/05/soap-envelope' ) ;
# Grab the Header and the Body
my $header_nodes =
$xp->find('/ver1:Envelope/ver1:Header/* | /ver2:Envelope/ver2:Header/*');
my $body_nodes
= $xp->find('/ver1:Envelope/ver1:Body/* | /ver2:Envelope/ver2:Body/*');
my $header = '';
my $body = '';
# Serialize them
for ($header_nodes->get_nodelist) { $header .= $_->toString }
for ($body_nodes->get_nodelist) { $body .= $_->toString }
# That's all done
return( $body, $header );
}
=head2 xml_parse
Like C<parse()>, but returns C<XML::XPath::Nodeset> objects instead.
=cut
sub xml_parse {
# This method isn't enhanced by OO, so if the first argument was a ref,
# silently drop it and grab the next.
my $data = shift;
$data = shift if ref( $data ); # Handle OO calls
# Open up our parser...
my $xp = XML::XPath->new( xml => $data );
# This means that when the namespace is set to X, we can assume the prefix
# is going to be Y... This simplifies our XPath expressions a little.
$xp->set_namespace( ver1 => 'http://schemas.xmlsoap.org/soap/envelope/');
$xp->set_namespace( ver2 => 'http://www.w3.org/2003/05/soap-envelope' ) ;
# Grab the Header and the Body
my $header_nodes =
$xp->find('/ver1:Envelope/ver1:Header/* | /ver2:Envelope/ver2:Header/*');
my $body_nodes
= $xp->find('/ver1:Envelope/ver1:Body/* | /ver2:Envelope/ver2:Body/*');
return ($header_nodes, $body_nodes);
}
=head2 new
Accepts the same arguments as C<create()>, and sets them as the defaults for
subsequent calls to C<create>.
=cut
sub new {
my $class = shift;
my $self = { @_ };
bless $self, $class;
return $self;
}
=head1 AUTHOR
Peter Sergeant - C<pete@clueball.com>
=cut
1;
| jkb78/extrajnm | local/lib/perl5/SOAP/Message.pm | Perl | mit | 5,426 |
#!/usr/bin/perl -w
$gnuplot="gnuplot"; # or complete path
$preamble="preamble.gpi";
$function=$ARGV[0];
unless($function) {
print STDERR "usage: $0 <function_definition_file.gpi>\n";
exit 1;
}
$dir="$function.d";
$plot="plot.gpi";
$format='png';
$t_i=0;
$t_f=7;
$step=0.0075; # time step
mkdir $dir;
open(GNUPLOT,"|$gnuplot");
print GNUPLOT "load \"$preamble\"\n";
print GNUPLOT "load \"$function\"\n";
for($t=$t_i;$t<=$t_f;$t+=$step) {
$n=sprintf("%07.4f",$t);
$n_f=sprintf("%07.4f",$t_f);
print GNUPLOT "
set title \"t=$n\" offset 0,-1
t=$t
unset multiplot
set output \"$dir/frame.$n.$format\"
load \"$plot\"
print \"t = $n / $n_f \"
";
}
print GNUPLOT "\n";
close(GNUPLOT);
| gderosa/2d_well | plot.pl | Perl | mit | 755 |
package PJVM;
use 5.008001;
use strict;
use warnings;
our $VERSION = "0.01_03";
1;
__END__
=head1 NAME
PJVM - Java virtual machine written in Perl
=head1 SYNOPSIS
use PJVM;
my $rt = PVJM::Runtime->new({classpath => [qw(.)]});
my $class = $rt->init_class("MyApp");
$class->main(@ARGV);
=head1 DESCRIPTION
PJVM is a Java Virtual Machine written in Perl. It will proably be dog-slow and is just an experiment. Currently it
is just able to load classes but not execute them which is being worked on.
The plan is to implement multiple bytecode backend execution engines, such as:
=over 4
=item *
Simple switching runloop
=item *
One that can transform Java bytecode to perl optrees directly
=item *
Transform bytecode -> Perl source and eval
=item *
Fast JIT:ing backend written in XS
=back
The execution during the lifetime of the app should not be limited to one execution engine and
each class/method might end up being executed by different backend depending on a criteria such as
maybe annotating the Java method with a PVJMExecutionEngine attribute or something.
Please do not report any bugs since this module is very experimental.
=head1 BUGS AND LIMITATIONS
* Disregard from this currently please *
Please report any bugs or feature requests to C<bug-pjvm@rt.cpan.org>,
or through the web interface at L<http://rt.cpan.org>.
=head1 AUTHOR
Claes Jakobsson, Versed Solutions C<< <claesjac@cpan.org> >>
=head1 LICENCE AND COPYRIGHT
Copyright (c) 2008, Versed Solutions C<< <info@versed.se> >>. All rights reserved.
This software is released under the MIT license cited below.
=head2 The "MIT" License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
=cut
| claesjac/pjvm | lib/PJVM.pm | Perl | mit | 2,679 |
#!/usr/bin/env perl
#---------------------------------------------------
%from = ();
%links = ();
print STDERR "reading good names...\n";
open GOOD, "<./goodpagelinks.csv" or die $!;
for (<GOOD>) {
if (my ($a,$b) = /^(\d+),"\[(.*)\]"$/) {
my @c = split(",",$b);
for my $to (@c) {
push(@{$from{$to}},$a);
$links{$a} = 1;
}
}
}
close(GOOD);
print STDERR " read ".(scalar keys %from)."/".(scalar keys %links)." link entries\n";
#---------------------------------------------------
%small = ();
print STDERR "reading small names...\n";
open SMALL, "<./small_page.csv" or die $!;
for (<SMALL>) {
chomp;
if (my ($a,$b) = /^(\d+),(.*)$/) {
$small{$a} = $b;
}
}
close(SMALL);
print STDERR " read ".(scalar keys %small)." small names...\n";
#---------------------------------------------------
print STDERR "writing fromlinks...\n";
{
for my $key (keys %from) {
print "$key,\"[".join(",",@{$from{$key}})."]\"\n";
}
}
my $small_removed = 0;
for my $key (keys %small) {
if (!defined($links{$key}) && !defined($from{$key})) {
delete($small{$key});
$small_removed++;
}
}
#---------------------------------------------------
if ($small_removed>0) {
print STDERR "rewriting small names, $small_removed removed...\n";
open SMALL, ">./small_page.csv" or die $!;
for my $k (keys %small) {
print SMALL "$k,$small{$k}\n";
}
close(SMALL);
}
| erikwilson/wiki-hop | import/filter_fromlinks.pl | Perl | mit | 1,408 |
package Paws::Batch::ContainerOverrides;
use Moose;
has Command => (is => 'ro', isa => 'ArrayRef[Str|Undef]', request_name => 'command', traits => ['NameInRequest']);
has Environment => (is => 'ro', isa => 'ArrayRef[Paws::Batch::KeyValuePair]', request_name => 'environment', traits => ['NameInRequest']);
has Memory => (is => 'ro', isa => 'Int', request_name => 'memory', traits => ['NameInRequest']);
has Vcpus => (is => 'ro', isa => 'Int', request_name => 'vcpus', traits => ['NameInRequest']);
1;
### main pod documentation begin ###
=head1 NAME
Paws::Batch::ContainerOverrides
=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::Batch::ContainerOverrides object:
$service_obj->Method(Att1 => { Command => $value, ..., Vcpus => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::Batch::ContainerOverrides object:
$result = $service_obj->Method(...);
$result->Att1->Command
=head1 DESCRIPTION
The overrides that should be sent to a container.
=head1 ATTRIBUTES
=head2 Command => ArrayRef[Str|Undef]
The command to send to the container that overrides the default command
from the Docker image or the job definition.
=head2 Environment => ArrayRef[L<Paws::Batch::KeyValuePair>]
The environment variables to send to the container. You can add new
environment variables, which are added to the container at launch, or
you can override the existing environment variables from the Docker
image or the job definition.
=head2 Memory => Int
The number of MiB of memory reserved for the job. This value overrides
the value set in the job definition.
=head2 Vcpus => Int
The number of vCPUs to reserve for the container. This value overrides
the value set in the job definition.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::Batch>
=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/Batch/ContainerOverrides.pm | Perl | apache-2.0 | 2,359 |
package Google::Ads::AdWords::v201809::CustomAffinityStatus;
use strict;
use warnings;
sub get_xmlns { 'https://adwords.google.com/api/adwords/rm/v201809'};
# derivation by restriction
use base qw(
SOAP::WSDL::XSD::Typelib::Builtin::string);
1;
__END__
=pod
=head1 NAME
=head1 DESCRIPTION
Perl data type class for the XML Schema defined simpleType
CustomAffinityStatus from the namespace https://adwords.google.com/api/adwords/rm/v201809.
Status of custom affinity.
This clase is derived from
SOAP::WSDL::XSD::Typelib::Builtin::string
. SOAP::WSDL's schema implementation does not validate data, so you can use it exactly
like it's base type.
# Description of restrictions not implemented yet.
=head1 METHODS
=head2 new
Constructor.
=head2 get_value / set_value
Getter and setter for the simpleType's value.
=head1 OVERLOADING
Depending on the simple type's base type, the following operations are overloaded
Stringification
Numerification
Boolification
Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information.
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/CustomAffinityStatus.pm | Perl | apache-2.0 | 1,105 |
% Towers of Hanoi
%
% The Towers of Hanoi is a game played with three poles and a number of discs of different sizes which can slide onto any pole.
% The game starts with all the discs stacked in ascending order of size on one pole, the smallest at the top.
% The aim of the game is to move the entire stack to another pole, obeying the following rules:
% - Only one disc may be moved at a time.
% - Each move consists of taking the upper disc from one of the poles and sliding it onto another pole.
% - No disc may be placed on top of a smaller one.
hanoi(N) :- move(N,left,centre,right).
move(0,_,_,_) :- !.
move(N,A,B,C) :-
M is N-1,
move(M,A,C,B), inform(A,B), move(M,C,B,A).
inform(X,Y) :-
write([move,a,disc,from,the,X,pole,to,the,Y,pole]),
nl.
| s-webber/projog | src/test/resources/towers-of-hanoi-example.pl | Perl | apache-2.0 | 766 |
=head1 NAME
LedgerSMB::Report::Unapproved::Batch_Detail - List Vouchers by Batch
in LedgerSMB
=head1 SYNPOSIS
my $report = LedgerSMB::Report::Unapproved::Batch_Detail->new(
%$request
);
$report->run;
$report->render($request, $format);
=head1 DESCRIPTION
This provides an ability to search for (and approve or delete) pending
transactions grouped in batches. This report only handles the vouchers in the
bach themselves. For searching for batches, use
LedgerSMB::Report::Unapproved::Batch_Overview instead.
=head1 INHERITS
=over
=item LedgerSMB::Report;
=back
=cut
package LedgerSMB::Report::Unapproved::Batch_Detail;
use Moose;
use LedgerSMB::DBObject::User;
extends 'LedgerSMB::Report';
use LedgerSMB::Business_Unit_Class;
use LedgerSMB::Business_Unit;
use LedgerSMB::Setting;
=head1 PROPERTIES
=over
=item columns
Read-only accessor, returns a list of columns.
=over
=item select
Select boxes for selecting the returned items.
=item id
ID of transaction
=item batch_class
Text description of batch class
=item transdate
Post date of transaction
use LedgerSMB::Report::Unapproved::Batch_Overview;
=item reference text
Invoice number or GL reference
=item description
Description of transaction
=item amount
Total on voucher. For AR/AP amount, this is the total of the AR/AP account
before payments. For payments, receipts, and GL, it is the sum of the credits.
=back
=cut
sub columns {
return [
{col_id => 'select',
name => '',
type => 'checkbox' },
{col_id => 'id',
name => LedgerSMB::Report::text('ID'),
type => 'text',
pwidth => 1, },
{col_id => 'batch_class',
name => LedgerSMB::Report::text('Batch Class'),
type => 'text',
pwidth => 2, },
{col_id => 'default_date',
name => LedgerSMB::Report::text('Date'),
type => 'text',
pwidth => '4', },
{col_id => 'Reference',
name => LedgerSMB::Report::text('Reference'),
type => 'href',
href_base => '',
pwidth => '3', },
{col_id => 'description',
name => LedgerSMB::Report::text('Description'),
type => 'text',
pwidth => '6', },
{col_id => 'amount',
name => LedgerSMB::Report::text('Amount'),
type => 'text',
money => 1,
pwidth => '2', },
];
# TODO: business_units int[]
}
=item name
Returns the localized template name
=cut
sub name {
return LedgerSMB::Report::text('Voucher List');
}
=item header_lines
Returns the inputs to display on header.
=cut
sub header_lines {
return [{name => 'batch_id',
text => LedgerSMB::Report::text('Batch ID')}, ]
}
=item subtotal_cols
Returns list of columns for subtotals
=cut
sub subtotal_cols {
return [];
}
=back
=head2 Criteria Properties
Note that in all cases, undef matches everything.
=over
=item batch_id (Int)
ID of batch to list vouchers of.
=cut
has 'batch_id' => (is => 'rw', isa => 'Int');
=back
=head1 METHODS
=over
=item run_report()
Runs the report, and assigns rows to $self->rows.
=cut
sub run_report{
my ($self) = @_;
my %lhash = LedgerSMB::DBObject::User->country_codes();
my ($default_language) = LedgerSMB::Setting->get('default_language');
my $locales = [ map { { text => $lhash{$_}, value => $_ } }
sort {$lhash{$a} cmp $lhash{$b}} keys %lhash
];
my $printer = [ {text => 'Screen', value => 'zip'},
map { {
text => $_, value => $LedgerSMB::Sysconfig::printer{$_}
} }
keys %LedgerSMB::Sysconfig::printer];
$self->options([{
name => 'language',
options => $locales,
default_value => [$default_language],
}, {
name => 'media',
options => $printer,
},
]);
$self->buttons([{
name => 'action',
type => 'submit',
text => LedgerSMB::Report::text('Post Batch'),
value => 'single_batch_approve',
class => 'submit',
},{
name => 'action',
type => 'submit',
text => LedgerSMB::Report::text('Delete Batch'),
value => 'single_batch_delete',
class => 'submit',
},{
name => 'action',
type => 'submit',
text => LedgerSMB::Report::text('Delete Vouchers'),
value => 'batch_vouchers_delete',
class => 'submit',
},
{
name => 'action',
type => 'submit',
text => LedgerSMB::Report::text('Unlock Batch'),
value => 'single_batch_unlock',
class => 'submit',
},
{
name => 'action',
type => 'submit',
text => LedgerSMB::Report::text('Print Batch'),
value => 'print_batch',
class => 'submit',
}, ]);
my @rows = $self->call_dbmethod(funcname => 'voucher__list');
for my $ref (@rows){
my $script;
my $class_to_script = {
'1' => 'ap',
'2' => 'ar',
'3' => 'gl',
'8' => 'is',
'9' => 'ir',
};
$script = $class_to_script->{lc($ref->{batch_class_id})};
$ref->{reference_href_suffix} = "$script.pl?action=edit&id=$ref->{id}" if $script;
}
$self->rows(\@rows);
}
=back
=head1 COPYRIGHT
COPYRIGHT (C) 2012 The LedgerSMB Core Team. This file may be re-used following
the terms of the GNU General Public License version 2 or at your option any
later version. Please see included LICENSE.TXT for details.
=cut
__PACKAGE__->meta->make_immutable;
1;
| tridentcodesolution/tridentcodesolution.github.io | projects/CRM/LedgerSMB-master/LedgerSMB/Report/Unapproved/Batch_Detail.pm | Perl | apache-2.0 | 5,951 |
package Paws::WAF::CreateSizeConstraintSet;
use Moose;
has ChangeToken => (is => 'ro', isa => 'Str', required => 1);
has Name => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'CreateSizeConstraintSet');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::WAF::CreateSizeConstraintSetResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::WAF::CreateSizeConstraintSet - Arguments for method CreateSizeConstraintSet on Paws::WAF
=head1 DESCRIPTION
This class represents the parameters used for calling the method CreateSizeConstraintSet on the
AWS WAF service. Use the attributes of this class
as arguments to method CreateSizeConstraintSet.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to CreateSizeConstraintSet.
As an example:
$service_obj->CreateSizeConstraintSet(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> ChangeToken => Str
The value returned by the most recent call to GetChangeToken.
=head2 B<REQUIRED> Name => Str
A friendly name or description of the SizeConstraintSet. You can't
change C<Name> after you create a C<SizeConstraintSet>.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method CreateSizeConstraintSet in L<Paws::WAF>
=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/WAF/CreateSizeConstraintSet.pm | Perl | apache-2.0 | 1,900 |
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::azure::network::loadbalancer::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_custom);
sub new {
my ( $class, %options ) = @_;
my $self = $class->SUPER::new( package => __PACKAGE__, %options );
bless $self, $class;
$self->{version} = '0.1';
$self->{modes} = {
'datapath' => 'cloud::azure::network::loadbalancer::mode::datapath',
'discovery' => 'cloud::azure::network::loadbalancer::mode::discovery',
'healthprobe' => 'cloud::azure::network::loadbalancer::mode::healthprobe',
'snat' => 'cloud::azure::network::loadbalancer::mode::snat',
'throughput' => 'cloud::azure::network::loadbalancer::mode::throughput'
};
$self->{custom_modes}->{azcli} = 'cloud::azure::custom::azcli';
$self->{custom_modes}->{api} = 'cloud::azure::custom::api';
return $self;
}
sub init {
my ($self, %options) = @_;
$self->{options}->add_options(arguments => {
'api-version:s' => { name => 'api_version', default => '2018-01-01' },
});
$self->SUPER::init(%options);
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Microsoft Azure Network LoadBalancers.
=cut
| centreon/centreon-plugins | cloud/azure/network/loadbalancer/plugin.pm | Perl | apache-2.0 | 1,953 |
#
# 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::oneaccess::snmp::mode::cpu;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"warning:s" => { name => 'warning', },
"critical:s" => { name => 'critical', },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
$self->{output}->option_exit();
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
my $oid_oacSysCpuUsed = '.1.3.6.1.4.1.13191.10.3.3.1.2.1.0';
my $result = $self->{snmp}->get_leef(oids => [$oid_oacSysCpuUsed], nothing_quit => 1);
my $exit = $self->{perfdata}->threshold_check(value => $result->{$oid_oacSysCpuUsed},
threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("CPU Usage: %d %%", $result->{$oid_oacSysCpuUsed}));
$self->{output}->perfdata_add(label => "cpu", unit => '%',
value => $result->{$oid_oacSysCpuUsed},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'),
min => 0, max => 100);
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check cpu usage (oneaccess-sys-mib).
=over 8
=item B<--warning>
Threshold warning in percent.
=item B<--critical>
Threshold critical in percent.
=back
=cut
| wilfriedcomte/centreon-plugins | network/oneaccess/snmp/mode/cpu.pm | Perl | apache-2.0 | 3,374 |
=head1 LICENSE
Copyright (c) 1999-2013 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/legal/code_licence.html
=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
package Bio::EnsEMBL::Variation::Pipeline::DataDumps::ReleaseDumps_conf;
use strict;
use warnings;
use base ('Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf');
sub default_options {
my ($self) = @_;
# The hash returned from this function is used to configure the
# pipeline, you can supply any of these options on the command
# line to override these default values.
# You shouldn't need to edit anything in this file other than
# these values, if you find you do need to then we should probably
# make it an option here, contact the variation team to discuss
# this - patches are welcome!
return {
hive_force_init => 1,
hive_use_param_stack => 0,
hive_use_triggers => 0,
# general pipeline options that you should change to suit your environment
hive_root_dir => $ENV{'HOME'} . '/HEAD/ensembl-hive',
ensembl_cvs_root_dir => $ENV{'HOME'} . '/HEAD',
# a name for your pipeline (will also be used in the name of the hive database)
pipeline_name => 'test_data_dumps_e' . $self->o('ensembl_release'),
# a directory to keep hive output files and your registry file, you should
# create this if it doesn't exist
pipeline_dir => '/lustre/scratch110/ensembl/at7/develop/test/data_dumps/',
# a directory where hive workers will dump STDOUT and STDERR for their jobs
# if you use lots of workers this directory can get quite big, so it's
# a good idea to keep it on lustre, or some other place where you have a
# healthy quota!
output_dir => $self->o('pipeline_dir') . '/hive_output',
# a standard ensembl registry file containing connection parameters
# for your target database(s) (and also possibly aliases for your species
# of interest that you can then supply to init_pipeline.pl with the -species
# option)
reg_file => $self->o('pipeline_dir') . '/ensembl.registry.75',
config_file => $self->o('pipeline_dir') . '/ovis_aries_75.json',
tmp_dir => $self->o('pipeline_dir') . '/tmp',
script_dir => $self->o('ensembl_cvs_root_dir') . '/ensembl-variation/scripts',
gvf_validator => '/nfs/users/nfs_a/at7/tools/gvf_validator',
so_file => '/nfs/users/nfs_a/at7/obo/e74/so.obo',
debug => 0,
# init_pipeline.pl will create the hive database on this machine, naming it
# <username>_<pipeline_name>, and will drop any existing database with this
# name
hive_db_host => 'ens-variation',
hive_db_port => 3306,
hive_db_user => 'ensadmin',
pipeline_db => {
-host => $self->o('hive_db_host'),
-port => $self->o('hive_db_port'),
-user => $self->o('hive_db_user'),
-pass => $self->o('hive_db_password'),
-dbname => $ENV{'USER'} . '_' . $self->o('pipeline_name'),
-driver => 'mysql',
},
};
}
sub pipeline_wide_parameters {
my ($self) = @_;
return {
%{$self->SUPER::pipeline_wide_parameters}, # here we inherit anything from the base class
release => $self->o('ensembl_release'),
ensembl_registry => $self->o('reg_file'),
config_file => $self->o('config_file'),
output_path => $self->o('pipeline_dir'),
debug => $self->o('debug'),
data_dump_dir => $self->o('pipeline_dir'),
tmp_dir => $self->o('tmp_dir'),
script_dir => $self->o('script_dir'),
so_file => $self->o('so_file'),
gvf_validator => $self->o('gvf_validator'),
config_file => $self->o('config_file'),
};
}
sub resource_classes {
my ($self) = @_;
return {
%{$self->SUPER::resource_classes},
'default' => { 'LSF' => '-R"select[mem>4000] rusage[mem=4000]" -M4000'},
'urgent' => { 'LSF' => '-q yesterday -R"select[mem>2000] rusage[mem=2000]" -M2000'},
'highmem' => { 'LSF' => '-R"select[mem>15000] rusage[mem=15000]" -M15000'}, # this is Sanger LSF speak for "give me 15GB of memory"
'long' => { 'LSF' => '-q long -R"select[mem>2000] rusage[mem=2000]" -M2000'},
};
}
sub pipeline_analyses {
my ($self) = @_;
my @analyses;
push @analyses, (
{ -logic_name => 'pre_run_checks_gvf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::PreRunChecks',
-input_ids => [{},],
-max_retry_count => 1,
-flow_into => {
1 => ['species_factory_gvf_dumps'],
},
-parameters => {
'file_type' => 'gvf',
},
},
{ -logic_name => 'species_factory_gvf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SpeciesFactory',
-analysis_capacity => 3,
-flow_into => {
'2->A' => ['init_dump'],
'A->1' => ['report_gvf_dumps']
},
},
{ -logic_name => 'init_dump',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::InitSubmitJob',
-analysis_capacity => 5,
-flow_into => {
1 => ['submit_job_gvf_dumps'],
},
-parameters => {
'file_type' => 'gvf',
'job_type' => 'dump',
},
-rc_name => 'default',
},
{ -logic_name => 'submit_job_gvf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SubmitJob',
-max_retry_count => 1,
-rc_name => 'default',
},
{ -logic_name => 'report_gvf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::Report',
-parameters => {
'file_type' => 'gvf',
'report_name' => 'ReportDumpGVF',
},
-flow_into => {1 => ['species_factory_validate_gvf']},
},
{ -logic_name => 'species_factory_validate_gvf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SpeciesFactory',
-analysis_capacity => 3,
-flow_into => {
'2->A' => ['join_dump'],
'A->1' => ['summary_validate_gvf']
},
-parameters => {
'file_type' => 'gvf',
},
},
{ -logic_name => 'join_dump',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::JoinDump',
-flow_into => {
1 => ['validate_gvf'],
}
},
{ -logic_name => 'validate_gvf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::ValidateDump',
-parameters => {
'file_type' => 'gvf',
'so_file' => $self->o('so_file'),
'gvf_validator' => $self->o('gvf_validator'),
},
},
{ -logic_name => 'summary_validate_gvf', # die if Error?
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SummariseValidation',
-parameters => {
'file_type' => 'gvf',
},
-flow_into => {
1 => ['clean_up_gvf_dumps']
},
},
{ -logic_name => 'clean_up_gvf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::CleanUp',
-flow_into => {
1 => ['pre_run_checks_gvf2vcf']
},
-parameters => {
'file_type' => 'gvf',
},
},
{ -logic_name => 'pre_run_checks_gvf2vcf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::PreRunChecks',
-max_retry_count => 1,
-flow_into => {
1 => ['species_factory_gvf2vcf'],
},
-parameters => {
'file_type' => 'vcf',
},
},
{ -logic_name => 'species_factory_gvf2vcf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SpeciesFactory',
-analysis_capacity => 3,
-flow_into => {
'2->A' => ['init_parse'],
'A->1' => ['summary_validate_vcf']
},
-parameters => {
'file_type' => 'vcf',
},
},
{ -logic_name => 'init_parse',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::InitSubmitJob',
-flow_into => {
1 => ['submit_job_gvf2vcf'],
},
-parameters => {
'file_type' => 'vcf',
'job_type' => 'parse',
},
},
{ -logic_name => 'submit_job_gvf2vcf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SubmitJob',
-flow_into => {
1 => ['validate_vcf'],
},
},
{ -logic_name => 'validate_vcf',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::ValidateVCF',
-parameters => {
'file_type' => 'vcf',
},
},
{ -logic_name => 'summary_validate_vcf', # die if Error?
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::SummariseValidation',
-parameters => {
'file_type' => 'vcf',
},
-flow_into => {
1 => ['clean_up_vcf_dumps'],
},
},
{ -logic_name => 'clean_up_vcf_dumps',
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::CleanUp',
-parameters => {
'file_type' => 'vcf',
},
-flow_into => {
1 => ['finish'],
},
},
{ -logic_name => 'finish', # readme,
-module => 'Bio::EnsEMBL::Variation::Pipeline::DataDumps::FinishDump',
},
);
return \@analyses;
}
1;
| dbolser-ebi/ensembl-variation | modules/Bio/EnsEMBL/Variation/Pipeline/DataDumps/ReleaseDumps_conf.pm | Perl | apache-2.0 | 9,552 |
:- module(_, _, [functions]).
:- use_module(library(terms)).
:- use_module(ciaosrc('CIAOSETTINGS')).
:- use_module(ciaosrc('CIAOSHARED')).
:- reexport(ciaosrc('doc/common/LPDOCCOMMON')).
:- reexport(ciaosrc('CIAOSETTINGS'), [lpdoclib/1]).
:- redefining(_).
:- discontiguous fileoption/2.
% -*- mode: Makefile; -*-
% ----------------------------------------------------------------------------
%
% **** lpdoc document generation SETTINGS *****
%
% These SETTINGS should be changed to suit your application
%
% The defaults listed are suggestions and/or the ones used for local
% installation in the CLIP group machines.
% ----------------------------------------------------------------------------
% List of all directories where the .pl files to be documented can be found
% (separated by spaces; put explicit paths, i.e., do not use any variables)
% You also need to specify all the paths of files used by those files!
%
filepath := ~atom_concat( [ ~ciaosrc , '/library/class' ] )|
~atom_concat( [ ~ciaosrc , '/library/class/examples' ] )|
~atom_concat( [ ~ciaosrc , '/library/objects' ] )|
~atom_concat( [ ~ciaosrc , '/library/interface' ] )|
~atom_concat( [ ~ciaosrc , '/library' ] )|
~atom_concat( [ ~ciaosrc , '-0.9/doc/common' ] )|
~atom_concat( [ ~ciaosrc , '/library/objects/examples' ] ).
% ----------------------------------------------------------------------------
% List of all the *system* directories where .pl files used are
% (separated by spaces; put explicit paths, i.e., do not use any variables)
% You also need to specify all the paths of files used by those files!
% You can put these in FILEPATHS instead. Putting them here only
% means that the corresponding files will be assumed to be "system"
% files in the documentation.
%
systempath := ~atom_concat( [ ~ciaosrc , '/lib' ] )|
~atom_concat( [ ~ciaosrc , '/library' ] ).
% ----------------------------------------------------------------------------
% Define this to be the main file name (include a path only if it
% should appear in the documentation)
%
mainfile := 'ociao_doc'.
% ----------------------------------------------------------------------------
% Select pl2texi options for main file (do 'lpdoc -h' to get list of options)
% Leaving this blank produces most verbose manuals
% -v -nobugs -noauthors -noversion -nochangelog -nopatches -modes
% -headprops -literalprops -nopropnames -noundefined -nopropsepln -norefs
% -nobullet
%
%# MAINOPTS = -v -nobugs -nopatches
fileoption(~mainfile) := '-nopatches'.
% ----------------------------------------------------------------------------
% List of files to be used as components. These can be .pl files
% or .src files (manually produced files in texinfo format).
% (include a path only if it should appear in the documentation, i.e.,
% for sublibraries)
%
component := 'class_doc' | 'class_error_doc'|
'objects_doc' | 'objects_error_doc'|
'objects_rt' | 'dynclasses'|
'interface_doc'.
% ----------------------------------------------------------------------------
% Select lpdoc opts for component file(s)
% (see above or do 'lpdoc -h' to get complete list of opts))
% Leaving this blank produces most verbose manuals
%
%# COMPOPTS = -v -nobugs -modes -noversion -noauthors
fileoption(~component) := '-noversion' | '-noauthors'.
% ----------------------------------------------------------------------------
% Define this to be the list of documentation formats to be generated by
% default when typing gmake (*** keep them in this order ***)
% dvi ps ascii manl info infoindex html htmlindex
%
docformat := 'dvi'.
% ----------------------------------------------------------------------------
% Define this to be the list (separated by spaces) of indices to be
% generated ('all' generates all the supported indices)
% Note: too many indices may exceed the capacity of texinfo!
% concept lib apl pred prop regtype decl op modedef file usage
% all
%
index := 'concept' | 'pred' | 'prop' | 'regtype' | 'usage'.
% ----------------------------------------------------------------------------
% If you are using bibliographic references, define this to be the list
% (separated by commas, full paths, no spaces) of .bib files to be used
% to find them.
%
:- reexport(ciaosrc('CIAOSHARED'), [bibfile/1]).
% ----------------------------------------------------------------------------
% Only need to change these if you will be installing the docs somewhere else
% ----------------------------------------------------------------------------
% Define this to be the dir in which you want the document(s) installed.
%
:- reexport(ciaosrc('CIAOSETTINGS'), [docdir/1]).
% ----------------------------------------------------------------------------
% Uncomment this for .dvi and .ps files to be compressed on installation
% If uncommented, set it to path for gzip
%
% COMPRESSDVIPS = gzip
% ----------------------------------------------------------------------------
% Uncomment this to specify a gif to be used as page background in html
%
htmlbackground := 'http://www.clip.dia.fi.upm.es/images/Clip_bg.gif'.
% ----------------------------------------------------------------------------
% Define this to be the permissions for automatically generated data files
%
datapermissions := perm(rw, rw, r).
% ----------------------------------------------------------------------------
% Define this to be the perms for automatically generated dirs and exec files
%
execpermissions := perm(rwx, rwx, rx).
% ----------------------------------------------------------------------------
% The settings below are important only for generating html and info *indices*
% ----------------------------------------------------------------------------
% Define this to be files containing header and tail for the html index.
% Pointers to the files generated by lpdoc are placed in a document that
% starts with HTMLINDEXHEADFILE and finishes with HTMLINDEXTAILFILE
%
% HTMLINDEXHEADFILE = $(LIBDIR)/Head_generic.html
htmlindex_headfile := ~atom_concat( [ ~lpdoclib , '/Head_clip.html' ] ).
% HTMLINDEXTAILFILE = $(LIBDIR)/Tail_generic.html
htmlindex_tailfile := ~atom_concat( [ ~lpdoclib , '/Tail_clip.html' ] ).
% ----------------------------------------------------------------------------
% Define this to be files containing header and tail for the info "dir" index.
% dir entries generated by lpdoc are placed in a "dir" file that
% starts with INFODIRHEADFILE and finishes with INFODIRTAILFILE
%
% INFODIRHEADFILE = $(LIBDIR)/Head_generic.info
infodir_headfile := ~atom_concat( [ ~lpdoclib , '/Head_clip.info' ] ).
% INFODIRTAILFILE = $(LIBDIR)/Tail_generic.info
infodir_tailfile := ~atom_concat( [ ~lpdoclib , '/Tail_clip.info' ] ).
%
startpage := 91.
% ----------------------------------------------------------------------------
% end of SETTINGS
| leuschel/ecce | www/CiaoDE/ciao/library/objects/Doc/LPSETTINGS.pl | Perl | apache-2.0 | 6,893 |
package Paws::SDB::GetAttributes;
use Moose;
has AttributeName => (is => 'ro', isa => 'Str');
has ConsistentRead => (is => 'ro', isa => 'Bool');
has DomainName => (is => 'ro', isa => 'Str', required => 1);
has ItemName => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetAttributes');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SDB::GetAttributesResult');
class_has _result_key => (isa => 'Str', is => 'ro', default => 'GetAttributesResult');
1;
### main pod documentation begin ###
=head1 NAME
Paws::SDB::GetAttributes - Arguments for method GetAttributes on Paws::SDB
=head1 DESCRIPTION
This class represents the parameters used for calling the method GetAttributes on the
Amazon SimpleDB service. Use the attributes of this class
as arguments to method GetAttributes.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetAttributes.
As an example:
$service_obj->GetAttributes(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 AttributeName => Str
The names of the attributes.
=head2 ConsistentRead => Bool
Determines whether or not strong consistency should be enforced when
data is read from SimpleDB. If C<true>, any data previously written to
SimpleDB will be returned. Otherwise, results will be consistent
eventually, and the client may not see data that was written
immediately before your read.
=head2 B<REQUIRED> DomainName => Str
The name of the domain in which to perform the operation.
=head2 B<REQUIRED> ItemName => Str
The name of the item.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method GetAttributes in L<Paws::SDB>
=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/SDB/GetAttributes.pm | Perl | apache-2.0 | 2,236 |
package Google::Ads::AdWords::v201809::GoalOptimizedShoppingAd;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use base qw(Google::Ads::AdWords::v201809::Ad);
# Variety: sequence
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %id_of :ATTR(:get<id>);
my %url_of :ATTR(:get<url>);
my %displayUrl_of :ATTR(:get<displayUrl>);
my %finalUrls_of :ATTR(:get<finalUrls>);
my %finalMobileUrls_of :ATTR(:get<finalMobileUrls>);
my %finalAppUrls_of :ATTR(:get<finalAppUrls>);
my %trackingUrlTemplate_of :ATTR(:get<trackingUrlTemplate>);
my %finalUrlSuffix_of :ATTR(:get<finalUrlSuffix>);
my %urlCustomParameters_of :ATTR(:get<urlCustomParameters>);
my %urlData_of :ATTR(:get<urlData>);
my %automated_of :ATTR(:get<automated>);
my %type_of :ATTR(:get<type>);
my %devicePreference_of :ATTR(:get<devicePreference>);
my %systemManagedEntitySource_of :ATTR(:get<systemManagedEntitySource>);
my %Ad__Type_of :ATTR(:get<Ad__Type>);
__PACKAGE__->_factory(
[ qw( id
url
displayUrl
finalUrls
finalMobileUrls
finalAppUrls
trackingUrlTemplate
finalUrlSuffix
urlCustomParameters
urlData
automated
type
devicePreference
systemManagedEntitySource
Ad__Type
) ],
{
'id' => \%id_of,
'url' => \%url_of,
'displayUrl' => \%displayUrl_of,
'finalUrls' => \%finalUrls_of,
'finalMobileUrls' => \%finalMobileUrls_of,
'finalAppUrls' => \%finalAppUrls_of,
'trackingUrlTemplate' => \%trackingUrlTemplate_of,
'finalUrlSuffix' => \%finalUrlSuffix_of,
'urlCustomParameters' => \%urlCustomParameters_of,
'urlData' => \%urlData_of,
'automated' => \%automated_of,
'type' => \%type_of,
'devicePreference' => \%devicePreference_of,
'systemManagedEntitySource' => \%systemManagedEntitySource_of,
'Ad__Type' => \%Ad__Type_of,
},
{
'id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
'url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'finalUrls' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'finalMobileUrls' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'finalAppUrls' => 'Google::Ads::AdWords::v201809::AppUrl',
'trackingUrlTemplate' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'finalUrlSuffix' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'urlCustomParameters' => 'Google::Ads::AdWords::v201809::CustomParameters',
'urlData' => 'Google::Ads::AdWords::v201809::UrlData',
'automated' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean',
'type' => 'Google::Ads::AdWords::v201809::Ad::Type',
'devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
'systemManagedEntitySource' => 'Google::Ads::AdWords::v201809::SystemManagedEntitySource',
'Ad__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
},
{
'id' => 'id',
'url' => 'url',
'displayUrl' => 'displayUrl',
'finalUrls' => 'finalUrls',
'finalMobileUrls' => 'finalMobileUrls',
'finalAppUrls' => 'finalAppUrls',
'trackingUrlTemplate' => 'trackingUrlTemplate',
'finalUrlSuffix' => 'finalUrlSuffix',
'urlCustomParameters' => 'urlCustomParameters',
'urlData' => 'urlData',
'automated' => 'automated',
'type' => 'type',
'devicePreference' => 'devicePreference',
'systemManagedEntitySource' => 'systemManagedEntitySource',
'Ad__Type' => 'Ad.Type',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201809::GoalOptimizedShoppingAd
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
GoalOptimizedShoppingAd from the namespace https://adwords.google.com/api/adwords/cm/v201809.
Represents a Smart Shopping ad that optimizes towards your goals. A Smart Shopping ad targets multiple advertising channels across Search, Google Display Network, and YouTube with a focus on retail. This supports ads that display product data (managed using the Google Merchant Center) as specified in the parent campaign's {@linkplain ShoppingSetting Shopping setting} as well as ads using advertiser provided asset data. <p class="caution"><b>Caution:</b> Smart Shopping ads do not use {@link #url url}, {@link #finalUrls finalUrls}, {@link #finalMobileUrls finalMobileUrls}, {@link #finalAppUrls finalAppUrls}, or {@link #displayUrl displayUrl}; setting these fields on a Smart Shopping ad will cause an error. <span class="constraint AdxEnabled">This is enabled for AdX.</span>
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/GoalOptimizedShoppingAd.pm | Perl | apache-2.0 | 5,282 |
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::azure::management::resource::mode::deploymentsstatus;
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 = sprintf("Status '%s' [Duration: %s] [Last modified: %s]", $self->{result_values}->{status},
$self->{result_values}->{duration},
$self->{result_values}->{last_modified});
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'};
$self->{result_values}->{duration} = centreon::plugins::misc::change_seconds(value => $options{new_datas}->{$self->{instance} . '_duration'});
$self->{result_values}->{last_modified} = $options{new_datas}->{$self->{instance} . '_last_modified'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub prefix_global_output {
my ($self, %options) = @_;
return "Deployments ";
}
sub prefix_deployment_output {
my ($self, %options) = @_;
return "Deployment '" . $options{instance_value}->{display} . "' ";
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'global', type => 0, cb_prefix_output => 'prefix_global_output' },
{ name => 'deployments', type => 1, cb_prefix_output => 'prefix_deployment_output', message_multiple => 'All deployments are ok' },
];
$self->{maps_counters}->{global} = [
{ label => 'total-succeeded', set => {
key_values => [ { name => 'succeeded' } ],
output_template => "succeeded : %s",
perfdatas => [
{ label => 'total_succeeded', value => 'succeeded', template => '%d', min => 0 },
],
}
},
{ label => 'total-failed', set => {
key_values => [ { name => 'failed' } ],
output_template => "failed : %s",
perfdatas => [
{ label => 'total_failed', value => 'failed', template => '%d', min => 0 },
],
}
},
];
$self->{maps_counters}->{deployments} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'status' }, { name => 'duration' }, { name => 'last_modified' }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"resource-group:s" => { name => 'resource_group' },
"filter-counters:s" => { name => 'filter_counters' },
"warning-status:s" => { name => 'warning_status', default => '' },
"critical-status:s" => { name => 'critical_status', default => '%{status} ne "Succeeded"' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (!defined($self->{option_results}->{resource_group}) || $self->{option_results}->{resource_group} eq '') {
$self->{output}->add_option_msg(short_msg => "Need to specify --resource-group option");
$self->{output}->option_exit();
}
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
sub manage_selection {
my ($self, %options) = @_;
$self->{global} = {
succeeded => 0, failed => 0,
};
$self->{deployments} = {};
my $deployments = $options{custom}->azure_list_deployments(resource_group => $self->{option_results}->{resource_group});
foreach my $deployment (@{$deployments}) {
my $duration = $options{custom}->convert_duration(time_string => $deployment->{properties}->{duration});
$self->{deployments}->{$deployment->{id}} = {
display => $deployment->{name},
status => $deployment->{properties}->{provisioningState},
duration => $duration,
last_modified => ($deployment->{properties}->{timestamp} =~ /^(.*)\..*$/) ? $1 : '',
};
foreach my $status (keys %{$self->{global}}) {
$self->{global}->{$status}++ if ($deployment->{properties}->{provisioningState} =~ /$status/i);
}
}
if (scalar(keys %{$self->{deployments}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No deployments found.");
$self->{output}->option_exit();
}
}
1;
__END__
=head1 MODE
Check deployments status.
Example:
perl centreon_plugins.pl --plugin=cloud::azure::management::resource::plugin --custommode=azcli --mode=deployments-status
--filter-counters='^total-failed$' --critical-total-failed='1' --verbose
=over 8
=item B<--resource-group>
Set resource group (Required).
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='^total-succeeded$'
=item B<--warning-status>
Set warning threshold for status (Default: '').
Can used special variables like: %{status}, %{display}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} ne "Succeeded"').
Can used special variables like: %{status}, %{display}
=item B<--warning-*>
Threshold warning.
Can be: 'total-succeeded', 'total-failed'.
=item B<--critical-*>
Threshold critical.
Can be: 'total-succeeded', 'total-failed'.
=back
=cut
| centreon/centreon-plugins | cloud/azure/management/resource/mode/deploymentsstatus.pm | Perl | apache-2.0 | 6,814 |
## OpenXPKI::FileUtils
package OpenXPKI::FileUtils;
use strict;
use warnings;
use English;
use Class::Std;
use OpenXPKI::Debug;
use OpenXPKI::Exception;
use File::Spec;
use File::Temp;
use Fcntl qw( :DEFAULT );
my %safe_filename_of :ATTR; # a hash of filenames created with safe_tmpfile
my %safe_dir_of :ATTR; # a hash of directories created with safe_tmpdir
my %temp_handles :ATTR;
my %temp_dir :ATTR;
=head1 OpenXPKI::FileUtils
Helper class for file operations and temp file management.
=head2 Parameters
The constructor expects arguments as a hash.
=over
=item TMP
The parent directory to use for all temporary items created. If not
set I</tmp> is used.
=back
=cut
sub BUILD {
my ($self, $ident, $arg_ref ) = @_;
$temp_handles{$ident} = [];
if ($arg_ref && $arg_ref->{TMP}) {
$temp_dir{$ident} = $arg_ref->{TMP};
} else {
$temp_dir{$ident} = '/tmp';
}
}
=head1 Functions
=head2 read_file I<filename>, I<encoding>
Reads the content of the given filename and returns it as string, pass
I<utf8> as second parameter to read the file in utf8 mode. Throws an
exception if the file can not be read.
=cut
sub read_file {
my $self = shift;
my $ident = ident $self;
my $filename = shift;
my $encoding = shift || '';
if (! defined $filename) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_READ_FILE_MISSING_PARAMETER',
);
}
if (! -e $filename) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_READ_FILE_DOES_NOT_EXIST',
params => {'FILENAME' => $filename});
}
if (! -r $filename) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_READ_FILE_NOT_READABLE',
params => {'FILENAME' => $filename});
}
my $enc = '';
if ($encoding eq 'utf8') {
$enc = ':encoding(UTF-8)';
}
my $result = do {
open my $HANDLE, "<$enc", $filename;
if (! $HANDLE) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_READ_FILE_OPEN_FAILED',
params => {'FILENAME' => $filename});
}
# slurp mode
local $INPUT_RECORD_SEPARATOR; # long version of $/
<$HANDLE>;
};
return $result;
}
=head2 write_file I<{ FILENAME, CONTENT, FORCE }>
Expects a hash with the keys I<CONTENT> and I<FILENAME>. The method will
B<NOT> overwrite an existing file but throw an exception if the target
already exists, unless I<FORCE> is passed a true value or the filename
is a tempfile created by I<get_safe_tmpfile> before.
=cut
sub write_file {
my $self = shift;
my $ident = ident $self;
my $arg_ref = shift;
my $filename = $arg_ref->{FILENAME};
my $content = $arg_ref->{CONTENT};
if (! defined $filename) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_WRITE_FILE_NO_FILENAME_SPECIFIED',
);
}
if (! defined $content) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_WRITE_FILE_NO_CONTENT_SPECIFIED',
);
}
if ((-e $filename) and
not $arg_ref->{FORCE} and
(not ref $self or
not $safe_filename_of{$ident} or
not $safe_filename_of{$ident}->{$filename})) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_WRITE_FILE_ALREADY_EXISTS',
params => {'FILENAME' => $filename});
}
my $mode = O_WRONLY | O_TRUNC;
if (! -e $filename) {
$mode |= O_EXCL | O_CREAT;
}
my $HANDLE;
if (not sysopen($HANDLE, $filename, $mode))
{
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_WRITE_FILE_OPEN_FAILED',
params => {'FILENAME' => $filename});
}
print {$HANDLE} $content;
close $HANDLE;
}
=head2 get_safe_tmpfile { TMP }
Create an emtpty tempfile and returns its name. You can pass a hash with
the key I<TMP> set to the parent directory to use, if not set the
directory given to the constructor is used.
The file will B<NOT> be removed unless you call the I<cleanup> method of
this class instance.
=cut
sub get_safe_tmpfile {
##! 1: 'start'
my $self = shift;
my $ident = ident $self;
my $arg_ref = shift;
##! 2: 'build template'
my $template = $self->__get_safe_template($arg_ref);
##! 2: 'build tmp file'
# with UNLINK => 1 the file will be scheduled for deletion after the
# file handle goes out of scope which is the end of this method!
# this might lead to a race condition where the caller writes to the
# file whereas the OS removes the file from the (visible) filesystem
# The class will keep a list of files internally and remove those when
# the I<cleanup> method is called
my $fh = File::Temp->new( TEMPLATE => $template, UNLINK => 0 );
if (! $fh) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_GET_SAFE_TMPFILE_MAKE_FAILED'
);
}
my $filename = $fh->filename;
close $fh;
##! 2: 'fix mode'
chmod 0600, $filename;
$safe_filename_of{$ident}->{$filename} = 1;
##! 1: 'end: $filename'
return $filename;
}
=head2 get_safe_tmpdir
Create an emtpty directory and returns its name. You can pass a hash with
the key I<TMP> set to the parent directory to use, if not set the
directory given to the constructor is used.
The directory will B<NEVER> be removed autmatically.
=cut
sub get_safe_tmpdir {
##! 1: 'start'
my $self = shift;
my $ident = ident $self;
my $arg_ref = shift;
##! 2: 'build template'
my $template = $self->__get_safe_template ($arg_ref);
##! 2: 'build tmp file'
my $dir = File::Temp::mkdtemp($template);
if (! -d $dir) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_GET_SAFE_TMPDIR_MAKE_FAILED',
params => {'DIR' => $dir});
}
##! 2: 'fix mode'
chmod 0700, $dir;
$safe_dir_of{$ident}->{$dir} = 1;
##! 1: 'end: $filename'
return $dir;
}
=head2 get_tmp_handle
Create a temporary file and return the object handle of it.
The return value can be used in string context to get the name of the
directory created. The handle will be held open by the class so it will
stay in the filesystem until the class is destroyed.
=cut
sub get_tmp_handle {
my $self = shift;
my $ident = ident $self;
my $fh = File::Temp->new(
TEMPLATE => $self->__get_safe_template({ TMP => $temp_dir{$ident} }),
);
# enforce umask
chmod 0600, $fh->filename;
push @{$temp_handles{$ident}}, $fh;
return $fh;
}
=head2 get_tmp_dirhandle
Create a temporary directory and return the object handle of it.
The return value can be used in string context to get the name of the
directory created. The handle will be held open by the class so it will
stay in the filesystem until the class is destroyed.
=cut
sub get_tmp_dirhandle {
my $self = shift;
my $ident = ident $self;
my $fh = File::Temp->newdir(
TEMPLATE => $self->__get_safe_template({ TMP => $temp_dir{$ident} }),
);
# enforce umask
chmod 0700, $fh->dirname;
push @{$temp_handles{$ident}}, $fh;
return $fh;
}
=head2 write_temp_file
Expects the content to write as argument. Creates a temporary file handle
using get_tmp_handle and writes the data to it. The filehandle is closed
and the name of the file is returned.
=cut
sub write_temp_file {
my $self = shift;
my $ident = ident $self;
my $content = shift;
if (! defined $content) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_WRITE_FILE_NO_CONTENT_SPECIFIED',
);
}
my $fh = $self->get_tmp_handle();
my $filename = $fh->filename;
print {$fh} $content;
close $fh;
return $filename ;
}
sub __get_safe_template
{
##! 1: 'start'
my $self = shift;
my $ident = ident $self;
my $arg_ref = shift;
my $tmpdir = $arg_ref->{TMP} || $temp_dir{$ident};
##! 2: 'check TMP'
if (!$tmpdir) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_GET_SAFE_TEMPLATE_MISSING_TMP');
}
if (not -d $tmpdir) {
OpenXPKI::Exception->throw (
message => 'I18N_OPENXPKI_FILEUTILS_GET_SAFE_TEMPLATE_DIR_DOES_NOT_EXIST',
params => {DIR => $tmpdir});
}
##! 2: 'build template'
return File::Spec->catfile($tmpdir, "openxpki${PID}XXXXXXXX");
}
=head2 cleanup
Unlink files created with get_safe_tempfile and remove all handles
held by the instance so File::Temp should cleanup them.
B<Warning>: This method is not fork-safe and will delete any files
created with get_safe_tempfile across forks!
=cut
sub cleanup {
my $self = shift;
my $ident = ident $self;
$temp_handles{$ident} = [];
# when the KEEP_ALL marker is set we also do not run our cleanup
return if ($File::Temp::KEEP_ALL);
foreach my $file (keys %{$safe_filename_of{$ident}}) {
if (-e $file) {
unlink($file);
delete $safe_filename_of{$ident}->{$file};
}
}
return 1;
}
1;
__END__
| openxpki/openxpki | core/server/OpenXPKI/FileUtils.pm | Perl | apache-2.0 | 9,292 |
package Fixtures::Region;
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
use Moose;
extends 'DBIx::Class::EasyFixture';
use namespace::autoclean;
my %definition_for = (
mile_high => {
new => 'Region',
using => {
id => 1,
name => 'Denver Region',
division => 1,
},
},
boulder => {
new => 'Region',
using => {
id => 2,
name => 'Boulder Region',
division => 1,
},
},
);
sub get_definition {
my ( $self, $name ) = @_;
return $definition_for{$name};
}
sub all_fixture_names {
return keys %definition_for;
}
__PACKAGE__->meta->make_immutable;
1;
| knutsel/traffic_control-1 | traffic_ops/app/lib/Fixtures/Region.pm | Perl | apache-2.0 | 1,109 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::Analysis::Runnable::Aspera
=head1 SYNOPSIS
=head1 DESCRIPTION
=cut
package Bio::EnsEMBL::Analysis::Runnable::Aspera;
use strict;
use warnings;
use Bio::EnsEMBL::Analysis::Tools::Logger qw(logger_verbosity logger_info);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use Bio::EnsEMBL::Analysis::Tools::Utilities qw(locate_executable execute_with_wait);
use File::Spec::Functions qw(catfile splitpath);
=head2 new
Arg [PROGRAM] : String
Arg [USE_THREADING]: Integer
Arg [VERBOSE] : Integer
Description: Creates a Bio::EnsEMBL::Analysis::Runnable::Samtools object to run samtools command
Returntype : Bio::EnsEMBL::Analysis::Runnable::Samtools
Exceptions : None
=cut
sub new {
my ($class,@args) = @_;
my $self = bless {},$class;
my ($program, $sshkey, $verbose) = rearrange( [ qw( PROGRAM SSHKEY VERBOSE) ], @args);
$program = 'ascp' unless ($program);
$self->program($program);
if (!$sshkey and exists $ENV{LINUXBREW_HOME}) {
$sshkey = catfile($ENV{LINUXBREW_HOME}, 'etc', 'asperaweb_id_dsa.openssh');
}
$self->sshkey($sshkey);
logger_verbosity($verbose) if ($verbose);
return $self;
}
=head2 program
Arg [1] : String (optional) $program
Description: Getter/setter for the binary. It tries to locate properly the executable
Returntype : String
Exceptions : Throw if it can't find the executable Arg[1]
=cut
sub program {
my ($self, $file) = @_;
if ($file) {
$self->{_program} = locate_executable($file);
}
return $self->{_program};
}
=head2 sshkey
Arg [1] : String path to sshkey file
Description: Getter/setter for the ssh key file
Returntype : String path
Exceptions : Throws if the file does not exists
=cut
sub sshkey {
my ($self, $file) = @_;
if ($file) {
if (-e $file) {
$self->{_sshkey_file} = $file;
}
else {
throw('Could not find ssh key file '.$file);
}
if ($self->options) {
$self->options =~ s/-i \S+/-i $file/;
}
else {
$self->options('-i '.$file);
}
}
return $self->{_sshkey_file};
}
sub options {
my ($self, $options) = @_;
if ($options) {
$self->{_options} = $options;
if ($self->sshkey and $options !~ /-i \S+/) {
$self->{_options} .= ' -i '.$self->sshkey;
}
}
return $self->{_options};
}
sub source {
my ($self, $source) = @_;
if ($source) {
$self->{_source} = $source;
}
return $self->{_source};
}
sub target {
my ($self, $target) = @_;
if ($target) {
$self->{_target} = $target;
}
return $self->{_target};
}
sub fetch {
my ($self, $source, $target) = @_;
$source = $self->source unless ($source);
$target = $self->target unless ($target);
throw("Could not find $target") unless (-e $target);
my $options = $self->options;
my $cmd = $self->program.' '.$self->options.' '.$source.' '.$target;
execute_with_wait($cmd);
my (undef, undef, $file) = splitpath($source);
return catfile($target, $file);
}
sub put {
my ($self, $source, $target) = @_;
$source = $self->source unless ($source);
$target = $self->target unless ($target);
throw("Could not find $source") unless (-e $source);
my $cmd = $self->program.' '.$self->options.' '.$source.' '.$target;
execute_with_wait($cmd);
}
1;
| Ensembl/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/Aspera.pm | Perl | apache-2.0 | 4,288 |
#! /usr/bin/perl
use utf8;
use strict;
use warnings;
die "perl $0 <kegg.path> <the first number> \n" unless(@ARGV eq 2);
my(%ra, %qv);
open FA, $ARGV[0] or die $!;
<FA>;
while(<FA>)
{
chomp;
my @tmp = split /\t/;
my $ratio = $tmp[3] / $tmp[4];
$ra{$tmp[2]} = $ratio;
$qv{$tmp[2]} = "$tmp[6]\t$tmp[3]";
}
close FA;
my(%hash, $n);
open TMP, "> $ARGV[0].tmp" or die $!;
foreach(sort {$ra{$b} <=> $ra{$a}} keys %ra)
{
$n ++;
last if($n > $ARGV[1]);
my $path = $_;
$path =~ s/'/\'/g;
$path =~ s/"/\"/g;
print TMP "$path\t$ra{$_}\t$qv{$_}\n";
}
close TMP;
open RCMD, "> $ARGV[0].r" or die $!;
print RCMD "
library(ggplot2)
mat <- read.table(\"$ARGV[0].tmp\", sep = \"\t\", check.names = 0, header = F, quote=\"\")
matmp = as.matrix(mat)
matmpx = arrayInd(order(matmp,decreasing=TRUE)[1:1],dim(matmp))
matx = mat[matmpx[1,1],matmpx[1,2]]
matmpi = arrayInd(order(matmp,decreasing=FALSE)[1:1],dim(matmp))
mati = mat[matmpi[1,1],matmpi[1,2]]
if (matx == mati)
{
p <- ggplot(mat, aes(mat\$V2, mat\$V1))
p + geom_point(aes(size = mat\$V4,colour = mat\$V3)) + scale_size(\"GeneNumber\") + scale_colour_continuous(\"QValue\", low=\"red\", high = \"forestgreen\") + labs(title = \"Top $ARGV[1] of Pathway Enrichment\", x = \"RichFactor\", y = \"Pathway\") + theme_bw()
ggsave(file = \"$ARGV[0].png\", dpi = 300)
}else{
p <- ggplot(mat, aes(mat\$V2, mat\$V1))
p + geom_point(aes(size = mat\$V4,colour = \"red\")) + scale_size(\"GeneNumber\") + labs(title = \"Top $ARGV[1] of Pathway Enrichment\", x = \"RichFactor\", y = \"Pathway\") + theme_bw()
ggsave(file = \"$ARGV[0].png\", dpi = 300)
}
";
`Rscript $ARGV[0].r`;
`rm $ARGV[0].tmp $ARGV[0].r Rplots.pdf -rf`;
| BaconKwan/Perl_programme | utility/keggGradient.pl | Perl | apache-2.0 | 1,669 |
package OpenXPKI::Test::ConfigWriter;
use Moose;
use utf8;
=head1 NAME
OpenXPKI::Test::ConfigWriter - Create test configuration files (YAML)
=cut
# Core modules
use File::Path qw(make_path);
use File::Spec;
# CPAN modules
use Moose::Util::TypeConstraints;
use YAML::Tiny 1.69;
use Test::More;
use Test::Exception;
use Test::Deep::NoTest qw( eq_deeply bag ); # use eq_deeply() without beeing in a test
=head1 DESCRIPTION
Methods to create a configuration consisting of several YAML files for tests.
=cut
# TRUE if the initial configuration has been written
has is_written => (
is => 'rw',
isa => 'Bool',
init_arg => undef,
default => 0,
);
has basedir => (
is => 'rw',
isa => 'Str',
required => 1,
);
has _config => (
is => 'ro',
isa => 'HashRef',
default => sub { {} },
init_arg => undef, # disable assignment via construction
);
# Following attributes must be lazy => 1 because their builders access other attributes
has path_config_dir => ( is => 'rw', isa => 'Str', lazy => 1, default => sub { shift->basedir."/etc/openxpki/config.d" } );
has path_log_file => ( is => 'rw', isa => 'Str', lazy => 1, default => sub { shift->basedir."/var/log/openxpki/catchall.log" } );
has path_openssl => ( is => 'rw', isa => 'Str', default => "/usr/bin/openssl" );
has path_javaks_keytool => ( is => 'rw', isa => 'Str', default => "/usr/bin/keytool" );
has path_openca_scep => ( is => 'rw', isa => 'Str', default => "/usr/bin/openca-scep" );
sub _make_dir {
my ($self, $dir) = @_;
return if -d $dir;
make_path($dir) or die "Could not create temporary directory $dir: $@"
}
sub _make_parent_dir {
my ($self, $filepath) = @_;
# Strip off filename portion to create parent dir
$self->_make_dir( File::Spec->catpath((File::Spec->splitpath( $filepath ))[0,1]) );
}
sub write_str {
my ($self, $filepath, $content) = @_;
die "Empty content for $filepath" unless $content;
$self->_make_parent_dir($filepath);
open my $fh, ">:encoding(UTF-8)", $filepath or die "Could not open $filepath for UTF-8 encoded writing: $@";
print $fh $content, "\n" or die "Could not write to $filepath: $@";
close $fh or die "Could not close $filepath: $@";
}
sub write_private_key {
my ($self, $realm, $alias, $pem_str) = @_;
my $filepath = $self->get_private_key_path($realm, $alias);
$self->_make_parent_dir($filepath);
$self->write_str($filepath, $pem_str);
}
sub remove_private_key {
my ($self, $realm, $alias) = @_;
my $filepath = $self->get_private_key_path($realm, $alias);
unlink $filepath or die "Could not remove file $filepath: $@";
}
sub write_yaml {
my ($self, $filepath, $data) = @_;
$self->_make_parent_dir($filepath);
note "Writing $filepath";
$self->write_str($filepath, YAML::Tiny->new($data)->write_string);
}
sub add_config {
my ($self, %entries) = @_;
# notify user about added custom config
my $pkg = __PACKAGE__; my $line; my $i = 0;
while ($pkg and ($pkg eq __PACKAGE__ or $pkg =~ /^(Eval::Closure::|Class::MOP::)/)) {
($pkg, $line) = (caller(++$i))[0,2];
}
# user specified config data might overwrite default configs
for (keys %entries) {
$self->_add_config_entry($_, $entries{$_}, "$pkg:$line");
}
}
# Add a configuration node (I<HashRef>) below the given configuration key
# (dot separated path in the config hierarchy)
#
# $config_writer->add_config('realm.alpha.workflow', $workflow);
sub _add_config_entry {
my ($self, $key, $data, $source) = @_;
die "add_config() must be called before create()" if $self->is_written;
my @parts = split /\./, $key;
my $node = $self->_config; # root node
my $overwrite_hint ="";
# given data is a structure (i.e.: "node")
if (ref $data eq 'HASH') {
for my $i (0..$#parts) {
$node->{$parts[$i]} //= {};
$node = $node->{$parts[$i]};
}
$overwrite_hint = " # replaces existing node (may be prevented by more precise config path)" if scalar keys %$node;
%{$node} = %$data; # intentionally replace any probably existing data
}
# given data is a config value (i.e. "leaf": scalar or e.g. array ref)
else {
my $last_key = $parts[-1];
for my $i (0..$#parts-1) {
$node->{$parts[$i]} //= {};
$node = $node->{$parts[$i]};
}
$overwrite_hint = " # replaces existing value" if $node->{$last_key};
$node->{$last_key} = $data;
}
note sprintf("- %s%s%s",
$key,
$source ? " ($source)" : "",
$overwrite_hint,
);
}
=head2 get_config_node
Returns a all config data that was defined below the given dot separated config
path. This might be a HashRef (config node) or a Scalar (config leaf).
B<Parameters>
=over
=item * I<$config_key> - dot separated configuration key/path
=item * I<$allow_undef> - set to 1 to return C<undef> instead of dying if the
config key is not found
=back
=cut
sub get_config_node {
my ($self, $config_key, $allow_undef) = @_;
# Part 1: exact matches and superkeys
my @parts = split /\./, $config_key;
my $node = $self->_config; # root node
for my $i (0..$#parts) {
$node = $node->{$parts[$i]}
or ($allow_undef ? return : die "Configuration key $config_key not found");
}
return $node;
}
sub create {
my ($self) = @_;
$self->_make_dir($self->path_config_dir);
$self->_make_parent_dir($self->path_log_file);
# write all config files
for my $level1 (sort keys %{$self->_config}) {
for my $level2 (sort keys %{$self->_config->{$level1}}) {
my $filepath = sprintf "%s/%s/%s.yaml", $self->path_config_dir, $level1, $level2;
$self->write_yaml($filepath, $self->_config->{$level1}->{$level2});
}
}
$self->is_written(1);
}
=head2 get_private_key_path
Returns the private key path for the certificate specified by realm and alias.
B<Parameters>
=over
=item * C<$realm> (I<Str>) - PKI realm
=item * C<$alias> (I<Str>) - Token alias incl. generation (i.e. "ca-signer-1")
=back
=cut
sub get_private_key_path {
my ($self, $realm, $alias) = @_;
return sprintf "%s/etc/openxpki/ca/%s/%s.pem", $self->basedir, $realm, $alias;
}
=head2 get_realms
Returns an ArrayRef with all realm names defined by default, by roles or user.
=cut
sub get_realms {
my ($self) = @_;
return [ keys %{ $self->_config->{system}->{realms} } ];
}
=head2 default_realm
Returns the first defined test realm. The result may be different if other roles
are applied to C<OpenXPKI::Test>.
=cut
sub default_realm {
my ($self) = @_;
return $self->get_realms->[0];
}
__PACKAGE__->meta->make_immutable;
| oliwel/openxpki | core/server/t/lib/OpenXPKI/Test/ConfigWriter.pm | Perl | apache-2.0 | 6,783 |
#!/usr/bin/env perl
# 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.
=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 Getopt::Long;
use ImportUtils qw(dumpSQL debug load);
use Bio::EnsEMBL::Utils::Exception qw(warning throw verbose);
use DBH;
use Bio::EnsEMBL::Variation::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp);
use FindBin qw( $Bin );
use POSIX;
use Data::Dumper;
use constant DISTANCE => 100_000;
use constant MAX_SHORT => 2**16 -1;
## Backslash Escaping
my %Printable = ( "\\"=>'\\', "\r"=>'r', "\n"=>'n', "\t"=>'t', "\""=>'"' );
my ($TMP_DIR, $TMP_FILE, $species, $allow_nulls);
GetOptions( 'tmpdir=s' => \$TMP_DIR,
'tmpfile=s' => \$TMP_FILE,
'species=s' => \$species,
'allownulls' => \$allow_nulls,
);
warn("Make sure you have an updated ensembl.registry file!\n");
usage('-TMP_DIR argument is required') if(!$TMP_DIR);
usage('-TMP_FILE argument is required') if(!$TMP_FILE);
usage('-species argument is required') if(!$species);
my $registry_file ||= $Bin . "/ensembl.registry";
Bio::EnsEMBL::Registry->load_all( $registry_file );
my $vdba = Bio::EnsEMBL::Registry->get_DBAdaptor($species,'variation');
my $dbCore = Bio::EnsEMBL::Registry->get_DBAdaptor($species,'core');
my $dbVar = $vdba->dbc->db_handle;
$ImportUtils::TMP_DIR = $TMP_DIR;
$ImportUtils::TMP_FILE = $TMP_FILE;
compress_genotypes($dbCore,$dbVar, $allow_nulls);
update_meta_coord($dbCore,$dbVar,"compressed_genotype_single_bp");
#reads the genotype and variation_feature data and compress it in one table with blob field
sub compress_genotypes{
my $dbCore = shift;
my $dbVar = shift;
my $allow_nulls = shift;
my $buffer;
my $genotypes = {}; #hash containing all the genotypes
my $blob = '';
my $count = 0;
my %rec_seq_region;
my $sth = $dbCore->dbc->prepare(qq{SELECT seq_region_id
FROM seq_region_attrib sa, attrib_type at
WHERE sa.attrib_type_id=at.attrib_type_id
AND at.code = "toplevel"});
$sth->execute();
while (my ($seq_region_id) = $sth->fetchrow_array()) {
$rec_seq_region{$seq_region_id} = 1;
}
debug("Checking whether compressed_genotype table exist or not");
my $table = "compressed_genotype_single_bp";
my $res_ref = $dbVar->selectall_arrayref(qq{SELECT * FROM $table limit 10});
my $table_rec = $res_ref->[0][0] ;
if ($table_rec) {
debug("TABLE $table have records exists, truncate the $table?");
$dbVar->do(qq{TRUNCATE TABLE $table});
}
print "Time starting to dump data from database: ",scalar(localtime(time)),"\n";
my $sql;
foreach my $seq_region_id (keys %rec_seq_region) {
if (! -e "$TMP_DIR/genotype_dump\_$seq_region_id") {
##for small amount of SNPs and a lot of seq_region_ids, such as zfish, it's slower to use this method
debug("Dumping seq_region_id $seq_region_id...");
$sql = qq{SELECT vf.seq_region_id, vf.seq_region_start, vf.seq_region_end, vf.seq_region_strand, ig.allele_1, ig.allele_2, ig.sample_id, vf.allele_string
FROM variation_feature vf, tmp_individual_genotype_single_bp ig
WHERE ig.variation_id = vf.variation_id
AND vf.map_weight = 1
};
if (!$allow_nulls)
{
$sql .= qq{AND ig.allele_1 <> 'N'
#AND ig.allele_2 <> 'N'
};
}
$sql .= qq{AND vf.seq_region_id = $seq_region_id
#AND ig.sample_id=11346
ORDER BY vf.seq_region_start
#ORDER BY vf.seq_region_id, vf.seq_region_start
};
dumpSQL($dbVar, $sql);
#information dumping from database
#system("sort -k 2 -g -o $TMP_DIR/genotype_dump\_$seq_region_id $TMP_DIR/$TMP_FILE");
system("mv $TMP_DIR/$TMP_FILE $TMP_DIR/genotype_dump\_$seq_region_id");
}
open IN, "$TMP_DIR/genotype_dump\_$seq_region_id" or die "Can't open tmp_file : $!";
while (<IN>) {
my ($seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand, $allele_1, $allele_2, $sample_id, $allele_string) = split;
#same variation and individual but different genotype !!!
next if (defined $genotypes->{$sample_id}->{region_end} && $seq_region_start == $genotypes->{$sample_id}->{region_end});
#new region for the individual, update coordinates
if (!defined $genotypes->{$sample_id}->{region_start}) {
$genotypes->{$sample_id}->{region_start} = $seq_region_start;
$genotypes->{$sample_id}->{region_end} = $seq_region_end;
}
#compare with the beginning of the region if it is within the DISTANCE of compression
if ((abs($genotypes->{$sample_id}->{region_start} - $seq_region_start) > DISTANCE()) || (abs($seq_region_start - $genotypes->{$sample_id}->{region_end}) > MAX_SHORT)) {
#snp outside the region, print the region for the sample we have already visited and start a new one
print_file("$TMP_DIR/compressed_genotype\_$seq_region_id",$genotypes, $seq_region_id, $sample_id);
delete $genotypes->{$sample_id}; #and remove the printed entry
$genotypes->{$sample_id}->{region_start} = $seq_region_start;
}
#escape characters (tab, new line)
reverse_alleles($seq_region_strand, $allele_string, \$allele_1, \$allele_2);
#and write it to the buffer
if ($seq_region_start != $genotypes->{$sample_id}->{region_start}) {
#compress information
$blob = pack ("n",$seq_region_start - $genotypes->{$sample_id}->{region_end} - 1);
$genotypes->{$sample_id}->{genotypes} .= escape($blob) . $allele_1 . $allele_2;
} else {
#first genotype starts in the region_start, not necessary the number
$genotypes->{$sample_id}->{genotypes} = $allele_1 . $allele_2;
}
#and update the new region_end
$genotypes->{$sample_id}->{region_end} = $seq_region_start; #to avoid nasty effects of indels coordinates
}
#print all remaining genotypes and upload the file
print_file("$TMP_DIR/compressed_genotype\_$seq_region_id",$genotypes, $seq_region_id);
$genotypes = {}; #and flush the hash
#need to fork for upload the data
my $pid = fork;
if (! defined $pid) {
throw("Not possible to fork: $!\n");
} elsif ($pid == 0) {
#you are the child.....
my $dbVar_write = $vdba->dbc;
debug("Import for seq_region_id $seq_region_id");
&import_genotypes($dbVar_write,"$TMP_DIR/compressed_genotype\_$seq_region_id");
#unlink "$TMP_DIR/genotype_dump\_$seq_region_id";
POSIX:_exit(0);
} else {
#the parent waits for the child to finish;
waitpid($pid,0);
}
}
print "Time finishing dumping data: ",scalar(localtime(time)),"\n";
#unlink "$TMP_DIR/genotype_dump_*";
}
sub print_file{
my $file = shift;
my $genotypes = shift;
my $seq_region_id = shift;
my $sample_id = shift;
open( FH, ">>$file") or die "Could not add compressed information: $!\n";
if (!defined $sample_id){
#new chromosome, print all the genotypes and flush the hash
foreach my $sample_id (keys %{$genotypes}){
print FH join("\t",$sample_id,$seq_region_id, $genotypes->{$sample_id}->{region_start}, $genotypes->{$sample_id}->{region_end}, 1, $genotypes->{$sample_id}->{genotypes}) . "\n";
}
}
else{
#only print the region corresponding to sample_id
print FH join("\t",$sample_id,$seq_region_id, $genotypes->{$sample_id}->{region_start}, $genotypes->{$sample_id}->{region_end}, 1, $genotypes->{$sample_id}->{genotypes}) . "\n";
}
close FH;
}
sub import_genotypes{
my $dbVar = shift;
my $file = shift;
debug("Importing compressed genotype data");
my $call = "mv $file $TMP_DIR/$TMP_FILE";
system($call);
load($dbVar,qw(compressed_genotype_single_bp sample_id seq_region_id seq_region_start seq_region_end seq_region_strand genotypes));
}
#
# updates the meta coord table
#
sub update_meta_coord {
my $dbCore = shift;
my $dbVar = shift;
my $table_name = shift;
my $csname = shift || 'chromosome';
my $csa = $dbCore->get_CoordSystemAdaptor();
my $cs = $csa->fetch_by_name($csname);
my $sth = $dbVar->prepare
('INSERT INTO meta_coord (table_name,coord_system_id,max_length) VALUES (?,?,?)');
$sth->execute($table_name, $cs->dbID(),DISTANCE+1);
$sth->finish();
return;
}
#checks if the genotype is in the opposite strand. If so, reverse the alleles
sub reverse_alleles{
my $seq_region_strand = shift;
my $allele_string = shift;
my $ref_allele_1 = shift;
my $ref_allele_2 = shift;
my @alleles = split("/",$allele_string);
#the variation_feature is in the opposite strand, reverse the genotypes
if ($seq_region_strand == -1){
reverse_comp($ref_allele_1);
reverse_comp($ref_allele_2);
# reverse_comp(\$alleles[0]);
# reverse_comp(\$alleles[1]);
}
#Only reverse genotypes with valid base
# if ($$ref_allele_1 ne 'N'){
# #compare the genotype with the forward alleles, if they are different, reverse them
# if ((@alleles == 2) && (($$ref_allele_1 ne $alleles[0]) && ($$ref_allele_1 ne $alleles[1]))){
# reverse_comp($ref_allele_1);
# reverse_comp($ref_allele_2);
# }
# }
}
# $special_characters_escaped = printable( $source_string );
sub escape ($) {
local $_ = ( defined $_[0] ? $_[0] : '' );
s/([\r\n\t\\\"])/\\$Printable{$1}/sg;
return $_;
}
sub usage {
my $msg = shift;
print STDERR <<EOF;
usage: perl compress_genotypes.pl <options>
options:
-tmpdir <dir> temp directory to use (with lots of space!)
-tmpfile <filename> name of temp file to use
-species <species_name> name of the specie you want to compress the genotypes
EOF
die("\n$msg\n\n");
}
| Ensembl/ensembl-variation | scripts/import/compress_genotypes_by_seq_region.pl | Perl | apache-2.0 | 10,603 |
:- module(_,[sql_persistent_tr/2, sql_goal_tr/2,
dbId/2],[assertions]).
:- use_module(library(dynamic)).
:- use_module(library(lists),[append/3]).
:- use_module(library('persdb_mysql_op/persdbrt_mysql_op'),
[assert_args/4]).
:- use_module(library('persdb_mysql_op/pl2sql')).
:- use_module(library('persdb_mysql_op/sql_types'),
[sql_type/1, sql_compatible/2]).
:- use_module(library(prolog_sys),[new_atom/1]).
:- use_module(library(write),[writeq/1]).
:- use_module(library(vndict),[create_dict/2]).
:- data dbId/2.
:- multifile([relation/3,attribute/4]).
:- data([relation/3,attribute/4]).
:- set_prolog_flag(multi_arity_warnings,off).
:- set_prolog_flag(write_strings,on).
is_true(true(Info),Info).
is_true(true).
is_ground('props:ground'(G),G).
is_ground(ground(G),G).
%% In source code both sql_persistent/3 directives and '$is_sql_persistent'/3
%% facts may appear. sql_persistent/3 directive will be present if the current
%% module has not been preprocessed before, while '$is_sql_persistent' facts
%% will appear after analyzing the code (because
%% sql_persistent/3 directives have been expanded to $is_sql_persistent facts.)
%% This package must include code for both cases.
sql_persistent_tr( ('$is_sql_persistent'(PrologDef,SQLDef,DBId):- Body),
('$is_sql_persistent'(PrologDef,SQLDef,DBId):- Body)):-
sql_persistent_tr_2(PrologDef,SQLDef,Skel),
assertz_fact(dbId(DBId,Skel)).
sql_persistent_tr( (:- sql_persistent(PrologDef,SQLDef,DBId)), ClauseList) :-
\+ dbId(_,PrologDef), % It has not been already expanded (due to analysis preprocessing).
sql_persistent_tr_2(PrologDef,SQLDef,Consequence),
ClauseList = [ '$is_sql_persistent'(PrologDef,SQLDef,DBId),
%jcf-deterministic-db-calls-begin
% 10/06/03: change made to check if a call is deterministic.
% We use prefetch/3 to get a db tuple in advance.
% (Consequence :- db_call_db_atomic_goal(DBId,Consequence)) ].
(Consequence :- prefetch_db_call(DBId,Consequence)) ],
% display(ClauseList),nl.
true.
%jcf-deterministic-db-calls-end
sql_persistent_tr((:- true pred Assertion), ClauseList) :-
get_persistence_info(Assertion,PrologDef,SQLDef,DBId),
% writeq((:- true pred Assertion)),nl,
\+ dbId(_,PrologDef), % It has not been already expanded (due to analysis preprocessing).
sql_persistent_tr_2(PrologDef,SQLDef,Consequence),
ClauseList = [
(:- true pred Assertion),
'$is_sql_persistent'(PrologDef,SQLDef,DBId),
% 10/06/03: change made to check if a call is deterministic.
% We use prefetch/3 to get a db tuple in advance.
% (Consequence :- db_call_db_atomic_goal(DBId,Consequence)) ].
(Consequence :- prefetch_db_call(DBId,Consequence))
%jcf-deterministic-db-calls-end
],
% writeq(ClauseList),nl.
true.
sql_persistent_tr( (Head :- Body), (Head :- NewBody)) :-
group_persistent_goals(Body,Body1),
remove_trues(Body1,Body2),
transform_body(Body2,NewBody),
% writeq((Head :- NewBody)),nl.
true.
sql_persistent_tr(end_of_file,end_of_file) :-
retractall_fact(relation(_,_,_)),
retractall_fact(attribute(_,_,_,_)),
retractall_fact(dbId(_,_)).
%%---------------
sql_persistent_tr_2(PrologDef,SQLDef,Consequence):-
functor(PrologDef,PrologName,Arity),
functor(Consequence,PrologName,Arity),
PrologDef =.. [PrologName | Types],
SQLDef =.. [TableName | ArgNames],
assertz_fact(relation(PrologName,Arity,TableName)),
assert_args(Types,ArgNames,1,TableName).
%%---------------
%% Currently assertions are not normalized. Only specific
%% assertions are understood.
get_persistence_info(Ass,PrologDef,SQLDef,DBId):-
Ass = (Pred :: Types + persistent(DBId,SQLDef)),
name_arity(Pred,Name,Arity),
functor(SQLDef,_,Arity),
functor(PrologDef,Name,Arity),
get_types(Types,TypesList),
PrologDef =.. [Name | TypesList].
name_arity(Name/Arity,Name,Arity).
name_arity(Pred,Name,Arity):-
functor(Pred,Name,Arity).
get_types(Type,[SqlType]):-
is_sql_type(Type,SqlType).
get_types(*(Type,Types),[SqlType|LTypes]):-
is_sql_type(Type,SqlType),
get_types(Types,LTypes).
is_sql_type(Type,Type):-
sql_type(Type).
is_sql_type(Type,SqlType):-
sql_compatible(Type,SqlType).
%% ----------------------------------------------------------------------------
:- pred group_persistent_goals(+Body,-NewBody)
# "Given a complex goal @var{Body}, possibly including program point
analysis info, transforms it grouping persistent atomic goals and
removing all analysis info at program points except those preceding
every group of atomic persistent goals. Grouped goals are
encapsulated in the second argument of @tt{true/2} goals. These
goals are transformed later bytransform_body/2.".
group_persistent_goals( (True,Goal) , (true(PPInfo,Pers),NewRest) ):-
is_true(True,PPInfo),
split_persistent_goals(Goal,Pers,_Db,Rest),
Pers \== true, !,
group_persistent_goals(Rest,NewRest).
group_persistent_goals(Goal, (true([],Pers),NewRest) ):-
split_persistent_goals(Goal,Pers,_Db,Rest),
Pers \== true, !,
group_persistent_goals(Rest,NewRest).
group_persistent_goals( (A,B) , (NewA,NewB)):- !,
group_persistent_goals(A,NewA),
group_persistent_goals(B,NewB).
group_persistent_goals( (A;B) , (NewA;NewB)):- !,
group_persistent_goals(A,NewA),
group_persistent_goals(B,NewB).
group_persistent_goals( (A->B) , (NewA->NewB)):- !,
group_persistent_goals(A,NewA),
group_persistent_goals(B,NewB).
group_persistent_goals(A,A).
%% ----------------------------------------------------------------------------
:- pred split_persistent_goals(Goal,Pers,Db,Rest)
# "Given a complex goal @var{Goal}, splits it in two goals: @var{Pers}
is the subgoal that corresponds to the initial sequence of atomic
goals which are persistent (and belong to a single database
@var{Db}); and @var{Rest} is the sequence of remaining goals (those
next to the last persistent goal). No goal reordering is made; just
goal grouping.".
split_persistent_goals((True,Goal),Pers,Db,Rest):-
is_true(True,_), !,
split_persistent_goals(Goal,Pers,Db,Rest).
split_persistent_goals(Goal,Goal,Db,true):-
complex_goal_persistent(Goal,Db), !.
split_persistent_goals( (A,B) , (A,PersB) ,Db,Rest):-
complex_goal_persistent(A,Db),!,
split_persistent_goals(B,PersB,Db,Rest).
split_persistent_goals( (A,B) ,Pers,Db,Rest):-
split_persistent_goals(A,Pers,Db,RestA), !,
Rest = (RestA,B).
split_persistent_goals(True,true,_,true):-
is_true(True,_), !.
split_persistent_goals(Goal,true,_,Goal).
%% ----------------------------------------------------------------------------
:- pred complex_goal_persistent(Goal,Db)
# "Succeeds if @var{Goal} is formed exclusively by persistent atomic
goals of a single database @var{Db}.".
complex_goal_persistent((A,B),Db):-
complex_goal_persistent(A,Db),
complex_goal_persistent(B,Db).
complex_goal_persistent((A;B),Db):-
complex_goal_persistent(A,Db),
complex_goal_persistent(B,Db).
complex_goal_persistent((A->B),Db):-
complex_goal_persistent(A,Db),
complex_goal_persistent(B,Db).
complex_goal_persistent(A,Db):-
dbId(Db,A).
%% ----------------------------------------------------------------------------
:- pred remove_trues(Goal,NewGoal)
# "Removes unneeded true info (true/0, true/1 and true(_,true))".
remove_trues((True,Goal),NewGoal):-
(is_true(True) ; is_true(True,_) ; True = true(_,true)),!,
remove_trues(Goal,NewGoal).
remove_trues((Goal,True),NewGoal):-
(is_true(True) ; is_true(True,_) ; True = true(_,true)),!,
remove_trues(Goal,NewGoal).
remove_trues((A,B),(NewA,NewB)):- !,
remove_trues(A,NewA),
remove_trues(B,NewB).
remove_trues((A;B),(NewA;NewB)):- !,
remove_trues(A,NewA),
remove_trues(B,NewB).
remove_trues((A->B),(NewA->NewB)):- !,
remove_trues(A,NewA),
remove_trues(B,NewB).
remove_trues(true(_,Goal),true):-
remove_trues(Goal,true),!.
remove_trues(true(PPInfo,Goal),true(PPInfo,NewGoal)):- !,
remove_trues(Goal,NewGoal).
remove_trues(True,true):-
(is_true(True,_) ; True = true(_,true)),!.
remove_trues(G,G).
%% ----------------------------------------------------------------------------
:- pred transform_body(Goal,NewGoal)
# "Complex goal @var{Goal} is transformed to @var{NewGoal}, removing
@tt{true/1} goals and using their arguments to optimize calls to
persistent predicates. It is assumed that a complex conjunctive goal
is of the form (Goal1,(Goal2,(...,Goaln)...))".
transform_body(true(PPInfo,Goal),NewGoal):-
extract_ground_info(PPInfo,GroundVars),
translate_goal(Goal,GroundVars,NewGoal).
transform_body((A,B),(NewA,NewB)):- !,
transform_body(A,NewA),
transform_body(B,NewB).
transform_body((A;B),(NewA;NewB)):- !,
transform_body(A,NewA),
transform_body(B,NewB).
transform_body((A->B),(NewA->NewB)):- !,
transform_body(A,NewA),
transform_body(B,NewB).
transform_body(!,!):- !.
transform_body(Goal,Goal).
%% ----------------------------------------------------------------------------
:- pred extract_ground_info(+PPInfo,-GroundVars)
# "Given a list of program point info @var{PPInfo}, return the list of
ground variables @var{GroundVars}.".
extract_ground_info((A,B),G):- !,
extract_ground_info(A,GA),
extract_ground_info(B,GB),
append(GA,GB,G).
extract_ground_info(Ground,G):-
is_ground(Ground,G), !.
extract_ground_info(_,[]).
%% ----------------------------------------------------------------------------
:- pred translate_goal(+Goal,+GroundVars,-NewGoal)
# "Given a persistent goal @var{Goal} and a list of ground vars
@var{GroundVars}, to call directly to the sql query.".
translate_goal(Goal,GroundVars,NewGoal):-
copy_term(pair(Goal,GroundVars),pair(GGoal,GVars)),
build_proj_term(GGoal,PTerm), % A proj. term is built with all vars. (free or ground)
groundify(GVars), % Ground variables are asigned a key
copy_term(pair(GGoal,PTerm),pair(GroundGoal,ProjTerm)),
% pl2sql instantiates free vars, so we need another copy.
create_dict(ProjTerm,dic(ProjVars,_)), % ProjVars is the list of free variables.
pl2sqlstring(PTerm,GGoal,SQLStrQuery),
dbId(DBId,_), %%% MAL!!! (supone que solo hay una bd!!)
%jcf-deterministic-db-calls-begin
%%% new_atom(CallKey),
%jcf-deterministic-db-calls-end
( GVars = [] ->
GroundGoal = Goal,
NewGoal = (
( varlist(ProjVars) ->
%jcf-deterministic-db-calls-begin
% sql_query_one_tuple(DBId,SQLStrQuery,__ResultTuple),
prefetch_sql_query_one_tuple(DBId,SQLStrQuery,__ResultTuple),
%jcf-deterministic-db-calls-end
ProjTerm =.. [_|__ResultTuple]
; Goal
)
)
; NewGoal = (
( varlist(ProjVars) ->
replace_marks(GroundGoal,Goal,SQLStrQuery,__SQLString),
%jcf-deterministic-db-calls-begin
% sql_query_one_tuple(DBId,__SQLString,__ResultTuple),
prefetch_sql_query_one_tuple(DBId,__SQLString,__ResultTuple),
%jcf-deterministic-db-calls-end
ProjTerm =.. [_|__ResultTuple]
; Goal
)
)
).
%% ----------------------------------------------------------------------------
:- pred groundify(VarList)
# "Instantiates the variables in @var{VarList} to their names.".
groundify([]).
groundify([V|Vs]):-
new_atom(NewAtom),
atom_concat('persdb_opt$',NewAtom,V),
groundify(Vs).
%% ----------------------------------------------------------------------------
:- pred build_proj_term(+Goal,-ProjTerm)
# "Given a (possibly complex) goal @var{Goal}, builds a projection
term @var{ProjTerm}, a term that gathers the variables which appear
in the goal.".
build_proj_term(Goal,ProjTerm):-
create_dict(Goal,dic(Dict,_)),
ProjTerm =.. [proj_term|Dict].
%jcf.09.05.2003-end
%jcf
% If a persistent predicate is also defined as a normal predicate inside the same module,
% queries to that predicate should provide wrong results (first database rows, then
% prolog clauses), but it doesn't. THIS MUST BE CHECKED!
sql_goal_tr( Goal, db_call_db_atomic_goal(DBId,Goal)) :-
current_fact(dbId(DBId,Goal)).
:- set_prolog_flag(multi_arity_warnings,on).
| leuschel/ecce | www/CiaoDE/ciao/library/persdb_mysql_op/persdbtr_mysql_op.pl | Perl | apache-2.0 | 11,891 |
#!/usr/bin/perl
# KEWUN - Georg Fischer 4.3.1969 und 12.2.1973 (in ALGOL 60 on TR440)
# @(#) $Id: kewun2.pl 232 2009-08-27 22:17:16Z gfis $
# Copyright (c) 1969, 2009 Dr. Georg Fischer
use strict;
my ($n, $k, $g, $i, $na, $ne, $b0, $b1, $p0, $p1, $q0, $q1);
$na = shift(@ARGV); # untere Grenze
$ne = shift(@ARGV); # obere Grenze
$g = 0;
my $epsi = 0.0001; # fuer INTEGER-Division
for ($n = $na; $n <= $ne; $n ++) {
while ($g*$g <= $n) {
$g ++;
} # while $g
$g --;
print "$n $g ";
if ($g*$g != $n) { # keine Quadratzahl
$p0 = 0;
$q0 = 1;
$b0 = $g;
bb:
$p1 = $b0 * $q0 - $p0;
$q1 = int(($n - $p1*$p1) / $q0 + $epsi);
$b1 = int(($g + $p1) / $q1 + $epsi);
if ($q0 == $q1) {
print "/..."; # davor steht die linke Haelfte der Periode, sie spiegelt sich am "/"
} else {
if ($p0 == $p1) {
print "*..."; # vor dem letzten Wert steht die linke Haelfte der Periode, sie spiegelt sich an diesem Wert
} else {
print "$b1,";
$p0 = $p1;
$q0 = $q1;
$b0 = $b1;
goto bb;
}
}
print $g+$g;
} # keine Quadratzahl
print "\n";
} # for $n
| gfis/ramath | test/cf/kewun2.pl | Perl | apache-2.0 | 1,126 |
package ChimericCigarParser;
use strict;
use warnings;
use Carp;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(get_genome_coords_via_cigar);
####
sub get_genome_coords_via_cigar {
my ($rst, $cigar) = @_;
## borrowing this code from my SAM_entry.pm
my $genome_lend = $rst;
my $alignment = $cigar;
my $query_lend = 0;
my @genome_coords;
my @query_coords;
$genome_lend--; # move pointer just before first position.
while ($alignment =~ /(\d+)([A-Zp])/g) {
my $len = $1;
my $code = $2;
unless ($code =~ /^[MSDNIHp]$/) {
confess "Error, cannot parse cigar code [$code] ";
}
# print "parsed $len,$code\n";
if ($code eq 'M') { # aligned bases match or mismatch
my $genome_rend = $genome_lend + $len;
my $query_rend = $query_lend + $len;
push (@genome_coords, [$genome_lend+1, $genome_rend]);
push (@query_coords, [$query_lend+1, $query_rend]);
# reset coord pointers
$genome_lend = $genome_rend;
$query_lend = $query_rend;
}
elsif ($code eq 'D' || $code eq 'N' || $code eq 'p') { # insertion in the genome or gap in query (intron, perhaps)
$genome_lend += $len;
}
elsif ($code eq 'I' # gap in genome or insertion in query
||
$code eq 'S' || $code eq 'H') # masked region of query
{
$query_lend += $len;
}
}
return(\@genome_coords, \@query_coords);
}
1; #EOM
| STAR-Fusion/STAR-Fusion | PerlLib/ChimericCigarParser.pm | Perl | bsd-3-clause | 1,699 |
#!/usr/bin/perl -w
use strict;
use File::Temp qw/tempdir/;
my $usage = q{Usage: kmrun.pl seed file weights nstart
Runs clustering experiment with given settings.
Prints out inputs, outputs, number of seconds.
};
my $seed = shift;
my $file = shift;
my $weights = shift;
my $nstart = shift;
die $usage unless (defined $seed and defined $file and defined $weights and defined $nstart);
my $tmp = tempdir("kmrun-XXXX", CLEANUP => 1);
my $km_err = "$tmp/kmeans";
my $ev_err = "$tmp/eval";
my $ntest = 1173766;
my $K = 45;
my $test = 'wsj.words.gz';
my $gold = 'wsj.pos.gz';
my ($input, $kmeans, $score);
if ($weights) {
$input = "zcat $file | perl -ne 'print if s/^0://'";
$kmeans = "wkmeans -k $K -r $nstart -s $seed -w -l";
$score = "wkmeans2eval.pl -t $test | eval.pl -m -v -g $gold";
} else {
$input = "zcat $file | scode2kmeans.pl -t $test";
$kmeans = "wkmeans -k $K -r $nstart -s $seed";
$score = "eval.pl -m -v -g $gold";
}
my $cmd = "$input | $kmeans 2> $km_err | $score 2> $ev_err";
my $tm = time;
system($cmd);
$tm = time - $tm;
my @km = split(' ', `cat $km_err`);
my @ev = split(' ', `cat $ev_err`);
print join("\t", $seed, $file, $weights, $nstart, @km, @ev, $tm)."\n";
| ai-ku/upos_2014 | src/scripts/kmrun.pl | Perl | mit | 1,210 |
package d;
use datestring;
open my $f, '<', $INC{'datestring.pm'} or die "<datestring: $!";
undef local $/;
my $ds = <$f>;
$ds =~ s/datestring/d/;
eval $ds;
1;
| benizi/dotfiles | perl-lib/d.pm | Perl | mit | 160 |
=pod
=head1 NAME
OPENSSL_malloc_init,
OPENSSL_malloc, OPENSSL_zalloc, OPENSSL_realloc, OPENSSL_free,
OPENSSL_clear_realloc, OPENSSL_clear_free, OPENSSL_cleanse,
CRYPTO_malloc, CRYPTO_zalloc, CRYPTO_realloc, CRYPTO_free,
OPENSSL_strdup, OPENSSL_strndup,
OPENSSL_memdup, OPENSSL_strlcpy, OPENSSL_strlcat,
OPENSSL_hexstr2buf, OPENSSL_buf2hexstr, OPENSSL_hexchar2int,
CRYPTO_strdup, CRYPTO_strndup,
OPENSSL_mem_debug_push, OPENSSL_mem_debug_pop,
CRYPTO_mem_debug_push, CRYPTO_mem_debug_pop,
CRYPTO_clear_realloc, CRYPTO_clear_free,
CRYPTO_get_mem_functions, CRYPTO_set_mem_functions,
CRYPTO_get_alloc_counts,
CRYPTO_set_mem_debug, CRYPTO_mem_ctrl,
CRYPTO_mem_leaks, CRYPTO_mem_leaks_fp, CRYPTO_mem_leaks_cb,
OPENSSL_MALLOC_FAILURES,
OPENSSL_MALLOC_FD
- Memory allocation functions
=head1 SYNOPSIS
#include <openssl/crypto.h>
int OPENSSL_malloc_init(void)
void *OPENSSL_malloc(size_t num)
void *OPENSSL_zalloc(size_t num)
void *OPENSSL_realloc(void *addr, size_t num)
void OPENSSL_free(void *addr)
char *OPENSSL_strdup(const char *str)
char *OPENSSL_strndup(const char *str, size_t s)
size_t OPENSSL_strlcat(char *dst, const char *src, size_t size);
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t size);
void *OPENSSL_memdup(void *data, size_t s)
void *OPENSSL_clear_realloc(void *p, size_t old_len, size_t num)
void OPENSSL_clear_free(void *str, size_t num)
void OPENSSL_cleanse(void *ptr, size_t len);
unsigned char *OPENSSL_hexstr2buf(const char *str, long *len);
char *OPENSSL_buf2hexstr(const unsigned char *buffer, long len);
int OPENSSL_hexchar2int(unsigned char c);
void *CRYPTO_malloc(size_t num, const char *file, int line)
void *CRYPTO_zalloc(size_t num, const char *file, int line)
void *CRYPTO_realloc(void *p, size_t num, const char *file, int line)
void CRYPTO_free(void *str, const char *, int)
char *CRYPTO_strdup(const char *p, const char *file, int line)
char *CRYPTO_strndup(const char *p, size_t num, const char *file, int line)
void *CRYPTO_clear_realloc(void *p, size_t old_len, size_t num,
const char *file, int line)
void CRYPTO_clear_free(void *str, size_t num, const char *, int)
void CRYPTO_get_mem_functions(
void *(**m)(size_t, const char *, int),
void *(**r)(void *, size_t, const char *, int),
void (**f)(void *, const char *, int))
int CRYPTO_set_mem_functions(
void *(*m)(size_t, const char *, int),
void *(*r)(void *, size_t, const char *, int),
void (*f)(void *, const char *, int))
void CRYPTO_get_alloc_counts(int *m, int *r, int *f)
int CRYPTO_set_mem_debug(int onoff)
env OPENSSL_MALLOC_FAILURES=... <application>
env OPENSSL_MALLOC_FD=... <application>
int CRYPTO_mem_ctrl(int mode);
int OPENSSL_mem_debug_push(const char *info)
int OPENSSL_mem_debug_pop(void);
int CRYPTO_mem_debug_push(const char *info, const char *file, int line);
int CRYPTO_mem_debug_pop(void);
int CRYPTO_mem_leaks(BIO *b);
int CRYPTO_mem_leaks_fp(FILE *fp);
int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
void *u);
=head1 DESCRIPTION
OpenSSL memory allocation is handled by the B<OPENSSL_xxx> API. These are
generally macro's that add the standard C B<__FILE__> and B<__LINE__>
parameters and call a lower-level B<CRYPTO_xxx> API.
Some functions do not add those parameters, but exist for consistency.
OPENSSL_malloc_init() does nothing and does not need to be called. It is
included for compatibility with older versions of OpenSSL.
OPENSSL_malloc(), OPENSSL_realloc(), and OPENSSL_free() are like the
C malloc(), realloc(), and free() functions.
OPENSSL_zalloc() calls memset() to zero the memory before returning.
OPENSSL_clear_realloc() and OPENSSL_clear_free() should be used
when the buffer at B<addr> holds sensitive information.
The old buffer is filled with zero's by calling OPENSSL_cleanse()
before ultimately calling OPENSSL_free().
OPENSSL_cleanse() fills B<ptr> of size B<len> with a string of 0's.
Use OPENSSL_cleanse() with care if the memory is a mapping of a file.
If the storage controller uses write compression, then its possible
that sensitive tail bytes will survive zeroization because the block of
zeros will be compressed. If the storage controller uses wear leveling,
then the old sensitive data will not be overwritten; rather, a block of
0's will be written at a new physical location.
OPENSSL_strdup(), OPENSSL_strndup() and OPENSSL_memdup() are like the
equivalent C functions, except that memory is allocated by calling the
OPENSSL_malloc() and should be released by calling OPENSSL_free().
OPENSSL_strlcpy(),
OPENSSL_strlcat() and OPENSSL_strnlen() are equivalents of the common C
library functions and are provided for portability.
OPENSSL_hexstr2buf() parses B<str> as a hex string and returns a
pointer to the parsed value. The memory is allocated by calling
OPENSSL_malloc() and should be released by calling OPENSSL_free().
If B<len> is not NULL, it is filled in with the output length.
Colons between two-character hex "bytes" are ignored.
An odd number of hex digits is an error.
OPENSSL_buf2hexstr() takes the specified buffer and length, and returns
a hex string for value, or NULL on error.
B<Buffer> cannot be NULL; if B<len> is 0 an empty string is returned.
OPENSSL_hexchar2int() converts a character to the hexadecimal equivalent,
or returns -1 on error.
If no allocations have been done, it is possible to "swap out" the default
implementations for OPENSSL_malloc(), OPENSSL_realloc and OPENSSL_free()
and replace them with alternate versions (hooks).
CRYPTO_get_mem_functions() function fills in the given arguments with the
function pointers for the current implementations.
With CRYPTO_set_mem_functions(), you can specify a different set of functions.
If any of B<m>, B<r>, or B<f> are NULL, then the function is not changed.
The default implementation can include some debugging capability (if enabled
at build-time).
This adds some overhead by keeping a list of all memory allocations, and
removes items from the list when they are free'd.
This is most useful for identifying memory leaks.
CRYPTO_set_mem_debug() turns this tracking on and off. In order to have
any effect, is must be called before any of the allocation functions
(e.g., CRYPTO_malloc()) are called, and is therefore normally one of the
first lines of main() in an application.
CRYPTO_mem_ctrl() provides fine-grained control of memory leak tracking.
To enable tracking call CRYPTO_mem_ctrl() with a B<mode> argument of
the B<CRYPTO_MEM_CHECK_ON>.
To disable tracking call CRYPTO_mem_ctrl() with a B<mode> argument of
the B<CRYPTO_MEM_CHECK_OFF>.
While checking memory, it can be useful to store additional context
about what is being done.
For example, identifying the field names when parsing a complicated
data structure.
OPENSSL_mem_debug_push() (which calls CRYPTO_mem_debug_push())
attaches an identifying string to the allocation stack.
This must be a global or other static string; it is not copied.
OPENSSL_mem_debug_pop() removes identifying state from the stack.
At the end of the program, calling CRYPTO_mem_leaks() or
CRYPTO_mem_leaks_fp() will report all "leaked" memory, writing it
to the specified BIO B<b> or FILE B<fp>. These functions return 1 if
there are no leaks, 0 if there are leaks and -1 if an error occurred.
CRYPTO_mem_leaks_cb() does the same as CRYPTO_mem_leaks(), but instead
of writing to a given BIO, the callback function is called for each
output string with the string, length, and userdata B<u> as the callback
parameters.
If the library is built with the C<crypto-mdebug> option, then one
function, CRYPTO_get_alloc_counts(), and two additional environment
variables, B<OPENSSL_MALLOC_FAILURES> and B<OPENSSL_MALLOC_FD>,
are available.
The function CRYPTO_get_alloc_counts() fills in the number of times
each of CRYPTO_malloc(), CRYPTO_realloc(), and CRYPTO_free() have been
called, into the values pointed to by B<mcount>, B<rcount>, and B<fcount>,
respectively. If a pointer is NULL, then the corresponding count is not stored.
The variable
B<OPENSSL_MALLOC_FAILURES> controls how often allocations should fail.
It is a set of fields separated by semicolons, which each field is a count
(defaulting to zero) and an optional atsign and percentage (defaulting
to 100). If the count is zero, then it lasts forever. For example,
C<100;@25> or C<100@0;0@25> means the first 100 allocations pass, then all
other allocations (until the program exits or crashes) have a 25% chance of
failing.
If the variable B<OPENSSL_MALLOC_FD> is parsed as a positive integer, then
it is taken as an open file descriptor, and a record of all allocations is
written to that descriptor. If an allocation will fail, and the platform
supports it, then a backtrace will be written to the descriptor. This can
be useful because a malloc may fail but not be checked, and problems will
only occur later. The following example in classic shell syntax shows how
to use this (will not work on all platforms):
OPENSSL_MALLOC_FAILURES='200;@10'
export OPENSSL_MALLOC_FAILURES
OPENSSL_MALLOC_FD=3
export OPENSSL_MALLOC_FD
...app invocation... 3>/tmp/log$$
=head1 RETURN VALUES
OPENSSL_malloc_init(), OPENSSL_free(), OPENSSL_clear_free()
CRYPTO_free(), CRYPTO_clear_free() and CRYPTO_get_mem_functions()
return no value.
CRYPTO_mem_leaks(), CRYPTO_mem_leaks_fp() and CRYPTO_mem_leaks_cb() return 1 if
there are no leaks, 0 if there are leaks and -1 if an error occurred.
OPENSSL_malloc(), OPENSSL_zalloc(), OPENSSL_realloc(),
OPENSSL_clear_realloc(),
CRYPTO_malloc(), CRYPTO_zalloc(), CRYPTO_realloc(),
CRYPTO_clear_realloc(),
OPENSSL_buf2hexstr(), OPENSSL_hexstr2buf(),
OPENSSL_strdup(), and OPENSSL_strndup()
return a pointer to allocated memory or NULL on error.
CRYPTO_set_mem_functions() and CRYPTO_set_mem_debug()
return 1 on success or 0 on failure (almost
always because allocations have already happened).
CRYPTO_mem_ctrl() returns -1 if an error occurred, otherwise the
previous value of the mode.
OPENSSL_mem_debug_push() and OPENSSL_mem_debug_pop()
return 1 on success or 0 on failure.
=head1 NOTES
While it's permitted to swap out only a few and not all the functions
with CRYPTO_set_mem_functions(), it's recommended to swap them all out
at once. I<This applies specially if OpenSSL was built with the
configuration option> C<crypto-mdebug> I<enabled. In case, swapping out
only, say, the malloc() implementation is outright dangerous.>
=head1 COPYRIGHT
Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| pmq20/ruby-compiler | vendor/openssl/doc/man3/OPENSSL_malloc.pod | Perl | mit | 10,872 |
use v6;
# Specification:
# P09 (**) Pack consecutive duplicates of list elements into sublists.
# If a list contains repeated elements they should be placed in separate
# sublists.
# Example:
# > pack_dup(<a a a a b c c a a d e e e e>).perl.say
# [["a","a","a","a"],["b"],["c","c"],["a","a"],["d"],["e","e","e","e"]]
my @l = <a a a a b c c a a d e e e e>;
sub prob09 (@in) {
return gather while @in.elems {
my $val = @in[0];
take [gather while @in.elems and @in[0] ~~ $val { take shift @in }];
}
}
say ~@l;
say prob09(@l).perl;
| Mitali-Sodhi/CodeLingo | Dataset/perl/P09-unobe.pl | Perl | mit | 567 |
package Paws::Glue::DeleteCrawlerResponse;
use Moose;
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::Glue::DeleteCrawlerResponse
=head1 ATTRIBUTES
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/Glue/DeleteCrawlerResponse.pm | Perl | apache-2.0 | 250 |
%Create perfect numbers
top :-
findall(C, perfect(100, C), X),
ok(X).
ok([ 3213876088517980551083924184681057554444177758164088967397376,
12554203470773361527671578846336104669690446551334525075456,
191561942608236107294793378084303638130997321548169216,
46768052394588893382517909811217778170473142550528,
182687704666362864775460301858080473799697891328,
44601490397061246283066714178813853366747136,
2787593149816327892690784192460327776944128,
10889035741470030830754200461521744560128,
2658455991569831744654692615953842176,
166153499473114483824745506383331328,
40564819207303336344294875201536,
9903520314282971830448816128,
38685626227663735544086528,
2417851639228158837784576,
9444732965670570950656,
2305843008139952128,
144115187807420416,
35184367894528,
137438691328,
8589869056,
33550336,
2096128,
8128,
496,
28,
6
]).
%divisible(10, 2).
divisible(X, Y) :-
N is Y*Y,
N =< X,
X mod Y =:= 0.
divisible(X, Y) :-
Y < X,
Y1 is Y + 1,
divisible(X, Y1).
%isprime([3], Z).
isprime([X|_], X) :-
Y is 2,
X > 1,
\+ divisible(X, Y).
isprime([_|T], Z) :-
isprime(T, Z).
%Calculate the power of one number
%ie power(2, 10, R)
power(_, 0, 1) :- !.
power(N, K, R) :-
K1 is K-1,
power(N, K1, R1),
R is R1*N.
%formula of perfect numbers 2^(p-1)*(2^p-1)
%ie calc(2, 10, R)
calc(2, K, R) :-
power(2, K, X),
R1 is X-1,
power(2, K-1, R2),
R is R1 * R2.
%using lists
%ie calc([2, 3, 4], R).
listperf([K|_], R) :-
calc(2, K, R).
listperf([_|T], Z) :-
listperf(T, Z).
%generate one list of N numbers.
%genList(10, L).
generateList(0, []).
generateList(N, [X|Xs]) :-
N > 0,
X is N+1,
N1 is N-1, generateList(N1, Xs).
%list of N perfect numbers
%perfect(100, C)
perfect(N, C) :-
generateList(N, R),
findall(L, isprime(R, L), P),
listperf(P, C).
| LogtalkDotOrg/logtalk3 | examples/bench/perfect.pl | Perl | apache-2.0 | 1,901 |
package Paws::SSM::GetInventoryResult;
use Moose;
has Entities => (is => 'ro', isa => 'ArrayRef[Paws::SSM::InventoryResultEntity]');
has NextToken => (is => 'ro', isa => 'Str');
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::SSM::GetInventoryResult
=head1 ATTRIBUTES
=head2 Entities => ArrayRef[L<Paws::SSM::InventoryResultEntity>]
Collection of inventory entities such as a collection of instance
inventory.
=head2 NextToken => Str
The token to use when requesting the next set of items. If there are no
additional items to return, the string is empty.
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/SSM/GetInventoryResult.pm | Perl | apache-2.0 | 667 |
package CoGe::ECNCS::DB::Spike;
use strict;
use base 'CoGe::ECNCS::DB';
BEGIN {
use Exporter ();
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
$VERSION = '0.1';
@ISA = (@ISA, qw(Exporter));
#Give a hoot don't pollute, do not export more than needed by default
@EXPORT = qw();
@EXPORT_OK = qw();
%EXPORT_TAGS = ();
__PACKAGE__->table('spike');
__PACKAGE__->columns(All=>qw(spike_id length sequence_data));
__PACKAGE__->has_many(algorithm_data=>'CoGe::ECNCS::DB::Algorithm_data');
}
#################### subroutine header begin ####################
=head2 sample_function
Usage : How to use this function/method
Purpose : What it does
Returns : What it returns
Argument : What it wants to know
Throws : Exceptions and other anomolies
Comment : This is a sample subroutine header.
: It is polite to include more pod and fewer comments.
See Also :
=cut
#################### subroutine header end ####################
sub new
{
my ($class, %parameters) = @_;
my $self = bless ({}, ref ($class) || $class);
return $self;
}
#################### main pod documentation begin ###################
## Below is the stub of documentation for your module.
## You better edit it!
=head1 NAME
CoGe::ECNCS::DB::spike - CoGe::ECNCS::DB::spike
=head1 SYNOPSIS
use CoGe::ECNCS::DB::spike;
blah blah blah
=head1 DESCRIPTION
Stub documentation for this module was created by ExtUtils::ModuleMaker.
It looks like the author of the extension was negligent enough
to leave the stub unedited.
Blah blah blah.
=head1 USAGE
=head1 BUGS
=head1 SUPPORT
=head1 AUTHOR
HASH(0x813d9e0)
CPAN ID: MODAUTHOR
XYZ Corp.
a.u.thor@a.galaxy.far.far.away
http://a.galaxy.far.far.away/modules
=head1 COPYRIGHT
This program is free software licensed under the...
The Artistic License
The full text of the license can be found in the
LICENSE file included with this module.
=head1 SEE ALSO
perl(1).
=cut
#################### main pod documentation end ###################
sub algo_data
{
my $self = shift;
return $self->algorithm_data();
}
sub data
{
my $self = shift;
return $self->algorithm_data();
}
sub id
{
my $self = shift;
return $self->spike_id();
}
1;
# The preceding line will help the module return a true value
| asherkhb/coge | modules/ECNCS/lib/CoGe/ECNCS/DB/Spike.pm | Perl | bsd-2-clause | 2,382 |
package VCP::Filter::csv_trace ;
=head1 NAME
VCP::Filter::csv_trace - developement logging filter
=head1 DESCRIPTION
Dumps fields of revisions in CSV format.
Not a supported module, API and behavior may change without warning.
=cut
$VERSION = 0.1 ;
@ISA = qw( VCP::Filter );
use strict ;
#use base qw( VCP::Filter );
use VCP::Filter;
use VCP::Logger qw( pr lg );
use VCP::Utils qw( empty start_dir_rel2abs );
use Getopt::Long;
#use fields (
# 'FIELDS', ## Which fields to print
# 'FILE', ## Where to write output
# 'FH', ## The filehandle of the output file
#);
sub new {
my $self = shift->SUPER::new;
## Parse the options
my ( $spec, $options ) = @_ ;
## Cheesy. TODO: factor parse_options up to plugin?
if ( $options && @$options ) {
local *ARGV = $options;
GetOptions(
"fields=s" => \$self->{FIELDS},
"file=s" => \$self->{FILE},
) or $self->usage_and_exit ;
}
die "vcp: output filename required for csv_trace filter\n"
if empty $self->{FILE};
return $self ;
}
sub csv_escape {
local $_ = @_ ? shift : $_;
return "" unless defined;
return '""' unless length;
## crude but effective.
s/\r/\\r/g;
s/\n/\\n/g;
s/"/""/g;
$_ = qq{"$_"} if /[",]/;
$_;
}
sub init {
my $self = shift ;
$self->SUPER::init;
$self->{FIELDS} = [
!empty( $self->{FIELDS} )
? do {
my @names = split /,/, $self->{FIELDS};
my %fields = map {
my $name = $_;
$name =~ s/\@//;
( $name => $_ );
} VCP::Rev->fields;
for ( @names ) {
if ( ! exists $fields{$_} && !VCP::Rev->can($_) ) {
pr "vcp: '$_' not a name, skipping";
next;
}
$_ = $fields{$_} if exists $fields{$_};
}
@names;
}
: VCP::Rev->fields
];
}
sub handle_header {
my $self = shift ;
local *F;
my $fn = start_dir_rel2abs( $self->{FILE} );
open F, "> $fn" or die "$! opening $fn\n";
$self->{FH} = *F{IO};
my $fh = $self->{FH};
print $fh join( ",", map {
my $name = $_;
$name =~ s/\@//;
csv_escape( $name );
} @{$self->{FIELDS}} ),
"\n";
$self->SUPER::handle_header( @_ );
}
sub handle_rev {
my $self = shift ;
my ( $r ) = @_;
my $fh = $self->{FH};
print $fh join( ",", map {
my $name = $_;
my $is_list = $name =~ s/\@//;
csv_escape(
$name eq "time"
? VCP::Rev::iso8601format( $r->$name )
: $is_list
? join ";", $r->$name
: $r->$name
);
} @{$self->{FIELDS}}
),
"\n";
$self->SUPER::handle_rev( $r );
}
=back
=head1 AUTHOR
Barrie Slaymaker <barries@slaysys.com>
=head1 COPYRIGHT
Copyright (c) 2000, 2001, 2002 Perforce Software, Inc.
All rights reserved.
See L<VCP::License|VCP::License> (C<vcp help license>) for the terms of use.
=cut
1
| gitpan/VCP | lib/VCP/Filter/csv_trace.pm | Perl | bsd-3-clause | 3,025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.