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
# !!!!!!! 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. # The name this swash is to be known by, with the format of the mappings in # the main body of the table, and what all code points missing from this file # map to. $utf8::SwashInfo{'ToWB'}{'format'} = 's'; # string $utf8::SwashInfo{'ToWB'}{'missing'} = 'Other'; return <<'END'; 000A LF 000B 000C Newline 000D CR 0027 MidNumLet 002C MidNum 002E MidNumLet 0030 0039 Numeric 003A MidLetter 003B MidNum 0041 005A ALetter 005F ExtendNumLet 0061 007A ALetter 0085 Newline 00AA ALetter 00AD Format 00B5 ALetter 00B7 MidLetter 00BA ALetter 00C0 00D6 ALetter 00D8 00F6 ALetter 00F8 02C1 ALetter 02C6 02D1 ALetter 02E0 02E4 ALetter 02EC ALetter 02EE ALetter 0300 036F Extend 0370 0374 ALetter 0376 0377 ALetter 037A 037D ALetter 037E MidNum 0386 ALetter 0387 MidLetter 0388 038A ALetter 038C ALetter 038E 03A1 ALetter 03A3 03F5 ALetter 03F7 0481 ALetter 0483 0489 Extend 048A 0527 ALetter 0531 0556 ALetter 0559 ALetter 0561 0587 ALetter 0589 MidNum 0591 05BD Extend 05BF Extend 05C1 05C2 Extend 05C4 05C5 Extend 05C7 Extend 05D0 05EA ALetter 05F0 05F3 ALetter 05F4 MidLetter 0600 0604 Format 060C 060D MidNum 0610 061A Extend 0620 064A ALetter 064B 065F Extend 0660 0669 Numeric 066B Numeric 066C MidNum 066E 066F ALetter 0670 Extend 0671 06D3 ALetter 06D5 ALetter 06D6 06DC Extend 06DD Format 06DF 06E4 Extend 06E5 06E6 ALetter 06E7 06E8 Extend 06EA 06ED Extend 06EE 06EF ALetter 06F0 06F9 Numeric 06FA 06FC ALetter 06FF ALetter 070F Format 0710 ALetter 0711 Extend 0712 072F ALetter 0730 074A Extend 074D 07A5 ALetter 07A6 07B0 Extend 07B1 ALetter 07C0 07C9 Numeric 07CA 07EA ALetter 07EB 07F3 Extend 07F4 07F5 ALetter 07F8 MidNum 07FA ALetter 0800 0815 ALetter 0816 0819 Extend 081A ALetter 081B 0823 Extend 0824 ALetter 0825 0827 Extend 0828 ALetter 0829 082D Extend 0840 0858 ALetter 0859 085B Extend 08A0 ALetter 08A2 08AC ALetter 08E4 08FE Extend 0900 0903 Extend 0904 0939 ALetter 093A 093C Extend 093D ALetter 093E 094F Extend 0950 ALetter 0951 0957 Extend 0958 0961 ALetter 0962 0963 Extend 0966 096F Numeric 0971 0977 ALetter 0979 097F ALetter 0981 0983 Extend 0985 098C ALetter 098F 0990 ALetter 0993 09A8 ALetter 09AA 09B0 ALetter 09B2 ALetter 09B6 09B9 ALetter 09BC Extend 09BD ALetter 09BE 09C4 Extend 09C7 09C8 Extend 09CB 09CD Extend 09CE ALetter 09D7 Extend 09DC 09DD ALetter 09DF 09E1 ALetter 09E2 09E3 Extend 09E6 09EF Numeric 09F0 09F1 ALetter 0A01 0A03 Extend 0A05 0A0A ALetter 0A0F 0A10 ALetter 0A13 0A28 ALetter 0A2A 0A30 ALetter 0A32 0A33 ALetter 0A35 0A36 ALetter 0A38 0A39 ALetter 0A3C Extend 0A3E 0A42 Extend 0A47 0A48 Extend 0A4B 0A4D Extend 0A51 Extend 0A59 0A5C ALetter 0A5E ALetter 0A66 0A6F Numeric 0A70 0A71 Extend 0A72 0A74 ALetter 0A75 Extend 0A81 0A83 Extend 0A85 0A8D ALetter 0A8F 0A91 ALetter 0A93 0AA8 ALetter 0AAA 0AB0 ALetter 0AB2 0AB3 ALetter 0AB5 0AB9 ALetter 0ABC Extend 0ABD ALetter 0ABE 0AC5 Extend 0AC7 0AC9 Extend 0ACB 0ACD Extend 0AD0 ALetter 0AE0 0AE1 ALetter 0AE2 0AE3 Extend 0AE6 0AEF Numeric 0B01 0B03 Extend 0B05 0B0C ALetter 0B0F 0B10 ALetter 0B13 0B28 ALetter 0B2A 0B30 ALetter 0B32 0B33 ALetter 0B35 0B39 ALetter 0B3C Extend 0B3D ALetter 0B3E 0B44 Extend 0B47 0B48 Extend 0B4B 0B4D Extend 0B56 0B57 Extend 0B5C 0B5D ALetter 0B5F 0B61 ALetter 0B62 0B63 Extend 0B66 0B6F Numeric 0B71 ALetter 0B82 Extend 0B83 ALetter 0B85 0B8A ALetter 0B8E 0B90 ALetter 0B92 0B95 ALetter 0B99 0B9A ALetter 0B9C ALetter 0B9E 0B9F ALetter 0BA3 0BA4 ALetter 0BA8 0BAA ALetter 0BAE 0BB9 ALetter 0BBE 0BC2 Extend 0BC6 0BC8 Extend 0BCA 0BCD Extend 0BD0 ALetter 0BD7 Extend 0BE6 0BEF Numeric 0C01 0C03 Extend 0C05 0C0C ALetter 0C0E 0C10 ALetter 0C12 0C28 ALetter 0C2A 0C33 ALetter 0C35 0C39 ALetter 0C3D ALetter 0C3E 0C44 Extend 0C46 0C48 Extend 0C4A 0C4D Extend 0C55 0C56 Extend 0C58 0C59 ALetter 0C60 0C61 ALetter 0C62 0C63 Extend 0C66 0C6F Numeric 0C82 0C83 Extend 0C85 0C8C ALetter 0C8E 0C90 ALetter 0C92 0CA8 ALetter 0CAA 0CB3 ALetter 0CB5 0CB9 ALetter 0CBC Extend 0CBD ALetter 0CBE 0CC4 Extend 0CC6 0CC8 Extend 0CCA 0CCD Extend 0CD5 0CD6 Extend 0CDE ALetter 0CE0 0CE1 ALetter 0CE2 0CE3 Extend 0CE6 0CEF Numeric 0CF1 0CF2 ALetter 0D02 0D03 Extend 0D05 0D0C ALetter 0D0E 0D10 ALetter 0D12 0D3A ALetter 0D3D ALetter 0D3E 0D44 Extend 0D46 0D48 Extend 0D4A 0D4D Extend 0D4E ALetter 0D57 Extend 0D60 0D61 ALetter 0D62 0D63 Extend 0D66 0D6F Numeric 0D7A 0D7F ALetter 0D82 0D83 Extend 0D85 0D96 ALetter 0D9A 0DB1 ALetter 0DB3 0DBB ALetter 0DBD ALetter 0DC0 0DC6 ALetter 0DCA Extend 0DCF 0DD4 Extend 0DD6 Extend 0DD8 0DDF Extend 0DF2 0DF3 Extend 0E31 Extend 0E34 0E3A Extend 0E47 0E4E Extend 0E50 0E59 Numeric 0EB1 Extend 0EB4 0EB9 Extend 0EBB 0EBC Extend 0EC8 0ECD Extend 0ED0 0ED9 Numeric 0F00 ALetter 0F18 0F19 Extend 0F20 0F29 Numeric 0F35 Extend 0F37 Extend 0F39 Extend 0F3E 0F3F Extend 0F40 0F47 ALetter 0F49 0F6C ALetter 0F71 0F84 Extend 0F86 0F87 Extend 0F88 0F8C ALetter 0F8D 0F97 Extend 0F99 0FBC Extend 0FC6 Extend 102B 103E Extend 1040 1049 Numeric 1056 1059 Extend 105E 1060 Extend 1062 1064 Extend 1067 106D Extend 1071 1074 Extend 1082 108D Extend 108F Extend 1090 1099 Numeric 109A 109D Extend 10A0 10C5 ALetter 10C7 ALetter 10CD ALetter 10D0 10FA ALetter 10FC 1248 ALetter 124A 124D ALetter 1250 1256 ALetter 1258 ALetter 125A 125D ALetter 1260 1288 ALetter 128A 128D ALetter 1290 12B0 ALetter 12B2 12B5 ALetter 12B8 12BE ALetter 12C0 ALetter 12C2 12C5 ALetter 12C8 12D6 ALetter 12D8 1310 ALetter 1312 1315 ALetter 1318 135A ALetter 135D 135F Extend 1380 138F ALetter 13A0 13F4 ALetter 1401 166C ALetter 166F 167F ALetter 1681 169A ALetter 16A0 16EA ALetter 16EE 16F0 ALetter 1700 170C ALetter 170E 1711 ALetter 1712 1714 Extend 1720 1731 ALetter 1732 1734 Extend 1740 1751 ALetter 1752 1753 Extend 1760 176C ALetter 176E 1770 ALetter 1772 1773 Extend 17B4 17D3 Extend 17DD Extend 17E0 17E9 Numeric 180B 180D Extend 1810 1819 Numeric 1820 1877 ALetter 1880 18A8 ALetter 18A9 Extend 18AA ALetter 18B0 18F5 ALetter 1900 191C ALetter 1920 192B Extend 1930 193B Extend 1946 194F Numeric 19B0 19C0 Extend 19C8 19C9 Extend 19D0 19D9 Numeric 1A00 1A16 ALetter 1A17 1A1B Extend 1A55 1A5E Extend 1A60 1A7C Extend 1A7F Extend 1A80 1A89 Numeric 1A90 1A99 Numeric 1B00 1B04 Extend 1B05 1B33 ALetter 1B34 1B44 Extend 1B45 1B4B ALetter 1B50 1B59 Numeric 1B6B 1B73 Extend 1B80 1B82 Extend 1B83 1BA0 ALetter 1BA1 1BAD Extend 1BAE 1BAF ALetter 1BB0 1BB9 Numeric 1BBA 1BE5 ALetter 1BE6 1BF3 Extend 1C00 1C23 ALetter 1C24 1C37 Extend 1C40 1C49 Numeric 1C4D 1C4F ALetter 1C50 1C59 Numeric 1C5A 1C7D ALetter 1CD0 1CD2 Extend 1CD4 1CE8 Extend 1CE9 1CEC ALetter 1CED Extend 1CEE 1CF1 ALetter 1CF2 1CF4 Extend 1CF5 1CF6 ALetter 1D00 1DBF ALetter 1DC0 1DE6 Extend 1DFC 1DFF Extend 1E00 1F15 ALetter 1F18 1F1D ALetter 1F20 1F45 ALetter 1F48 1F4D ALetter 1F50 1F57 ALetter 1F59 ALetter 1F5B ALetter 1F5D ALetter 1F5F 1F7D ALetter 1F80 1FB4 ALetter 1FB6 1FBC ALetter 1FBE ALetter 1FC2 1FC4 ALetter 1FC6 1FCC ALetter 1FD0 1FD3 ALetter 1FD6 1FDB ALetter 1FE0 1FEC ALetter 1FF2 1FF4 ALetter 1FF6 1FFC ALetter 200C 200D Extend 200E 200F Format 2018 2019 MidNumLet 2024 MidNumLet 2027 MidLetter 2028 2029 Newline 202A 202E Format 203F 2040 ExtendNumLet 2044 MidNum 2054 ExtendNumLet 2060 2064 Format 206A 206F Format 2071 ALetter 207F ALetter 2090 209C ALetter 20D0 20F0 Extend 2102 ALetter 2107 ALetter 210A 2113 ALetter 2115 ALetter 2119 211D ALetter 2124 ALetter 2126 ALetter 2128 ALetter 212A 212D ALetter 212F 2139 ALetter 213C 213F ALetter 2145 2149 ALetter 214E ALetter 2160 2188 ALetter 24B6 24E9 ALetter 2C00 2C2E ALetter 2C30 2C5E ALetter 2C60 2CE4 ALetter 2CEB 2CEE ALetter 2CEF 2CF1 Extend 2CF2 2CF3 ALetter 2D00 2D25 ALetter 2D27 ALetter 2D2D ALetter 2D30 2D67 ALetter 2D6F ALetter 2D7F Extend 2D80 2D96 ALetter 2DA0 2DA6 ALetter 2DA8 2DAE ALetter 2DB0 2DB6 ALetter 2DB8 2DBE ALetter 2DC0 2DC6 ALetter 2DC8 2DCE ALetter 2DD0 2DD6 ALetter 2DD8 2DDE ALetter 2DE0 2DFF Extend 2E2F ALetter 3005 ALetter 302A 302F Extend 3031 3035 Katakana 303B 303C ALetter 3099 309A Extend 309B 309C Katakana 30A0 30FA Katakana 30FC 30FF Katakana 3105 312D ALetter 3131 318E ALetter 31A0 31BA ALetter 31F0 31FF Katakana 32D0 32FE Katakana 3300 3357 Katakana A000 A48C ALetter A4D0 A4FD ALetter A500 A60C ALetter A610 A61F ALetter A620 A629 Numeric A62A A62B ALetter A640 A66E ALetter A66F A672 Extend A674 A67D Extend A67F A697 ALetter A69F Extend A6A0 A6EF ALetter A6F0 A6F1 Extend A717 A71F ALetter A722 A788 ALetter A78B A78E ALetter A790 A793 ALetter A7A0 A7AA ALetter A7F8 A801 ALetter A802 Extend A803 A805 ALetter A806 Extend A807 A80A ALetter A80B Extend A80C A822 ALetter A823 A827 Extend A840 A873 ALetter A880 A881 Extend A882 A8B3 ALetter A8B4 A8C4 Extend A8D0 A8D9 Numeric A8E0 A8F1 Extend A8F2 A8F7 ALetter A8FB ALetter A900 A909 Numeric A90A A925 ALetter A926 A92D Extend A930 A946 ALetter A947 A953 Extend A960 A97C ALetter A980 A983 Extend A984 A9B2 ALetter A9B3 A9C0 Extend A9CF ALetter A9D0 A9D9 Numeric AA00 AA28 ALetter AA29 AA36 Extend AA40 AA42 ALetter AA43 Extend AA44 AA4B ALetter AA4C AA4D Extend AA50 AA59 Numeric AA7B Extend AAB0 Extend AAB2 AAB4 Extend AAB7 AAB8 Extend AABE AABF Extend AAC1 Extend AAE0 AAEA ALetter AAEB AAEF Extend AAF2 AAF4 ALetter AAF5 AAF6 Extend AB01 AB06 ALetter AB09 AB0E ALetter AB11 AB16 ALetter AB20 AB26 ALetter AB28 AB2E ALetter ABC0 ABE2 ALetter ABE3 ABEA Extend ABEC ABED Extend ABF0 ABF9 Numeric AC00 D7A3 ALetter D7B0 D7C6 ALetter D7CB D7FB ALetter FB00 FB06 ALetter FB13 FB17 ALetter FB1D ALetter FB1E Extend FB1F FB28 ALetter FB2A FB36 ALetter FB38 FB3C ALetter FB3E ALetter FB40 FB41 ALetter FB43 FB44 ALetter FB46 FBB1 ALetter FBD3 FD3D ALetter FD50 FD8F ALetter FD92 FDC7 ALetter FDF0 FDFB ALetter FE00 FE0F Extend FE10 MidNum FE13 MidLetter FE14 MidNum FE20 FE26 Extend FE33 FE34 ExtendNumLet FE4D FE4F ExtendNumLet FE50 MidNum FE52 MidNumLet FE54 MidNum FE55 MidLetter FE70 FE74 ALetter FE76 FEFC ALetter FEFF Format FF07 MidNumLet FF0C MidNum FF0E MidNumLet FF1A MidLetter FF1B MidNum FF21 FF3A ALetter FF3F ExtendNumLet FF41 FF5A ALetter FF66 FF9D Katakana FF9E FF9F Extend FFA0 FFBE ALetter FFC2 FFC7 ALetter FFCA FFCF ALetter FFD2 FFD7 ALetter FFDA FFDC ALetter FFF9 FFFB Format 10000 1000B ALetter 1000D 10026 ALetter 10028 1003A ALetter 1003C 1003D ALetter 1003F 1004D ALetter 10050 1005D ALetter 10080 100FA ALetter 10140 10174 ALetter 101FD Extend 10280 1029C ALetter 102A0 102D0 ALetter 10300 1031E ALetter 10330 1034A ALetter 10380 1039D ALetter 103A0 103C3 ALetter 103C8 103CF ALetter 103D1 103D5 ALetter 10400 1049D ALetter 104A0 104A9 Numeric 10800 10805 ALetter 10808 ALetter 1080A 10835 ALetter 10837 10838 ALetter 1083C ALetter 1083F 10855 ALetter 10900 10915 ALetter 10920 10939 ALetter 10980 109B7 ALetter 109BE 109BF ALetter 10A00 ALetter 10A01 10A03 Extend 10A05 10A06 Extend 10A0C 10A0F Extend 10A10 10A13 ALetter 10A15 10A17 ALetter 10A19 10A33 ALetter 10A38 10A3A Extend 10A3F Extend 10A60 10A7C ALetter 10B00 10B35 ALetter 10B40 10B55 ALetter 10B60 10B72 ALetter 10C00 10C48 ALetter 11000 11002 Extend 11003 11037 ALetter 11038 11046 Extend 11066 1106F Numeric 11080 11082 Extend 11083 110AF ALetter 110B0 110BA Extend 110BD Format 110D0 110E8 ALetter 110F0 110F9 Numeric 11100 11102 Extend 11103 11126 ALetter 11127 11134 Extend 11136 1113F Numeric 11180 11182 Extend 11183 111B2 ALetter 111B3 111C0 Extend 111C1 111C4 ALetter 111D0 111D9 Numeric 11680 116AA ALetter 116AB 116B7 Extend 116C0 116C9 Numeric 12000 1236E ALetter 12400 12462 ALetter 13000 1342E ALetter 16800 16A38 ALetter 16F00 16F44 ALetter 16F50 ALetter 16F51 16F7E Extend 16F8F 16F92 Extend 16F93 16F9F ALetter 1B000 Katakana 1D165 1D169 Extend 1D16D 1D172 Extend 1D173 1D17A Format 1D17B 1D182 Extend 1D185 1D18B Extend 1D1AA 1D1AD Extend 1D242 1D244 Extend 1D400 1D454 ALetter 1D456 1D49C ALetter 1D49E 1D49F ALetter 1D4A2 ALetter 1D4A5 1D4A6 ALetter 1D4A9 1D4AC ALetter 1D4AE 1D4B9 ALetter 1D4BB ALetter 1D4BD 1D4C3 ALetter 1D4C5 1D505 ALetter 1D507 1D50A ALetter 1D50D 1D514 ALetter 1D516 1D51C ALetter 1D51E 1D539 ALetter 1D53B 1D53E ALetter 1D540 1D544 ALetter 1D546 ALetter 1D54A 1D550 ALetter 1D552 1D6A5 ALetter 1D6A8 1D6C0 ALetter 1D6C2 1D6DA ALetter 1D6DC 1D6FA ALetter 1D6FC 1D714 ALetter 1D716 1D734 ALetter 1D736 1D74E ALetter 1D750 1D76E ALetter 1D770 1D788 ALetter 1D78A 1D7A8 ALetter 1D7AA 1D7C2 ALetter 1D7C4 1D7CB ALetter 1D7CE 1D7FF Numeric 1EE00 1EE03 ALetter 1EE05 1EE1F ALetter 1EE21 1EE22 ALetter 1EE24 ALetter 1EE27 ALetter 1EE29 1EE32 ALetter 1EE34 1EE37 ALetter 1EE39 ALetter 1EE3B ALetter 1EE42 ALetter 1EE47 ALetter 1EE49 ALetter 1EE4B ALetter 1EE4D 1EE4F ALetter 1EE51 1EE52 ALetter 1EE54 ALetter 1EE57 ALetter 1EE59 ALetter 1EE5B ALetter 1EE5D ALetter 1EE5F ALetter 1EE61 1EE62 ALetter 1EE64 ALetter 1EE67 1EE6A ALetter 1EE6C 1EE72 ALetter 1EE74 1EE77 ALetter 1EE79 1EE7C ALetter 1EE7E ALetter 1EE80 1EE89 ALetter 1EE8B 1EE9B ALetter 1EEA1 1EEA3 ALetter 1EEA5 1EEA9 ALetter 1EEAB 1EEBB ALetter E0001 Format E0020 E007F Format E0100 E01EF Extend END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/To/WB.pl
Perl
mit
13,400
#line 1 package Inline::C; $VERSION = '0.44'; use strict; require Inline; use Config; use Data::Dumper; use Carp; use Cwd qw(cwd abs_path); use File::Spec; @Inline::C::ISA = qw(Inline); #============================================================================== # Register this module as an Inline language support module #============================================================================== sub register { return { language => 'C', # XXX Breaking this on purpose; let's see who screams # aliases => ['c'], type => 'compiled', suffix => $Config{dlext}, }; } #============================================================================== # Validate the C config options #============================================================================== sub usage_validate { my $key = shift; return <<END; The value of config option '$key' must be a string or an array ref END } sub validate { my $o = shift; $o->{ILSM} ||= {}; $o->{ILSM}{XS} ||= {}; $o->{ILSM}{MAKEFILE} ||= {}; if (not $o->UNTAINT) { require FindBin; $o->{ILSM}{MAKEFILE}{INC} = "-I$FindBin::Bin"; } $o->{ILSM}{AUTOWRAP} = 0 if not defined $o->{ILSM}{AUTOWRAP}; $o->{ILSM}{XSMODE} = 0 if not defined $o->{ILSM}{XSMODE}; $o->{ILSM}{AUTO_INCLUDE} ||= <<END; #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "INLINE.h" END $o->{ILSM}{FILTERS} ||= []; $o->{STRUCT} ||= { '.macros' => '', '.xs' => '', '.any' => 0, '.all' => 0, }; while (@_) { my ($key, $value) = (shift, shift); if ($key eq 'MAKE' or $key eq 'AUTOWRAP' or $key eq 'XSMODE' ) { $o->{ILSM}{$key} = $value; next; } if ($key eq 'CC' or $key eq 'LD') { $o->{ILSM}{MAKEFILE}{$key} = $value; next; } if ($key eq 'LIBS') { $o->add_list($o->{ILSM}{MAKEFILE}, $key, $value, []); next; } if ($key eq 'INC' or $key eq 'MYEXTLIB' or $key eq 'OPTIMIZE' or $key eq 'CCFLAGS' or $key eq 'LDDLFLAGS') { $o->add_string($o->{ILSM}{MAKEFILE}, $key, $value, ''); next; } if ($key eq 'TYPEMAPS') { croak "TYPEMAPS file '$value' not found" unless -f $value; $value = File::Spec->rel2abs($value); $o->add_list($o->{ILSM}{MAKEFILE}, $key, $value, []); next; } if ($key eq 'AUTO_INCLUDE') { $o->add_text($o->{ILSM}, $key, $value, ''); next; } if ($key eq 'BOOT') { $o->add_text($o->{ILSM}{XS}, $key, $value, ''); next; } if ($key eq 'PREFIX') { croak "Invalid value for 'PREFIX' option" unless ($value =~ /^\w*$/ and $value !~ /\n/); $o->{ILSM}{XS}{PREFIX} = $value; next; } if ($key eq 'FILTERS') { next if $value eq '1' or $value eq '0'; # ignore ENABLE, DISABLE $value = [$value] unless ref($value) eq 'ARRAY'; my %filters; for my $val (@$value) { if (ref($val) eq 'CODE') { $o->add_list($o->{ILSM}, $key, $val, []); } else { eval { require Inline::Filters }; croak "'FILTERS' option requires Inline::Filters to be installed." if $@; %filters = Inline::Filters::get_filters($o->{API}{language}) unless keys %filters; if (defined $filters{$val}) { my $filter = Inline::Filters->new($val, $filters{$val}); $o->add_list($o->{ILSM}, $key, $filter, []); } else { croak "Invalid filter $val specified."; } } } next; } if ($key eq 'STRUCTS') { # A list of struct names if (ref($value) eq 'ARRAY') { for my $val (@$value) { croak "Invalid value for 'STRUCTS' option" unless ($val =~ /^[_a-z][_0-9a-z]*$/i); $o->{STRUCT}{$val}++; } } # Enable or disable elsif ($value =~ /^\d+$/) { $o->{STRUCT}{'.any'} = $value; } # A single struct name else { croak "Invalid value for 'STRUCTS' option" unless ($value =~ /^[_a-z][_0-9a-z]*$/i); $o->{STRUCT}{$value}++; } eval { require Inline::Struct }; croak "'STRUCTS' option requires Inline::Struct to be installed." if $@; $o->{STRUCT}{'.any'} = 1; next; } my $class = ref $o; # handles subclasses correctly. croak "'$key' is not a valid config option for $class\n"; } } sub add_list { my $o = shift; my ($ref, $key, $value, $default) = @_; $value = [$value] unless ref $value eq 'ARRAY'; for (@$value) { if (defined $_) { push @{$ref->{$key}}, $_; } else { $ref->{$key} = $default; } } } sub add_string { my $o = shift; my ($ref, $key, $value, $default) = @_; $value = [$value] unless ref $value; croak usage_validate($key) unless ref($value) eq 'ARRAY'; for (@$value) { if (defined $_) { $ref->{$key} .= ' ' . $_; } else { $ref->{$key} = $default; } } } sub add_text { my $o = shift; my ($ref, $key, $value, $default) = @_; $value = [$value] unless ref $value; croak usage_validate($key) unless ref($value) eq 'ARRAY'; for (@$value) { if (defined $_) { chomp; $ref->{$key} .= $_ . "\n"; } else { $ref->{$key} = $default; } } } #============================================================================== # Return a small report about the C code.. #============================================================================== sub info { my $o = shift; return <<END if $o->{ILSM}{XSMODE}; No information is currently generated when using XSMODE. END my $text = ''; $o->preprocess; $o->parse; if (defined $o->{ILSM}{parser}{data}{functions}) { $text .= "The following Inline $o->{API}{language} function(s) have been successfully bound to Perl:\n"; my $parser = $o->{ILSM}{parser}; my $data = $parser->{data}; for my $function (sort @{$data->{functions}}) { my $return_type = $data->{function}{$function}{return_type}; my @arg_names = @{$data->{function}{$function}{arg_names}}; my @arg_types = @{$data->{function}{$function}{arg_types}}; my @args = map {$_ . ' ' . shift @arg_names} @arg_types; $text .= "\t$return_type $function(" . join(', ', @args) . ")\n"; } } else { $text .= "No $o->{API}{language} functions have been successfully bound to Perl.\n\n"; } $text .= Inline::Struct::info($o) if $o->{STRUCT}{'.any'}; return $text; } sub config { my $o = shift; } #============================================================================== # Parse and compile C code #============================================================================== my $total_build_time; sub build { my $o = shift; if ($o->{CONFIG}{BUILD_TIMERS}) { eval {require Time::HiRes}; croak "You need Time::HiRes for BUILD_TIMERS option:\n$@" if $@; $total_build_time = Time::HiRes::time(); } $o->call('preprocess', 'Build Prepocess'); $o->call('parse', 'Build Parse'); $o->call('write_XS', 'Build Glue 1'); $o->call('write_Inline_headers', 'Build Glue 2'); $o->call('write_Makefile_PL', 'Build Glue 3'); $o->call('compile', 'Build Compile'); if ($o->{CONFIG}{BUILD_TIMERS}) { $total_build_time = Time::HiRes::time() - $total_build_time; printf STDERR "Total Build Time: %5.4f secs\n", $total_build_time; } } sub call { my ($o, $method, $header, $indent) = (@_, 0); my $time; my $i = ' ' x $indent; print STDERR "${i}Starting $header Stage\n" if $o->{CONFIG}{BUILD_NOISY}; $time = Time::HiRes::time() if $o->{CONFIG}{BUILD_TIMERS}; $o->$method(); $time = Time::HiRes::time() - $time if $o->{CONFIG}{BUILD_TIMERS}; print STDERR "${i}Finished $header Stage\n" if $o->{CONFIG}{BUILD_NOISY}; printf STDERR "${i}Time for $header Stage: %5.4f secs\n", $time if $o->{CONFIG}{BUILD_TIMERS}; print STDERR "\n" if $o->{CONFIG}{BUILD_NOISY}; } #============================================================================== # Apply any #============================================================================== sub preprocess { my $o = shift; return if $o->{ILSM}{parser}; $o->get_maps; $o->get_types; $o->{ILSM}{code} = $o->filter(@{$o->{ILSM}{FILTERS}}); } #============================================================================== # Parse the function definition information out of the C code #============================================================================== sub parse { my $o = shift; return if $o->{ILSM}{parser}; return if $o->{ILSM}{XSMODE}; my $parser = $o->{ILSM}{parser} = $o->get_parser; $parser->{data}{typeconv} = $o->{ILSM}{typeconv}; $parser->{data}{AUTOWRAP} = $o->{ILSM}{AUTOWRAP}; Inline::Struct::parse($o) if $o->{STRUCT}{'.any'}; $parser->code($o->{ILSM}{code}) or croak <<END; Bad $o->{API}{language} code passed to Inline at @{[caller(2)]} END } # Create and initialize a parser sub get_parser { my $o = shift; require Inline::C::ParseRecDescent; Inline::C::ParseRecDescent::get_parser($o); } #============================================================================== # Gather the path names of all applicable typemap files. #============================================================================== sub get_maps { my $o = shift; my $typemap = ''; my $file; $file = File::Spec->catfile($Config::Config{installprivlib},"ExtUtils","typemap"); $typemap = $file if -f $file; $file = File::Spec->catfile($Config::Config{privlibexp} ,"ExtUtils","typemap"); $typemap = $file if (not $typemap and -f $file); warn "Can't find the default system typemap file" if (not $typemap and $^W); unshift(@{$o->{ILSM}{MAKEFILE}{TYPEMAPS}}, $typemap) if $typemap; if (not $o->UNTAINT) { require FindBin; $file = File::Spec->catfile($FindBin::Bin,"typemap"); push(@{$o->{ILSM}{MAKEFILE}{TYPEMAPS}}, $file) if -f $file; } } #============================================================================== # This routine parses XS typemap files to get a list of valid types to create # bindings to. This code is mostly hacked out of Larry Wall's xsubpp program. #============================================================================== sub get_types { my (%type_kind, %proto_letter, %input_expr, %output_expr); my $o = shift; croak "No typemaps specified for Inline C code" unless @{$o->{ILSM}{MAKEFILE}{TYPEMAPS}}; my $proto_re = "[" . quotemeta('\$%&*@;') . "]"; foreach my $typemap (@{$o->{ILSM}{MAKEFILE}{TYPEMAPS}}) { next unless -e $typemap; # skip directories, binary files etc. warn("Warning: ignoring non-text typemap file '$typemap'\n"), next unless -T $typemap; open(TYPEMAP, $typemap) or warn ("Warning: could not open typemap file '$typemap': $!\n"), next; my $mode = 'Typemap'; my $junk = ""; my $current = \$junk; while (<TYPEMAP>) { next if /^\s*\#/; my $line_no = $. + 1; if (/^INPUT\s*$/) {$mode = 'Input'; $current = \$junk; next} if (/^OUTPUT\s*$/) {$mode = 'Output'; $current = \$junk; next} if (/^TYPEMAP\s*$/) {$mode = 'Typemap'; $current = \$junk; next} if ($mode eq 'Typemap') { chomp; my $line = $_; TrimWhitespace($_); # skip blank lines and comment lines next if /^$/ or /^\#/; my ($type,$kind, $proto) = /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/ or warn("Warning: File '$typemap' Line $. '$line' TYPEMAP entry needs 2 or 3 columns\n"), next; $type = TidyType($type); $type_kind{$type} = $kind; # prototype defaults to '$' $proto = "\$" unless $proto; warn("Warning: File '$typemap' Line $. '$line' Invalid prototype '$proto'\n") unless ValidProtoString($proto); $proto_letter{$type} = C_string($proto); } elsif (/^\s/) { $$current .= $_; } elsif ($mode eq 'Input') { s/\s+$//; $input_expr{$_} = ''; $current = \$input_expr{$_}; } else { s/\s+$//; $output_expr{$_} = ''; $current = \$output_expr{$_}; } } close(TYPEMAP); } my %valid_types = map {($_, 1)} grep {defined $input_expr{$type_kind{$_}}} keys %type_kind; my %valid_rtypes = map {($_, 1)} (grep {defined $output_expr{$type_kind{$_}}} keys %type_kind), 'void'; $o->{ILSM}{typeconv}{type_kind} = \%type_kind; $o->{ILSM}{typeconv}{input_expr} = \%input_expr; $o->{ILSM}{typeconv}{output_expr} = \%output_expr; $o->{ILSM}{typeconv}{valid_types} = \%valid_types; $o->{ILSM}{typeconv}{valid_rtypes} = \%valid_rtypes; } sub ValidProtoString ($) { my $string = shift; my $proto_re = "[" . quotemeta('\$%&*@;') . "]"; return ($string =~ /^$proto_re+$/) ? $string : 0; } sub TrimWhitespace { $_[0] =~ s/^\s+|\s+$//go; } sub TidyType { local $_ = shift; s|\s*(\*+)\s*|$1|g; s|(\*+)| $1 |g; s|\s+| |g; TrimWhitespace($_); $_; } sub C_string ($) { (my $string = shift) =~ s|\\|\\\\|g; $string; } #============================================================================== # Write the XS code #============================================================================== sub write_XS { my $o = shift; my $modfname = $o->{API}{modfname}; my $module = $o->{API}{module}; $o->mkpath($o->{API}{build_dir}); open XS, "> ".File::Spec->catfile($o->{API}{build_dir},"$modfname.xs") or croak $!; if ($o->{ILSM}{XSMODE}) { warn <<END if $^W and $o->{ILSM}{code} !~ /MODULE\s*=\s*$module\b/; While using Inline XSMODE, your XS code does not have a line with MODULE = $module You should use the Inline NAME config option, and it should match the XS MODULE name. END print XS $o->xs_code; } else { print XS $o->xs_generate; } close XS; } #============================================================================== # Generate the XS glue code (piece together lots of snippets) #============================================================================== sub xs_generate { my $o = shift; return join '', ($o->xs_includes, $o->xs_struct_macros, $o->xs_code, $o->xs_struct_code, $o->xs_bindings, $o->xs_boot, ); } sub xs_includes { my $o = shift; return $o->{ILSM}{AUTO_INCLUDE}; } sub xs_struct_macros { my $o = shift; return $o->{STRUCT}{'.macros'}; } sub xs_code { my $o = shift; return $o->{ILSM}{code}; } sub xs_struct_code { my $o = shift; return $o->{STRUCT}{'.xs'}; } sub xs_boot { my $o = shift; if (defined $o->{ILSM}{XS}{BOOT} and $o->{ILSM}{XS}{BOOT}) { return <<END; BOOT: $o->{ILSM}{XS}{BOOT} END } return ''; } sub xs_bindings { my $o = shift; my ($pkg, $module) = @{$o->{API}}{qw(pkg module)}; my $prefix = (($o->{ILSM}{XS}{PREFIX}) ? "PREFIX = $o->{ILSM}{XS}{PREFIX}" : ''); my $XS = <<END; MODULE = $module PACKAGE = $pkg $prefix PROTOTYPES: DISABLE END my $parser = $o->{ILSM}{parser}; my $data = $parser->{data}; warn("Warning. No Inline C functions bound to Perl\n" . "Check your C function definition(s) for Inline compatibility\n\n") if ((not defined$data->{functions}) and ($^W)); for my $function (@{$data->{functions}}) { my $return_type = $data->{function}->{$function}->{return_type}; my @arg_names = @{$data->{function}->{$function}->{arg_names}}; my @arg_types = @{$data->{function}->{$function}->{arg_types}}; $XS .= join '', ("\n$return_type\n$function (", join(', ', @arg_names), ")\n"); for my $arg_name (@arg_names) { my $arg_type = shift @arg_types; last if $arg_type eq '...'; $XS .= "\t$arg_type\t$arg_name\n"; } my $listargs = ''; $listargs = pop @arg_names if (@arg_names and $arg_names[-1] eq '...'); my $arg_name_list = join(', ', @arg_names); if ($return_type eq 'void') { $XS .= <<END; PREINIT: I32* temp; PPCODE: temp = PL_markstack_ptr++; $function($arg_name_list); if (PL_markstack_ptr != temp) { /* truly void, because dXSARGS not invoked */ PL_markstack_ptr = temp; XSRETURN_EMPTY; /* return empty stack */ } /* must have used dXSARGS; list context implied */ return; /* assume stack size is correct */ END } elsif ($listargs) { $XS .= <<END; PREINIT: I32* temp; CODE: temp = PL_markstack_ptr++; RETVAL = $function($arg_name_list); PL_markstack_ptr = temp; OUTPUT: RETVAL END } } $XS .= "\n"; return $XS; } #============================================================================== # Generate the INLINE.h file. #============================================================================== sub write_Inline_headers { my $o = shift; open HEADER, "> ".File::Spec->catfile($o->{API}{build_dir},"INLINE.h") or croak; print HEADER <<'END'; #define Inline_Stack_Vars dXSARGS #define Inline_Stack_Items items #define Inline_Stack_Item(x) ST(x) #define Inline_Stack_Reset sp = mark #define Inline_Stack_Push(x) XPUSHs(x) #define Inline_Stack_Done PUTBACK #define Inline_Stack_Return(x) XSRETURN(x) #define Inline_Stack_Void XSRETURN(0) #define INLINE_STACK_VARS Inline_Stack_Vars #define INLINE_STACK_ITEMS Inline_Stack_Items #define INLINE_STACK_ITEM(x) Inline_Stack_Item(x) #define INLINE_STACK_RESET Inline_Stack_Reset #define INLINE_STACK_PUSH(x) Inline_Stack_Push(x) #define INLINE_STACK_DONE Inline_Stack_Done #define INLINE_STACK_RETURN(x) Inline_Stack_Return(x) #define INLINE_STACK_VOID Inline_Stack_Void #define inline_stack_vars Inline_Stack_Vars #define inline_stack_items Inline_Stack_Items #define inline_stack_item(x) Inline_Stack_Item(x) #define inline_stack_reset Inline_Stack_Reset #define inline_stack_push(x) Inline_Stack_Push(x) #define inline_stack_done Inline_Stack_Done #define inline_stack_return(x) Inline_Stack_Return(x) #define inline_stack_void Inline_Stack_Void END close HEADER; } #============================================================================== # Generate the Makefile.PL #============================================================================== sub write_Makefile_PL { my $o = shift; $o->{ILSM}{xsubppargs} = ''; for (@{$o->{ILSM}{MAKEFILE}{TYPEMAPS}}) { $o->{ILSM}{xsubppargs} .= "-typemap $_ "; } my %options = ( VERSION => $o->{API}{version} || '0.00', %{$o->{ILSM}{MAKEFILE}}, NAME => $o->{API}{module}, ); open MF, "> ".File::Spec->catfile($o->{API}{build_dir},"Makefile.PL") or croak; print MF <<END; use ExtUtils::MakeMaker; my %options = %\{ END local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 1; print MF Data::Dumper::Dumper(\ %options); print MF <<END; \}; WriteMakefile(\%options); # Remove the Makefile dependency. Causes problems on a few systems. sub MY::makefile { '' } END close MF; } #============================================================================== # Run the build process. #============================================================================== sub compile { my $o = shift; my $build_dir = $o->{API}{build_dir}; my $cwd = &cwd; ($cwd) = $cwd =~ /(.*)/ if $o->UNTAINT; chdir $build_dir; $o->call('makefile_pl', '"perl Makefile.PL"', 2); $o->call('make', '"make"', 2); $o->call('make_install', '"make install"', 2); chdir $cwd; $o->call('cleanup', 'Cleaning Up', 2); } sub makefile_pl { my ($o) = @_; my $perl; -f ($perl = $Config::Config{perlpath}) or ($perl = $^X) or croak "Can't locate your perl binary"; $o->system_call("$perl Makefile.PL", 'out.Makefile_PL'); $o->fix_make; } sub make { my ($o) = @_; my $make = $o->{ILSM}{MAKE} || $Config::Config{make} or croak "Can't locate your make binary"; $o->system_call("$make", 'out.make'); } sub make_install { my ($o) = @_; my $make = $o->{ILSM}{MAKE} || $Config::Config{make} or croak "Can't locate your make binary"; $o->system_call("$make pure_install", 'out.make_install'); } sub cleanup { my ($o) = @_; my ($modpname, $modfname, $install_lib) = @{$o->{API}}{qw(modpname modfname install_lib)}; if ($o->{API}{cleanup}) { $o->rmpath(File::Spec->catdir($o->{API}{directory},'build'), $modpname); my $autodir = File::Spec->catdir($install_lib,'auto',$modpname); unlink (File::Spec->catfile($autodir,'.packlist'), File::Spec->catfile($autodir,'$modfname.bs'), File::Spec->catfile($autodir,'$modfname.exp'), #MSWin32 File::Spec->catfile($autodir,'$modfname.lib'), #MSWin32 ); } } sub system_call { my ($o, $cmd, $output_file) = @_; my $build_noisy = defined $ENV{PERL_INLINE_BUILD_NOISY} ? $ENV{PERL_INLINE_BUILD_NOISY} : $o->{CONFIG}{BUILD_NOISY}; if (not $build_noisy) { $cmd = "$cmd > $output_file 2>&1"; } ($cmd) = $cmd =~ /(.*)/ if $o->UNTAINT; system($cmd) == 0 or croak($o->build_error_message($cmd, $output_file, $build_noisy)); } sub build_error_message { my ($o, $cmd, $output_file, $build_noisy) = @_; my $build_dir = $o->{API}{build_dir}; my $output = ''; if (not $build_noisy and open(OUTPUT, $output_file) ) { local $/; $output = <OUTPUT>; close OUTPUT; } return $output . <<END; A problem was encountered while attempting to compile and install your Inline $o->{API}{language} code. The command that failed was: $cmd The build directory was: $build_dir To debug the problem, cd to the build directory, and inspect the output files. END } #============================================================================== # This routine fixes problems with the MakeMaker Makefile. #============================================================================== my %fixes = ( INSTALLSITEARCH => 'install_lib', INSTALLDIRS => 'installdirs', XSUBPPARGS => 'xsubppargs', INSTALLSITELIB => 'install_lib', ); sub fix_make { use strict; my (@lines, $fix); my $o = shift; $o->{ILSM}{install_lib} = $o->{API}{install_lib}; $o->{ILSM}{installdirs} = 'site'; open(MAKEFILE, '< Makefile') or croak "Can't open Makefile for input: $!\n"; @lines = <MAKEFILE>; close MAKEFILE; open(MAKEFILE, '> Makefile') or croak "Can't open Makefile for output: $!\n"; for (@lines) { if (/^(\w+)\s*=\s*\S+.*$/ and $fix = $fixes{$1} ) { print MAKEFILE "$1 = $o->{ILSM}{$fix}\n" } else { print MAKEFILE; } } close MAKEFILE; } 1; __END__
gitpan/Algorithm-LBFGS
inc/Inline/C.pm
Perl
mit
22,732
package GAL::Base; use strict; use vars qw($VERSION); use Carp qw(croak cluck); use Bio::DB::Fasta; use Scalar::Util qw(blessed); $VERSION = 0.2.1; =head1 NAME L<GAL::Base> - Base class for the Genome Annotation Library =head1 VERSION This document describes L<GAL::Base> version 0.2.1 =head1 SYNOPSIS use base qw(GAL::Base); =head1 DESCRIPTION L<GAL::Base> serves as a base class for all of the other classes in GAL. It is not intended to be instantiated directly, but rather to be used with the 'use base' pragma by the other modules. L<GAL::Base> provides object instantiation, argument preparation and attribute setting functions for other classes during object construction. In addition it provides a wide range of utility functions that are expected to be applicable throughout the library. =head1 INHERITS FROM None =head1 INHERITED BY =over 4 =item L<Annotation.pm> =item L<Base.pm> =item L<Index.pm> =item L<Interval.pm> =item L<List.pm> =over 4 =item L<List::Categorical.pm> =item L<List::Numeric.pm> =back =item L<Manual.pm> =item L<Parser.pm> =over 4 =item L<Parser::23andMe.pm> =item L<Parser::basic_snp.pm> =item L<Parser::bed.pm> =item L<Parser::cgi_complete.pm> =item L<Parser::dbsnp_flat.pm> =item L<Parser::gff3.pm> =item L<Parser::gff3_fast.pm> =item L<Parser::hapmap_genotypes.pm> =item L<Parser::hgmd_indel.pm> =item L<Parser::hgmd_snv.pm> =item L<Parser::ncbi_blast_tab.pm> =item L<Parser::samtools_pileup.pm> =item L<Parser::soap_snp.pm> =item L<Parser::solid_snp.pm> =item L<Parser::template.pm> =item L<Parser::template_sequence_alteration.pm> =item L<Parser::ucsc_gene_table.pm> =item L<Parser::vaast_smp.pm> =item L<Parser::VCFv4_0.pm> =back =item L<Reader.pm> =over 4 =item L<Reader::DelimitedLine.pm> =item L<Reader::RecordParser.pm> =item L<Reader::Template.pm> =back =item L<Run.pm> =item L<Schema.pm> =over 4 =item L<Schema::Result::Attribute.pm> =item L<Schema::Result::Feature::cds.pm> =item L<Schema::Result::Feature::exon.pm> =item L<Schema::Result::Feature::five_prime_utr.pm> =item L<Schema::Result::Feature::gene.pm> =item L<Schema::Result::Feature::intron.pm> =item L<Schema::Result::Feature::mrna.pm> =item L<Schema::Result::Feature::protein.pm> =item L<Schema::Result::Feature::sequence_alteration.pm> =item L<Schema::Result::Feature::sequence_feature.pm> =item L<Schema::Result::Feature::template.pm> =item L<Schema::Result::Feature::three_prime_utr.pm> =item L<Schema::Result::Feature::transcript.pm> =item L<Schema::Result::Feature.pm> =item L<Schema::Result::Relationship.pm> =item L<Schema::ResultSet::Feature.pm> =back =item L<SchemaAnnotation.pm> =item L<Storage.pm> =over 4 =item L<Storage::mysql.pm> =item L<Storage::RAM.pm> =item L<Storage::SQLite.pm> =back =back =head1 USES =over =item * L<Carp> =item * L<Bio::DB::Fasta> =item * L<Scalar::Util> =back =head1 CONSTRUCTOR L<GAL::Base> is not intended to by instantiated on it's own. It does however, handle object creation for the rest of the library. Each class in GAL calls: my $self = $class->SUPER::new(@args); This means that GAL::Base - at the bottom of the inheritance chain does the actual object creation. It creates the new object based on the calling class, and then checks to see if there is a 'class' argument provided. If there is it calls the class attribute, which L<GAL::Base> provides, and reblesses the object using the value to the class argument as a subclass of the current calling class. This allows this kind of an idiom for any class that has subclasses: my $parser = GAL::Parser->(class => 'gff3'); That invocation would return a L<GAL::Parser::gff3> object instead of a L<GAL::Parser> object. L<GAL::Base> provides the following attributes to all other classes in the GAL. Each attribute is described full below in the L</"Attributes"> section. =over 4 =item * C<< fasta => '/path/to/fasta/files/' >> This optional parameter defines a path to fasta files that are (or will be) indexed and available to all objects in the library. The object created is an instance of L<Bio::DB::Fasta>. =item * C<< class => 'subclass_name' >> This optional parameter will cause the current object to be reblessed as the given subclass of the calling object. =cut #----------------------------------------------------------------------------- #--------------------------------- Constructor ------------------------------- #----------------------------------------------------------------------------- =head2 new Title : new Usage : GAL::SomeClass->new(); Function: Creates on object of the calling class Returns : An object of the calling class Args : See the attributes described above. =cut sub new { my ($class, @args) = @_; $class = ref($class) || $class; my $self = bless {}, $class; my $args = $self->prepare_args(@args); # Call attribute class first so that objects get reblessed # into the appropriate subclass before they set their # attributes. if ($args->{class}) { $self = $self->class($args->{class}); delete $args->{class}; } $self->_initialize_args($args); return $self; } #----------------------------------------------------------------------------- sub _initialize_args { my ($self, $args) = @_; ###################################################################### # This block of code handels class attributes. Use the # @valid_attributes below to define the valid attributes for # this class. You must have identically named get/set methods # for each attribute. Leave the rest of this block alone! ###################################################################### my @valid_attributes = qw(fasta class); # Set valid class attributes here $self->set_attributes($args, @valid_attributes); ###################################################################### return $args; } #----------------------------------------------------------------------------- #-------------------------------- Attributes --------------------------------- #----------------------------------------------------------------------------- =head1 ATTRIBUTES All attributes can be supplied as parameters to the constructor as a list (or referenece) of key value pairs. =cut =head2 fasta Title : fasta Usage : $fasta = $self->fasta($fasta_dir); Function: Provides a Bio::DB::Fasta object Returns : A Bio::DB::Fasta object Args : A fasta file or directory of fasta files. =cut sub fasta { my ($self, $fasta_path) = @_; if ($fasta_path) { # $fasta_path ||= $self->config('default_fasta_path'); $self->info('fasta_database_loading_indexing', "Loading (and possibly indexing) $fasta_path"); my $fasta = Bio::DB::Fasta->new($fasta_path); $self->{fasta} = $fasta; } if (! $self->{fasta}) { $self->throw('missing_fasta_datasource', 'Your code has requested ' . 'access to fasta sequence data, but no fasta ' . 'file has been provided'); } return $self->{fasta}; } #----------------------------------------------------------------------------- =head2 class Title : class Usage : $class = $self->class($subclass_name); Function: Reblesses an object into the appropriate subclass. Returns : A object blessed into the given subclass Args : A class name of a subclass of the calling object. =cut sub class { my ($self, $subclass) = @_; my $class = ref($self); $subclass =~ s/\.pm$//; $subclass =~ s/$class//; $subclass = $class . "::$subclass"; $self->load_module($subclass); bless $self, $subclass; return $self; } #----------------------------------------------------------------------------- #------------------------------------ Methods -------------------------------- #----------------------------------------------------------------------------- =head1 METHODS =head2 verbosity Title : verbosity Usage : $base->verbosity($level); Function: Set the level of verbosity written to STDERR by the code. Returns : None Args : Arguments can be either the words debug, info, unique, warn, fatal or their numerical equivalents as given below. debug | 1: Print all FATAL, WARN, INFO, and DEBUG messages. Produces a lot of output. info | 2: Print all FATAL, WARN, and INFO messages. This is the default. unique | 3: Print only the first occurence of each error/info code. warn | 4: Don't print INFO messages. fatal | 5: Don't print INFO or WARN messages. Still dies with message on FATAL errors. =cut sub verbosity { my ($self, $verbosity) = @_; if ($verbosity) { $verbosity = lc $verbosity; $verbosity = ($verbosity =~ /^d/ ? 1 : $verbosity =~ /^i/ ? 2 : $verbosity =~ /^u/ ? 3 : $verbosity =~ /^w/ ? 4 : $verbosity =~ /^f/ ? 5 : $verbosity); if (! grep {$verbosity eq $_} qw(1 2 3 4 5)) { $self->warn('invalid_verbosity_level', "$verbosity - setting verbosity level to info"); $verbosity = 2; } $self->{verbosity} = $verbosity; } $self->{verbosity} ||= '2'; return $self->{verbosity}; } #----------------------------------------------------------------------------- =head2 handle_message Title : handle_message Usage : $base->handle_message($level, $code, $message); Function: Handle a message and print to STDERR accordingly. Returns : None Args : level : FATAL, WARN, INFO, DEBUG code : $info_code # single_word_code_for_info message: $info_msg # Free text description of info Note that the 'code' above should not contain whitespace, should generally by lowercase unless uppercase is needed for clarity, and should be standardized throughout the library such that a code like 'file_not_found' is used consistently rather than 'file_not_found' in one place and 'file_does_not_exist' in another. All codes should be documented in the module and in Manual.pm The 'message' above can be arbitrary text and should provide details that will help explain this instance of the error, such as "Expected an integer but got the text 'ABCDEFG' instead". =cut sub handle_message { my ($self, $level, $code, $message) = @_; my $caller = ref($self); $level ||= 'UNKNOWN'; $message ||= $caller; if (! $code) { $code = 'unspecified_code'; $message = join '', ("GAL::Base is handling a message " . "for $caller without an error code. " . "Complain to the author of $caller!"); } chomp $message; $message .= "\n"; my $verbosity = $self->verbosity; if ($level eq 'FATAL') { $message = join ' : ', ('FATAL', $code, $message); croak $message; } elsif ($level eq 'WARN') { return if ($verbosity > 4); return if ($verbosity == 3 && $self->{unique_codes}{$code}++); $message = join ' : ', ('WARN', $code, $message); print STDERR $message; } elsif ($level eq 'INFO') { return if ($verbosity > 3); return if ($verbosity == 3 && $self->{unique_codes}{$code}++); $message = join ' : ', ('INFO', $code, $message); print STDERR $message; } elsif ($level eq 'DEBUG') { return if ($verbosity != 1); my $sub = (caller(4))[3]; #my $sub = $data[3]; $message = join ' : ', ('DEBUG', $code, "($caller\:\:$sub) $message"); print STDERR $message; print ''; } else { $message = join '', ("GAL::Base is handling a message " . "for $caller without an error level. " . "Complain to the author of $caller!\n"); chomp $message; $message = join ' : ', ('UNKNOWN', $code, $message); croak $message; } } #----------------------------------------------------------------------------- =head2 throw Title : throw Usage : $base->throw($error_code, $error_message); Function: Throw an error - print an error message to STDERR and die. Returns : None Args : A text string for the error code and a text string for the error message. See the documentation for the method handle_message in this module for more details. =cut sub throw { shift->handle_message('FATAL', @_); } #----------------------------------------------------------------------------- =head2 warn Title : warn Usage : $base->warn($warning_code, $warning_message); Function: Send a warning message to STDERR. Returns : None Args : A text string for the error code and a text string for the error message. See the documentation for the method handle_message in this module for more details. =cut sub warn { shift->handle_message('WARN', @_); } #----------------------------------------------------------------------------- =head2 info Title : info Usage : $base->info($info_code, $info_message); Function: Send a INFO message. Returns : None Args : A text string for the info code and a text string for the info message. See the documentation for the method handle_message in this module for more details. =cut sub info { shift->handle_message('INFO', @_); } #----------------------------------------------------------------------------- =head2 debug Title : debug Usage : $base->debug($debug_code, $debug_message); Function: Send a DEBUG message. Returns : None Args : A text string for the debug code and a text string for the debug message. See the documentation for the method handle_message in this module for more details. =cut sub debug { shift->handle_message('DEBUG', @_); } #----------------------------------------------------------------------------- =head2 wrap_text Title : wrap_text Usage : $text = $self->wrap_text($text, 50); Function: Wrap text to the specified column width. Default width is 50 characters. Returns : Returns wrapped text as a string. Args : A string of text and an optional integer value for the wrapped width. =cut sub wrap_text { my ($self, $text, $cols) = @_; $cols ||= 50; $text =~ s/(.{0,$cols})/$1\n/g; $text =~ s/\n+$//; return $text; } #----------------------------------------------------------------------------- =head2 trim_whitespace Title : trim_whitespace Usage : $trimmed_text = $self->trim_whitespace($text); Function: Trim leading and trailing whitespace from text; Returns : Returns trimmed text as a string. Args : A text string. =cut sub trim_whitespace { my ($self, $text) = @_; $text =~ s/^\s+//; $text =~ s/\s+$//; return $text; } #----------------------------------------------------------------------------- =head2 prepare_args Title : prepare_args Usage : $args = $self->prepare_args(@_); Function: Take a list of key value pairs that may be structured as an array, a hash or and array or hash reference and return them as a hash or hash reference depending on calling context. Returns : Hash or hash reference. Args : An array, hash or reference to either. =cut sub prepare_args { my ($self, @args) = @_; my %args_hash; if (! $args[0]) { # If no args are passed, don't do anything just return an empty # hash(ref). } elsif (scalar @args == 1 && ref $args[0] eq 'ARRAY') { %args_hash = @{$args[0]}; } elsif (scalar @args == 1 && ref $args[0] eq 'HASH') { %args_hash = %{$args[0]}; } elsif (scalar @args % 2 == 0) { %args_hash = @args; } else { my $class = ref($self); my $err_code = 'invalid_arguments_to_prepare_args'; my $err_msg = ("Bad arguments passed to $class. A list " . "of key value pairs or a reference to " . "such a list was expected, But we got:\n" . join ' ', @args); $self->throw($err_code, $err_msg); } return wantarray ? %args_hash : \%args_hash; } #----------------------------------------------------------------------------- =head2 set_attributes Title : set_attributes Usage : $base->set_attributes($args, @valid_attributes); Function: Take a hash reference of arguments and a list (or reference) of valid attribute names and call the methods to set those attribute values. Returns : None Args : A hash reference of arguments and an array or array reference of valid attributes names. =cut sub set_attributes { my $self = shift; my $args = shift; # Allow @valid_attributes to be passed as array or arrayref. my @valid_attributes = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_; my $package = __PACKAGE__; my $caller = ref($self); $args = $self->prepare_args($args); for my $attribute (@valid_attributes) { next unless exists $args->{$attribute}; if (exists $self->{$attribute}) { my $package = __PACKAGE__; my $caller = ref($self); my $warning_message = ("$package is about to reset the value of $attribute " . "on behalf of a $caller object. This may be " . "a bad idea."); $self->warn('resetting_attribute_values', $warning_message); } $self->$attribute($args->{$attribute}); delete $args->{$attribute}; } } #----------------------------------------------------------------------------- =head2 expand_iupac_nt_codes Title : expand_iupac_nt_codes Usage : @nucleotides = $self->expand_iupac_nt_codes('W'); Function: Expands an IUPAC ambiguity codes to an array of nucleotides Returns : An array or array ref of nucleotides (ATGC-); Args : An IUPAC Nucleotide ambiguity code (ACGTUMRWSYKVHDBNX-) or an array (or ref) of such. =cut sub expand_iupac_nt_codes { my ($self, @codes) = @_; my %iupac_code_map = ('A' => ['A'], 'C' => ['C'], 'G' => ['G'], 'T' => ['T'], 'U' => ['T'], 'M' => ['A', 'C'], 'R' => ['A', 'G'], 'W' => ['A', 'T'], 'S' => ['C', 'G'], 'Y' => ['C', 'T'], 'K' => ['G', 'T'], 'V' => ['A', 'C', 'G'], 'H' => ['A', 'C', 'T'], 'D' => ['A', 'G', 'T'], 'B' => ['C', 'G', 'T'], 'N' => ['A', 'C', 'G', 'T'], 'X' => ['A', 'C', 'G', 'T'], '-' => ['-'], ); my @nts; for my $code (@codes) { my $nts = $iupac_code_map{$code}; $self->throw('invalid_ipuac_nucleotide_code', $code) unless $nts; push @nts, @{$nts}; } return wantarray ? @nts : \@nts; } #----------------------------------------------------------------------------- =head2 load_module Title : load_module Usage : $base->load_module(Some::Module); Function: Do runtime loading (require) of a module/class. Returns : 1 on success - throws exception on failure Args : A valid module name. =cut sub load_module { my ($self, $module_name) = @_; eval "require $module_name"; if ($@) { my $self_class = ref $self; my $err_code = 'failed_to_load_module'; my $err_msg = "$module_name in $self_class\n$@"; $self->throw($err_code, $err_msg); } return 1; } #----------------------------------------------------------------------------- =head2 revcomp Title : revcomp Usage : $base->revcomp($sequence); Function: Get the reverse compliment of a nucleotide sequence Returns : The reverse complimented sequence Args : A nucleotide sequence (ACGTRYMKSWHBVDNX). Input sequence is case insensitive and case is maintained. =cut sub revcomp { my ($self, $sequence) = @_; my $revcomp_seq = reverse $sequence; $revcomp_seq =~ tr/acgtrymkswhbvdnxACGTRYMKSWHBVDNX/tgcayrkmswdvbhnxTGCAYRKMSWDVBHNX/; return $revcomp_seq; } #----------------------------------------------------------------------------- =head2 get_feature_bins Title : get_feature_bins Usage : $base->get_feature_bins($feature); Function: Get the genome bins for a given range. GAL uses a feature binning scheme to speed range queries to a database. This binning scheme is similar to (but not identical to) the scheme described in the UCSC Genome Browser publication (http://www.ncbi.nlm.nih.gov/pubmed/12045153) and on the UCSC Genome Browser wiki (http://genomewiki.ucsc.edu/index.php/Bin_indexing_system). Breifly, for a given genomic range this method will calculate the bins on the genome of sizes 512 MB, 64 MB, 8 MB, 1 MB, and 128 KB that completely contains the feature. These bins are returned as a list sorted smallest bin to largest so that the first value returned is the smallest bin that completely contains the feature. Returns : An array of bins that the given range is compeltely contained within sorted smallest bin to largest so that the first value return is smallest possible bin in which the feature is fully contained. Args : A hash reference with key values seqid, start, end (i.e. a feature hash) or an object with methods seqid, start, end. =cut sub get_feature_bins { my ($self, $feature) = @_; my ($seqid, $start, $end); if (ref $feature eq 'HASH') { ($seqid, $start, $end) = @{$feature}{qw(seqid start end)}; } elsif (blessed $feature && $feature->can('seqid') && $feature->can('start') && $feature->can('end')) { ($seqid, $start, $end) = ($feature->seqid, $feature->start, $feature->end) } else { my $data = ref $feature || $feature; $self->throw('invalid_arguments_to_get_feature_bins', $data); } my @feature_bins; my $count; my $single_bin; for my $bin_size (128_000, 1_000_000, 8_000_000, 64_000_000, 512_000_000) { $count++; my $start_bin = int($start/$bin_size); my $end_bin = int($end/$bin_size); my @these_bins = map {$_ = join ':', ($seqid, $count, $_)} ($start_bin .. $end_bin); if (! $single_bin && scalar @these_bins == 1) { $single_bin = shift @these_bins; } unshift @feature_bins, @these_bins; } unshift @feature_bins, $single_bin; return wantarray ? @feature_bins : \@feature_bins; } #----------------------------------------------------------------------------- =head2 translate Title : translate Usage : $base->translate($sequence, $offset, $length); Function: Translate a nucleotide sequence to an amino acid sequence Returns : An amino acid sequence Args : The sequence as a scalar, an integer offset from which to begin translation (default 0), and an integer length to translate (default is full length of input sequence). =cut sub translate { my ($self, $sequence, $offset, $length) = @_; my $genetic_code = $self->genetic_code; $offset ||= 0; $sequence =~ s/\s+|\d+//g; $length ||= length($sequence); my $polypeptide; for (my $i = (0 + $offset); $i < $length; $i += 3) { my $codon = uc substr($sequence, $i, 3); my $aa = $genetic_code->{$codon}; $polypeptide .= $aa; } return $polypeptide; } #----------------------------------------------------------------------------- =head2 genetic_code Title : genetic_code Usage : $base->genetic_code; Function: Returns a hash reference of the genetic code. Currently only supports the standard genetic code without ambiguity codes. Returns : A hash reference of the genetic code Args : None =cut sub genetic_code { my $self = shift; #TODO: Need to add ambiguity codes to codons. return {AAA => 'K', AAC => 'N', AAG => 'K', AAT => 'N', ACA => 'T', ACC => 'T', ACG => 'T', ACT => 'T', AGA => 'R', AGC => 'S', AGG => 'R', AGT => 'S', ATA => 'I', ATC => 'I', ATG => 'M', ATT => 'I', CAA => 'Q', CAC => 'H', CAG => 'Q', CAT => 'H', CCA => 'P', CCC => 'P', CCG => 'P', CCT => 'P', CGA => 'R', CGC => 'R', CGG => 'R', CGT => 'R', CTA => 'L', CTC => 'L', CTG => 'L', CTT => 'L', GAA => 'E', GAC => 'D', GAG => 'E', GAT => 'D', GCA => 'A', GCC => 'A', GCG => 'A', GCT => 'A', GGA => 'G', GGC => 'G', GGG => 'G', GGT => 'G', GTA => 'V', GTC => 'V', GTG => 'V', GTT => 'V', TAA => '*', TAC => 'Y', TAG => '*', TAT => 'Y', TCA => 'S', TCC => 'S', TCG => 'S', TCT => 'S', TGA => '*', TGC => 'C', TGG => 'W', TGT => 'C', TTA => 'L', TTC => 'F', TTG => 'L', TTT => 'F', }; } #----------------------------------------------------------------------------- =head2 amino_acid_data Title : amino_acid_data Usage : $base->amino_acid_data($aa, $value); Function: Returns data about an amino acid - either a specific value or a hash reference of all data for that amino acid. Returns : A string representing a data point about an given amino acid or a hash reference with all data points about the given amino acid. Args : 1) An amino acid in either: a) single-letter code b) three-letter 2) Optionally a code for the value to return. Any of: a) name : The full name of the amino acid. b) one_letter : The one-letter code for the amino acid. c) three_letter : The three-letter code for the amino acid. d) polarity : The polarity of the amino acid. e) charge : The charge of the amino acid's side chain (at pH 7.4). f) hydropathy : The hydropathy index of the amino acid. g) weight : The molecular weight of the amino acid in g/mol. h) size : Returns small or large. i) h_bond : return 1 or 0 indicating if the amino acid can form hydrogen bonds j) aromaticity : Returns aromatic, aliphatic or undef. =cut sub amino_acid_data { my ($self, $aa, $datum) = @_; my %aa321 = (Ala => 'A', Arg => 'R', Asn => 'N', Asp => 'D', Cys => 'C', Glu => 'E', Gln => 'Q', Gly => 'G', His => 'H', Ile => 'I', Leu => 'L', Lys => 'K', Met => 'M', Phe => 'F', Pro => 'P', Ser => 'S', Thr => 'T', Trp => 'W', Tyr => 'Y', Val => 'V', Sec => 'U', Pyl => 'O', ); if (length($aa) == 3) { $aa = $aa321{$aa} } my %aa_data = (A => {name => 'Alanine', one_letter => 'A', three_letter => 'Ala', polarity => 'nonpolar', charge => 'neutral', hydropathy => 1.8, weight => 71.09, size => 'small', h_bond => 0, aromaticity => 'aliphatic', }, R => {name => 'Arginine', one_letter => 'R', three_letter => 'Arg', polarity => 'polar', charge => 'positive', hydropathy => -4.5, weight => 156.19, size => 'large', h_bond => 1, aromaticity => undef, }, N => {name => 'Asparagine', one_letter => 'N', three_letter => 'Asn', polarity => 'polar', charge => 'neutral', hydropathy => -3.5, weight => 114.11, size => 'small', h_bond => 1, aromaticity => undef, }, D => {name => 'Aspartic acid', one_letter => 'D', three_letter => 'Asp', polarity => 'polar', charge => 'negative', hydropathy => -3.5, weight => 115.09, size => 'small', h_bond => 1, aromaticity => undef, }, C => {name => 'Cysteine', one_letter => 'C', three_letter => 'Cys', polarity => 'polar', charge => 'neutral', hydropathy => 2.5, weight => 103.15, size => 'small', h_bond => 1, aromaticity => undef, }, E => {name => 'Glutamic acid', one_letter => 'E', three_letter => 'Glu', polarity => 'polar', charge => 'negative', hydropath => -3.5, weight => 129.12, size => 'large', h_bond => 1, aromaticity => undef, }, Q => {name => 'Glutamine', one_letter => 'Q', three_letter => 'Gln', polarity => 'polar', charge => 'neutral', hydropathy => -3.5, weight => 128.14, size => 'large', h_bond => 1, aromaticity => undef, }, G => {name => 'Glycine', one_letter => 'G', three_letter => 'Gly', polarity => 'nonpolar', charge => 'neutral', hydropathy => -0.4, weight => 57.05, size => 'small', h_bond => 0, aromaticity => 'aliphatic', }, H => {name => 'Histidine', one_letter => 'H', three_letter => 'His', polarity => 'polar', charge => 'positive', hydropathy => -3.2, weight => 137.14, size => 'large', h_bond => 1, aromaticity => 'aromatic', }, I => {name => 'Isoleucine', one_letter => 'I', three_letter => 'Ile', polarity => 'nonpolar', charge => 'neutral', hydropathy => 4.5, weight => 113.16, size => 'large', h_bond => 0, aromaticity => 'aliphatic', }, L => {name => 'Leucine', one_letter => 'L', three_letter => 'Leu', polarity => 'nonpolar', charge => 'neutral', hydropathy => 3.8, weight => 113.16, size => 'large', h_bond => 0, aromaticity => 'aliphatic', }, K => {name => 'Lysine', one_letter => 'K', three_letter => 'Lys', polarity => 'polar', charge => 'positive', hydropathy => -3.9, weight => 128.17, size => 'large', h_bond => 1, aromaticity => undef, }, M => {name => 'Methionine', one_letter => 'M', three_letter => 'Met', polarity => 'nonpolar', charge => 'neutral', hydropathy => 1.9, weight => 131.19, size => 'large', h_bond => 0, aromaticity => undef, }, F => {name => 'Phenylalanine', one_letter => 'F', three_letter => 'Phe', polarity => 'nonpolar', charge => 'neutral', hydropathy => 2.8, weight => 147.18, size => 'large', h_bond => 0, aromaticity => 'aromatic', }, P => {name => 'Proline', one_letter => 'P', three_letter => 'Pro', polarity => 'nonpolar', charge => 'neutral', hydropathy => -1.6, weight => 97.12, size => 'small', h_bond => 0, aromaticity => 'aliphatic', }, S => {name => 'Serine', one_letter => 'S', three_letter => 'Ser', polarity => 'polar', charge => 'neutral', hydropathy => -0.8, weight => 87.08, size => 'small', h_bond => 1, aromaticity => undef, }, T => {name => 'Threonine', one_letter => 'T', three_letter => 'Thr', polarity => 'polar', charge => 'neutral', hydropathy => -0.7, size => 'small', h_bond => 1, aromaticity => undef, }, W => {name => 'Tryptophan', one_letter => 'W', three_letter => 'Trp', polarity => 'nonpolar', charge => 'neutral', hydropathy => -0.9, weight => 186.21, size => 'large', h_bond => 1, aromaticity => 'aromatic', }, Y => {name => 'Tyrosine', one_letter => 'Y', three_letter => 'Tyr', polarity => 'polar', charge => 'neutral', hydropathy => -1.3, weight => 163.18, size => 'large', h_bond => 1, aromaticity => 'aromatic', }, V => {name => 'Valine', one_letter => 'V', three_letter => 'Val', polarity => 'nonpolar', charge => 'neutral', hydropathy => 4.2, weight => 99.14, size => 'small', h_bond => 0, aromaticity => 'aliphatic', }, U => {name => 'Selenocysteine', one_letter => 'U', three_letter => 'Sec', polarity => undef, charge => undef, hydropathy => undef, weight => undef, size => undef, h_bond => undef, aromaticity => undef, }, O => {name => 'Pyrrolysine', one_letter => 'O', three_letter => 'Pyl', polarity => undef, charge => undef, hydropathy => undef, weight => undef, size => undef, h_bond => undef, aromaticity => undef, } ); if (defined $datum) { if (exists $aa_data{$aa}{$datum}) { return $aa_data{$aa}{$datum}; } else { $self->throw('invalid_aa_datum_code', "$datum passed to GAL::Base::amino_acid_data"); } } else { return $aa_data{$aa}; } } #----------------------------------------------------------------------------- =head2 time_stamp Title : time_stamp Usage : $base->time_stamp; Function: Returns a YYYYMMDD time_stamp Returns : A YYYYMMDD time_stamp Args : None =cut sub time_stamp { my $self = shift; my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst) = localtime(time); my $time_stamp = sprintf("%02d%02d%02d", $year + 1900, $mon + 1, $mday); return $time_stamp; } #----------------------------------------------------------------------------- =head2 random_string Title : random_string Usage : $base->random_string(8); Function: Returns a random alphanumeric string Returns : A random alphanumeric string of a given length. Default length is 8 charachters. Args : The length of the string to be returned [8] =cut sub random_string { my ($self, $length) = @_; $length ||= 8; my $random_string = join "", map { unpack "H*", chr(rand(256)) } (1 .. $length); return substr($random_string, 0, $length); } #----------------------------------------------------------------------------- =head2 float_lt Title : float_lt Usage : $base->float_lt(0.0000123, 0.0000124, 7); Function: Return true if the first number given is less than (<) the second number at a given level of accuracy. Default accuracy length is 6 decimal places. Returns : 1 if the first number is less than the second, otherwise 0. Args : The two values to compare and optionally a integer value for the accuracy. Accuracy defaults to 6 decimal places. =cut sub float_lt { my ($self, $A, $B, $accuracy) = @_; $accuracy ||= 6; $A = sprintf("%.${accuracy}f", $A); $B = sprintf("%.${accuracy}f", $B); $A =~ s/\.//; $B =~ s/\.//; return $A < $B; } #----------------------------------------------------------------------------- =head2 float_le Title : float_le Usage : $base->float_le(0.0000123, 0.0000124, 7); Function: Return true if the first number given is less than or equal to (<=) the second number at a given level of accuracy. Default accuracy length is 6 decimal places. Returns : 1 if the first number is less than or equal to the second, otherwise 0. Args : The two values to compare and optionally a integer value for the accuracy. Accuracy defaults to 6 decimal places. =cut sub float_le { my ($self, $A, $B, $accuracy) = @_; $accuracy ||= 6; $A = sprintf("%.${accuracy}f", $A); $B = sprintf("%.${accuracy}f", $B); $A =~ s/\.//; $B =~ s/\.//; return $A <= $B; } #----------------------------------------------------------------------------- =head2 float_gt Title : float_gt Usage : $base->float_gt(0.0000123, 0.0000124, 7); Function: Return true if the first number given is greater than (>) the second number at a given level of accuracy. Default accuracy length is 6 decimal places. Returns : 1 if the first number is greater than the second, otherwise 0 Args : The two values to compare and optionally a integer value for the accuracy. Accuracy defaults to 6 decimal places. =cut sub float_gt { my ($self, $A, $B, $accuracy) = @_; $accuracy ||= 6; $A = sprintf("%.${accuracy}f", $A); $B = sprintf("%.${accuracy}f", $B); $A =~ s/\.//; $B =~ s/\.//; return $A > $B; } #----------------------------------------------------------------------------- =head2 float_ge Title : float_ge Usage : $base->float_ge(0.0000123, 0.0000124, 7); Function: Return true if the first number given is greater than or equal to (>=) the second number at a given level of accuracy. Default accuracy length is 6 decimal places. Returns : 1 if the first number is greater than or equal to the second, otherwise 0. Args : The two values to compare and optionally a integer value for the accuracy. Accuracy defaults to 6 decimal places. =cut sub float_ge { my ($self, $A, $B, $accuracy) = @_; $accuracy ||= 6; $A = sprintf("%.${accuracy}f", $A); $B = sprintf("%.${accuracy}f", $B); $A =~ s/\.//; $B =~ s/\.//; return $A >= $B; } #----------------------------------------------------------------------------- =head2 open_file Title : open_file Usage : $base->open_file($file); Function: Open a given file for reading and return a filehandle. Returns : A filehandle Args : A file path/name =cut sub open_file { my ($self, $file) = @_; if (! defined $file) { $self->throw('file_does_not_exist', $file); } if (! -e $file) { $self->throw('file_does_not_exist', $file); } if (! -r $file) { $self->throw('cant_read_file', $file); } open(my $FH, '<', $file) || $self->throw('cant_open_file_for_reading', $file); return $FH; } #----------------------------------------------------------------------------- ############################################################################## ## Consolidate three copies of this method 1) Here 2) Feature/gene.pm and ## 3) Base.pm ############################################################################## =head2 get_transcript_types Title : get_transcript_types Usage : $transcript_types = $self->get_transcript_types Function: Get a list of all features that are types of transcripts. Returns : An array or ref of feature names for transcript and it's children. Args : None =cut sub get_transcript_types { my $self = shift; my @transcripts = qw(EST RNase_MRP_RNA RNase_P_RNA SRP_RNA SRP_RNA_primary_transcript Y_RNA aberrant_processed_transcript alternatively_spliced_transcript antisense_RNA antisense_primary_transcript capped_mRNA capped_primary_transcript class_II_RNA class_I_RNA consensus_mRNA dicistronic_mRNA dicistronic_primary_transcript dicistronic_transcript edited_mRNA edited_transcript edited_transcript_by_A_to_I_substitution enhancerRNA enzymatic_RNA exemplar_mRNA guide_RNA lnc_RNA mRNA mRNA_recoded_by_codon_redefinition mRNA_recoded_by_translational_bypass mRNA_region mRNA_with_frameshift mRNA_with_minus_1_frameshift mRNA_with_minus_2_frameshift mRNA_with_plus_1_frameshift mRNA_with_plus_2_frameshift mature_transcript mature_transcript_region miRNA_primary_transcript mini_exon_donor_RNA monocistronic_mRNA monocistronic_primary_transcript monocistronic_transcript ncRNA nc_primary_transcript piRNA polyadenylated_mRNA polycistronic_mRNA polycistronic_primary_transcript polycistronic_transcript pre_edited_mRNA primary_transcript primary_transcript_region processed_transcript protein_coding_primary_transcript pseudogenic_transcript rRNA rRNA_cleavage_RNA rRNA_primary_transcript rasiRNA recoded_mRNA regional_centromere_outer_repeat_transcript riboswitch ribozyme scRNA scRNA_primary_transcript siRNA small_regulatory_ncRNA snRNA snRNA_primary_transcript snoRNA snoRNA_primary_transcript spliced_leader_RNA stRNA tRNA tRNA_primary_transcript tasiRNA tasiRNA_primary_transcript telomerase_RNA tmRNA_primary_transcript trans_spliced_mRNA trans_spliced_transcript transcript transcript_bound_by_nucleic_acid transcript_bound_by_protein transcript_region transcript_with_translational_frameshift vault_RNA ); return wantarray ? @transcripts : \@transcripts; } #----------------------------------------------------------------------------- #=head2 validate_feature # # Title : validate_feature # Usage : $self->validate_feature($feature_hash) # Function: Validates a feature hash. # Returns : NA # Args : A feature hash reference in the form returned by next_feature_hash # #=cut # #sub validate_feature { # my ($self, $feature) = @_; # # my ($feature_id, $seqid, $source, $type, $start, $end, $score, # $strand, $phase, $attributes) = # @{$feature}{qw(feature_id seqid source type start end # score strand phase attributes)}; # # my $feature_text = $self->to_gff3($feature); # # # Validate seqid # unless ($self->is_valid_seqid) { # my $error_code = 'invalid_characters_in_seqid_column'; # $self->throw($error_code, "($seqid) $feature_text"); # } # # Validate source - No validation # # Validate type # unless ($self->is_valid_sequence_feature($type)) { # my $error_code = 'invalid_type_value'; # $self->warn($error_code, "($type) $feature_text"); # } # # Validate start # unless ($self->is_integer($start)) { # my $error_code = 'invalid_start_value'; # $self->throw($error_code, "($start) $feature_text"); # } # # Validate end # unless ($self->is_integer($end)) { # my $error_code = 'invalid_end_value'; # $self->throw($error_code, "($end) $feature_text"); # } # # Validate end > start # unless ($start <= $end) { # my $error_code = 'invalid_start_gt_end_value'; # $self->throw($error_code, "($start > $end) $feature_text"); # } # # Validate score # unless ($self->is_real_number($score)) { # my $error_code = 'invalid_score_value'; # $self->warn($error_code, "($score) $feature_text"); # } # # Validate strand # unless ($strand =~ /^[.+-]/) { # my $error_code = 'invalid_strand_value'; # $self->throw($error_code, "($strand) $feature_text"); # } # # Validate phase # unless ($phase =~ /^[012.]/) { # my $error_code = 'invalid_phase_value'; # $self->warn($error_code, "($phase) $feature_text"); # } # # Validate attributes # $self->validate_attributes($attributes); # # # feature_id # $feature->{feature_id} ||= $feature->{attributes}{ID}[0]; # if ($feature->{feature_id} ne $feature->{attributes}{ID}[0]) { # my $fid = $feature->{feature_id}; # my $aid = $feature->{attributes}{ID}[0]; # my $error_code = 'feature_id_ne_attribute_ID'; # $self->throw($error_code, "($fid ne $aid) $feature_text"); # } #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_gff3_attribute_key # # Title : is_valid_gff3_attribute_key # Usage : $self->is_valid_gff3_attribute_key($key) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : An attribute key # #=cut # #sub validate_attributes { # # $self->{valid_gff3_attributes_keys} ||= {}; # # return 1 if exists # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_gvf_attribute_key # # Title : is_valid_gvf_attribute_key # Usage : $self->is_valid_gvf_attribute_key($key) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : An attribute key # #=cut # #sub validate_attributes { # # #} # ##----------------------------------------------------------------------------- # #=head2 validate_attributes # # Title : validate_attributes # Usage : $self->validate_attributes($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub validate_attributes { # # my $attributes = shift; # # if (! defined $attributes) { # my $error_code = 'missing_attributes'; # $self->warn($error_code, $feature_text); # } # elsif (ref $attributes ne 'HASH') { # my $error_code = 'attributes_must_be_hash'; # $self->warn($error_code, $feature_text); # } # else { # for my $key (keys %{$attributes}) { # unless ($self->is_valid_gff3_attribute_key($key) || # $self->is_valid_gvf_attribute_key($key)) { # my $error_code = 'invalid_attribute_key'; # $self->throw($error_code, "($key) $feature_text"); # } # unless (defined $attributes->{$key}) { # my $error_code = 'missing_attribute_value'; # $self->throw($error_code, "($key) $feature_text"); # } # unless (ref $attributes->{$key} eq 'ARRAY') { # my $error_code = 'attribute_value_must_be_array'; # $self->throw($error_code, "($key) $feature_text"); # } # my @values = @{$attributes->{$key}}; # # Validate GFF3 Attributes # # ID # if ($key eq 'ID') { # if (scalar @values > 1) { # my $error_code = 'invalid_ID_attribute_multiple_values'; # my $all_ids = join ' ', @values; # $self->throw($error_code, "($all_ids) $feature_text"); # } # } # # Name # elsif ($key eq 'Name') { # # No validation on Name values # } # # Alias # elsif ($key eq 'Alias') { # # No validation on Alias values # } # # Parent # elsif ($key eq 'Parent') { # # No validation on Alias values # } # # Target # elsif ($key eq 'Target') { # } # # Gap # elsif ($key eq 'Gap') { # } # # Derives_from # elsif ($key eq 'Derives_from') { # } # # Note # elsif ($key eq 'Note') { # } # # Dbxref # elsif ($key eq 'Dbxref') { # } # # Ontology_term # elsif ($key eq 'Ontology_term') { # # TODO: Validate Ontology_term # } # # Is_circular # elsif ($key eq 'Is_circular') { # } # # Validate GVF attributes # # Variant_seq # elsif ($key eq 'Variant_seq') { # } # # Reference_seq # elsif ($key eq 'Reference_seq') { # } # # Variant_reads # elsif ($key eq 'Variant_reads') { # } # # Total_reads # elsif ($key eq 'Total_reads') { # } # # Zygosity # elsif ($key eq 'Zygosity') { # } # # Variant_freq # elsif ($key eq 'Variant_freq') { # } # # Variant_effect # elsif ($key eq 'Variant_effect') { # } # # Start_range # elsif ($key eq 'Start_range') { # } # # End_range # elsif ($key eq 'End_range') { # } # # Phased # elsif ($key eq 'Phased') { # } # # Genotype # elsif ($key eq 'Genotype') { # } # # Individual # elsif ($key eq 'Individual') { # } # # Variant_copy_number # elsif ($key eq 'Variant_copy_number') { # } # # Reference_copy_number # elsif ($key eq 'Reference_copy_number') { # } # # Variant_codon # elsif ($key eq 'Variant_codon') { # } # # Reference_codon # elsif ($key eq 'Reference_codon') { # } # # Variant_aa # elsif ($key eq 'Variant_aa') { # } # # Reference_aa # elsif ($key eq 'Reference_aa') { # } # # Breakpoint_detail # elsif ($key eq 'Breakpoint_detail') { # } # # Sequence_context # elsif ($key eq 'Sequence_context') { # } # # All others # else { # if ($key =~ /^[A-Z]/) { # my $error_code = 'non_standard_attribute_must_begin_with_lowercase'; # $self->throw($error_code, "($key) $feature_text"); # } # } # } # ##----------------------------------------------------------------------------- # #=head2 is_integer # # Title : is_integer # Usage : $self->is_integer($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_integer { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_real_number # # Title : is_real_number # Usage : $self->is_real_number($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_real_number { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_aa_sequence # # Title : is_valid_aa_sequence # Usage : $self->is_valid_aa_sequence($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_aa_sequence { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_iupac_nt # # Title : is_valid_iupac_nt # Usage : $self->is_valid_iupac_nt($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_iupac_nt { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_seqid # # Title : is_valid_seqid # Usage : $self->is_valid_seqid($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_seqid { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_type # # Title : is_valid_type # Usage : $self->is_valid_type($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_type { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_start # # Title : is_valid_start # Usage : $self->is_valid_start($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_start { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_end # # Title : is_valid_end # Usage : $self->is_valid_end($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_end { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_strand # # Title : is_valid_strand # Usage : $self->is_valid_strand($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_strand { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_phase # # Title : is_valid_phase # Usage : $self->is_valid_phase($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_phase { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_id_attribute # # Title : is_valid_id_attribute # Usage : $self->is_valid_id_attribute($feature_hash) # Function: Validates a id_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_id_attribute { # # my $value = shift; ##----------------------------------------------------------------------------- # #=head2 is_valid # # Title : is_valid # Usage : $self->is_valid($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid { # # my $values = shift; # if (scalar @{$values} > 1) { # my $error_code = 'invalid_ID_attribute_multiple_values'; # my $all_ids = join ' ', @values; # $self->throw($error_code, "($all_ids) $feature_text"); # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_name_attribute # # Title : is_valid_name_attribute # Usage : $self->is_valid_name_attribute($feature_hash) # Function: Validates a name_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_name_attribute { # # my $values = shift; # # No validation of Name attribute # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_alias_attribute # # Title : is_valid_alias_attribute # Usage : $self->is_valid_alias_attribute($feature_hash) # Function: Validates a alias_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_alias_attribute { # # my $values = shift; # # No validation of Alias attribute # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_parent_attribute # # Title : is_valid_parent_attribute # Usage : $self->is_valid_parent_attribute($feature_hash) # Function: Validates a parent_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_parent_attribute { # # my $values = shift; # # No validation of Parent attribute # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_target_attribute # # Title : is_valid_target_attribute # Usage : $self->is_valid_target_attribute($feature_hash) # Function: Validates a target_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_target_attribute { # # my $values = shift; # # if (scalar @{$values} > 1) { # my $error_code = 'invalid_Target_attribute_multiple_values'; # my $all_values = join ' ', @{$values}; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values->[0]; # if ($value !~ /\S+\s+\d+\s+\d+\s*[\-+]*/) { # my $error_code = 'invalid_Target_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_gap_attribute # # Title : is_valid_gap_attribute # Usage : $self->is_valid_gap_attribute($feature_hash) # Function: Validates a gap_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_gap_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Gap_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # # TODO: Validate the CIGAR format # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_derives_from_attribute # # Title : is_valid_derives_from_attribute # Usage : $self->is_valid_derives_from_attribute($feature_hash) # Function: Validates a derives_from_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_derives_from_attribute { # # my $values = shift; # # if (scalar @values > 1) { # my $error_code = 'invalid_Derives_from_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # # TODO: Validate the Derives_from relationships # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_note_attribute # # Title : is_valid_note_attribute # Usage : $self->is_valid_note_attribute($feature_hash) # Function: Validates a note_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_note_attribute { # # my $values = shift; # # No validation of Note attribute # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_dbxref_attribute # # Title : is_valid_dbxref_attribute # Usage : $self->is_valid_dbxref_attribute($feature_hash) # Function: Validates a dbxref_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_dbxref_attribute { # # my $values = shift; # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_ontology_term_attribute # # Title : is_valid_ontology_term_attribute # Usage : $self->is_valid_ontology_term_attribute($feature_hash) # Function: Validates a ontology_term_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_ontology_term_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Is_circular_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_is_circular_attribute # # Title : is_valid_is_circular_attribute # Usage : $self->is_valid_is_circular_attribute($feature_hash) # Function: Validates a is_circular_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_is_circular_attribute { # # my $values = shift; # # TODO: Validate Is_circular # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_seq_attribute # # Title : is_valid_variant_seq_attribute # Usage : $self->is_valid_variant_seq_attribute($feature_hash) # Function: Validates a variant_seq_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_seq_attribute { # # my $values = shift; # for my $value (@values) { # # TODO: Validate the length of the Variant_seq # # Compile regex once above # # my $Variant_seq_regex = qr/[A-DGHKMNR-WY]+| # Any valid IUPAC Nucleotide # # ~\d*| # A ~ optionally followed by an integer # # [.\-!^\*] # Any of [.-!^*] # # /x; # if (! $self->is_valid_variant_seq_term($value)) { # if ($type eq 'SNV') { # # A single nt or .!^* # if ($value !~ /^([A-DGHKMNR-WY]|[.!^\*])$/i) { # my $error_code = 'invalid_Variant_seq_attribute_value_for_SNV'; # $self->warn($error_code, "($value) $feature_text"); # } # } # # A nt string or .!^* # elsif ($type eq 'insertion') { # if ($value !~ /^([A-DGHKMNR-WY]+|~\d*|[.!^\*])$/i) { # my $error_code = 'invalid_Variant_seq_attribute_value_for_insertion'; # $self->warn($error_code, "($value) $feature_text"); # } # } # # Any of .!^- # elsif ($type eq 'deletion') { # if ($value !~ /^[\.\^!-]$/i) { # my $error_code = 'invalid_Variant_seq_attribute_value_for_deletion'; # $self->warn($error_code, "($value) $feature_text"); # } # } # # A nt string or .!^*- # elsif ($type eq 'indel') { # if ($value !~ /^([A-DGHKMNR-WY]+|~\d*|[.\-!^])$/i) { # my $error_code = 'invalid_Variant_seq_attribute_value_for_indel'; # $self->warn($error_code, "($value) $feature_text"); # } # } # } # else { # my $error_code = 'invalid_Variant_seq_attribute_value'; # $self->warn($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_reference_seq_attribute # # Title : is_valid_reference_seq_attribute # Usage : $self->is_valid_reference_seq_attribute($feature_hash) # Function: Validates a reference_seq_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_reference_seq_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Reference_seq_attribute_multiple_values'; # my $all_values = join ', ', @values; # $self->warn($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # if (! $self->is_valid_reference_seq($value)) { # if ($type eq 'SNV') { # if ($value !~ /^([A-DGHKMNR-WY]+|\.)$/) { # my $error_code = 'invalid_Reference_seq_attribute_value_for_SNV'; # $self->warn($error_code, "($value) $feature_text"); # } # } # elsif ($type eq 'insertion') { # if ($value ne '-') { # my $error_code = 'invalid_Reference_seq_attribute_value_insertion'; # $self->warn($error_code, "($value) $feature_text"); # } # } # elsif ($type eq 'deletion') { # if ($value !~ /^([A-DGHKMNR-WY]+|[\.~])$/) { # my $error_code = 'invalid_Reference_seq_attribute_value_deletion'; # $self->warn($error_code, "($value) $feature_text"); # } # } # elsif ($type eq 'indel') { # if ($value !~ /^([A-DGHKMNR-WY]+|[\.\-~])$/) { # my $error_code = 'invalid_Reference_seq_attribute_value_indel'; # $self->warn($error_code, "($value) $feature_text"); # } # } # } # else { # my $error_code = 'invalid_Reference_seq_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # if ($self->fasta) { # my $fasta_seq = $self->fasta->get_seq($seqid, $start, $end); # if ($fasta_seq ne $value) { # my $error_code = 'Reference_seq_attribute_value_ne_fasta_seq'; # $self->throw($error_code, "($value ne $fasta_seq) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_reads_attribute # # Title : is_valid_variant_reads_attribute # Usage : $self->is_valid_variant_reads_attribute($feature_hash) # Function: Validates a variant_reads_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_reads_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_integer($value)) { # my $error_code = 'invalid_Variant_reads_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_total_reads_attribute # # Title : is_valid_total_reads_attribute # Usage : $self->is_valid_total_reads_attribute($feature_hash) # Function: Validates a total_reads_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_total_reads_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Total_reads_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # if (! $self->is_integer($value)) { # my $error_code = 'invalid_Total_reads_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_zygosity_attribute # # Title : is_valid_zygosity_attribute # Usage : $self->is_valid_zygosity_attribute($feature_hash) # Function: Validates a zygosity_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_zygosity_attribute { # # my $values = shift; # for my $value (@values) { # if ($value !~ /^(hetero|homo|hemi)zygous$/) { # my $error_code = 'invalid_Zygosity_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_freq_attribute # # Title : is_valid_variant_freq_attribute # Usage : $self->is_valid_variant_freq_attribute($feature_hash) # Function: Validates a variant_freq_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_freq_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_real_number($value)) { # my $error_code = 'invalid_Variant_freq_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_effect_attribute # # Title : is_valid_variant_effect_attribute # Usage : $self->is_valid_variant_effect_attribute($feature_hash) # Function: Validates a variant_effect_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_effect_attribute { # # my $values = shift; # for my $value (@values) { # my ($sequence_variant, $index, $sequence_feature, @featureIDs) = split /\s+/, $value; # # TODO: Validate $sequence_variant # if (! $self->is_integer($index) || $index > (scalar @{$attributes->{lVariant_seq}} - 1)) { # my $error_code = 'invalid_Variant_effect_attribute_index_value'; # $self->throw($error_code, "($index) $feature_text"); # } # if (! $self->is_valid_variant_effect($sequence_variant)) { # my $error_code = 'invalid_Variant_effect_attribute_seq_var_id_value'; # $self->throw($error_code, "($sequence_variant) $feature_text"); # } # if (! $self->is_valid_sequence_feature($sequence_feature)) { # my $error_code = 'invalid_Variant_effect_attribute_seq_feat_id_value'; # $self->throw($error_code, "($sequence_feature) $feature_text"); # } # # TODO: Validate featureIDs # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_start_range_attribute # # Title : is_valid_start_range_attribute # Usage : $self->is_valid_start_range_attribute($feature_hash) # Function: Validates a start_range_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_start_range_attribute { # # my $values = shift; # if (scalar @values != 2) { # my $error_code = 'invalid_Start_range_attribute_must_have_two_values'; # my $all_values = join ',', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # if (is_integer($values[0]) && $values[0] > $start) { # my $error_code = 'invalid_Start_range_attribute_values_must_contain_start'; # my $all_values = join ',', @values; # $self->throw($error_code, "($all_values, $start) $feature_text"); # } # if (is_integer($values[1]) && $values[1] < $start) { # my $error_code = 'invalid_Start_range_attribute_values_must_contain_start'; # my $all_values = join ',', @values; # $self->throw($error_code, "($all_values, $start) $feature_text"); # } # for my $value (@values) { # if ($value ne '.' && ! $self->is_integer($value)) { # my $error_code = 'invalid_Start_range_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_end_range_attribute # # Title : is_valid_end_range_attribute # Usage : $self->is_valid_end_range_attribute($feature_hash) # Function: Validates a end_range_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_end_range_attribute { # # my $values = shift; # if (scalar @values != 2) { # my $error_code = 'invalid_End_range_attribute_must_have_2_values'; # my $all_values = join ',', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # if (is_integer($values[0]) && $values[0] > $end) { # my $error_code = 'invalid_End_range_attribute_values_must_contain_end'; # my $all_values = join ',', @values; # $self->throw($error_code, "($all_values, $end) $feature_text"); # } # for my $value (@values) { # if ($value ne '.' && ! $self->is_integer($value)) { # my $error_code = 'invalid_End_range_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_phased_attribute # # Title : is_valid_phased_attribute # Usage : $self->is_valid_phased_attribute($feature_hash) # Function: Validates a phased_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_phased_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Phased_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # # TODO: Validate the Phased attribute # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_genotype_attribute # # Title : is_valid_genotype_attribute # Usage : $self->is_valid_genotype_attribute($feature_hash) # Function: Validates a genotype_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_genotype_attribute { # # my $values = shift; # for my $value (@values) { # if ($value !~ /^\d+:\d+$/) { # my $error_code = 'invalid_Genotype_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_individual_attribute # # Title : is_valid_individual_attribute # Usage : $self->is_valid_individual_attribute($feature_hash) # Function: Validates a individual_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_individual_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_integer($value)) { # my $error_code = 'invalid_Individual_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_copy_number_attribute # # Title : is_valid_variant_copy_number_attribute # Usage : $self->is_valid_variant_copy_number_attribute($feature_hash) # Function: Validates a variant_copy_number_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_copy_number_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_integer($value)) { # my $error_code = 'invalid_Variant_copy_number_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_reference_copy_number_attribute # # Title : is_valid_reference_copy_number_attribute # Usage : $self->is_valid_reference_copy_number_attribute($feature_hash) # Function: Validates a reference_copy_number_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_reference_copy_number_attribute { # # my $values = shift; # if (scalar @values > 1) { # my $error_code = 'invalid_Reference_copy_number_attribute_multiple_values'; # my $all_values = join ' ', @values; # $self->throw($error_code, "($all_values) $feature_text"); # } # my $value = $values[0]; # for my $value (@values) { # if (! $self->is_integer($value)) { # my $error_code = 'invalid_Reference_copy_number_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_codon_attribute # # Title : is_valid_variant_codon_attribute # Usage : $self->is_valid_variant_codon_attribute($feature_hash) # Function: Validates a variant_codon_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_codon_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_iupac_nt($value)) { # my $error_code = 'invalid_Variant_codon_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_reference_codon_attribute # # Title : is_valid_reference_codon_attribute # Usage : $self->is_valid_reference_codon_attribute($feature_hash) # Function: Validates a reference_codon_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_reference_codon_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_iupac_nt($value)) { # my $error_code = 'invalid_Reference_codon_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_aa_attribute # # Title : is_valid_variant_aa_attribute # Usage : $self->is_valid_variant_aa_attribute($feature_hash) # Function: Validates a variant_aa_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_aa_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_aa_sequence($value)) { # my $error_code = 'invalid_Variant_aa_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_reference_aa_attribute # # Title : is_valid_reference_aa_attribute # Usage : $self->is_valid_reference_aa_attribute($feature_hash) # Function: Validates a reference_aa_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_reference_aa_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_aa_sequence($value)) { # my $error_code = 'invalid_Reference_aa_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_breakpoint_detail_attribute # # Title : is_valid_breakpoint_detail_attribute # Usage : $self->is_valid_breakpoint_detail_attribute($feature_hash) # Function: Validates a breakpoint_detail_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_breakpoint_detail_attribute { # # my $values = shift; # my $value = $values[0]; # my ($seqid, $start_end, $strand) = split /:/, $value; # my ($start, $end) = split /\-/, $start_end; # if (! $self->is_integer($start)) { # my $error_code = 'invalid_start_in_Breakpoint_detail_attribute'; # $self->warn($error_code, $feature_text); # } # if ($end && ! $self->is_integer($end)) { # my $error_code = 'invalid_end_in_Breakpoint_detail_attribute'; # $self->warn($error_code, $feature_text); # } # if ($strand && $strand !~ /^(=|\-)$/) { # my $error_code = 'invalid_strand_in_Breakpoint_detail_attribute'; # $self->warn($error_code, $feature_text); # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_sequence_context_attribute # # Title : is_valid_sequence_context_attribute # Usage : $self->is_valid_sequence_context_attribute($feature_hash) # Function: Validates a sequence_context_attribute. # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_sequence_context_attribute { # # my $values = shift; # for my $value (@values) { # if (! $self->is_iupac_nt($value)) { # my $error_code = 'invalid_Sequence_context_attribute_value'; # $self->throw($error_code, "($value) $feature_text"); # } # } # return 1; #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_all # # # Title : is_valid_all # Usage : $self->is_valid_all($feature_hash) # Function: Validates all attributes # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_all { # # my $values = shift; # return 1; # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid # # Title : is_valid # Usage : $self->is_valid($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_reference_seq # # Title : is_valid_reference_seq # Usage : $self->is_valid_reference_seq($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_reference_seq { # # #} # # ##----------------------------------------------------------------------------- # #=head2 is_valid_sequence_feature # # Title : is_valid_sequence_feature # Usage : $self->is_valid_sequence_feature($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_sequence_feature { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_sequence_alteration # # Title : is_valid_sequence_alteration # Usage : $self->is_valid_sequence_alteration($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_sequence_alteration { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_effect # # Title : is_valid_variant_effect # Usage : $self->is_valid_variant_effect($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_effect { # # #} # ##----------------------------------------------------------------------------- # #=head2 is_valid_variant_seq # # Title : is_valid_variant_seq # Usage : $self->is_valid_variant_seq($feature_hash) # Function: Validates a ... # Returns : 1 if valid undef otherwise. # Args : A string of text. # #=cut # #sub is_valid_variant_seq { # # #} #----------------------------------------------------------------------------- =head1 DIAGNOSTICS =over =item C<< invalid_arguments_to_prepare_args >> C<GAL::Base::prepare_args> accepts an array, a hash or a reference to either an array or hash, but it was passed something different. =item C<< invalid_ipuac_nucleotide_code >> C<GAL::Base::expand_iupac_nt_codes> was passed a charachter that is not a valid IUPAC nucleotide code (http://en.wikipedia.org/wiki/Nucleic_acid_notation). =item C<< failed_to_load_module >> C<GAL::Base::load_module> was unable to load (require) the specified module. The module may not be installed or it may have a compile time error. =item C<< invalid_arguments_to_get_feature_bins >> C<GAL::Base::get_feature_bins> was called with invalid arguments. It must have either a hash with the keys qw(seqid start end) or an object with those same keys as methods. The error message will try to give you some idea of what arguments were passed. =item C<< invalid_aa_datum_code >> An invalid amino acid code was passed to C<GAL::Base::amino_acid_data>. Single-letter or three-letter amino acid codes are required. =back =head1 CONFIGURATION AND ENVIRONMENT L<GAL::Base> requires no configuration files or environment variables. =head1 DEPENDENCIES =over =item L<Carp> qw(croak cluck) =item L<Bio::DB::Fasta> =back =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to: barry.moore@genetics.utah.edu =head1 AUTHOR Barry Moore <barry.moore@genetics.utah.edu> =head1 LICENCE AND COPYRIGHT Copyright (c) 2010-2014, Barry Moore <barry.moore@genetics.utah.edu>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself (See LICENSE). =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =cut 1;
4ureliek/TEanalysis
Lib/GAL/Base.pm
Perl
mit
82,586
# # $Id: Jcode.pm,v 2.6 2006/07/02 07:56:06 dankogai Exp dankogai $ # package Jcode; use 5.005; # fair ? use Carp; use strict; use vars qw($RCSID $VERSION $DEBUG); $RCSID = q$Id: Jcode.pm,v 2.6 2006/07/02 07:56:06 dankogai Exp dankogai $; $VERSION = do { my @r = (q$Revision: 2.6 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; $DEBUG = 0; # we no longer use Exporter use vars qw($USE_ENCODE); $USE_ENCODE = ($] >= 5.008001); use Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); @ISA = qw(Exporter); @EXPORT = qw(jcode getcode); @EXPORT_OK = qw($RCSID $VERSION $DEBUG); %EXPORT_TAGS = ( all => [ @EXPORT, @EXPORT_OK ] ); use overload q("") => sub { $_[0]->euc }, q(==) => sub { overload::StrVal($_[0]) eq overload::StrVal($_[1]) }, q(.=) => sub { $_[0]->append( $_[1] ) }, fallback => 1, ; if ($USE_ENCODE){ $DEBUG and warn "Using Encode"; my $data = join("", <DATA>); eval $data; $@ and die $@; }else{ $DEBUG and warn "Not Using Encode"; require Jcode::_Classic; use vars qw/@ISA/; unshift @ISA, qw/Jcode::_Classic/; for my $sub (qw/jcode getcode convert load_module/){ no strict 'refs'; *{$sub} = \&{'Jcode::_Classic::' . $sub }; } for my $enc (qw/sjis jis ucs2 utf8/){ no strict 'refs'; *{"euc_" . $enc} = \&{"Jcode::_Classic::" . "euc_" . $enc}; *{$enc . "_euc"} = \&{"Jcode::_Classic::" . $enc . "_euc"}; } } 1; __DATA__ # # This idea was inspired by JEncode # http://www.donzoko.net/cgi/jencode/ # package Jcode; use Encode; use Encode::Alias; use Encode::Guess; use Encode::JP::H2Z; use Scalar::Util; # to resolve from_to() vs. 'constant' issue. my %jname2e = ( sjis => 'shiftjis', euc => 'euc-jp', jis => '7bit-jis', iso_2022_jp => 'iso-2022-jp', ucs2 => 'UTF-16BE', ); my %ename2j = reverse %jname2e; our $FALLBACK = Encode::LEAVE_SRC; sub FB_PERLQQ() { Encode::FB_PERLQQ() }; sub FB_XMLCREF() { Encode::FB_XMLCREF() }; sub FB_HTMLCREF() { Encode::FB_HTMLCREF() }; #for my $fb (qw/FB_PERLQQ FB_XMLCREF FB_HTMLCREF/){ # no strict 'refs'; # *{$fb} = \&{"Encode::$fb"}; #} ####################################### # Functions ####################################### sub jcode { return __PACKAGE__->new(@_); } # # Used to be in Jcode::Constants # my %_0208 = ( 1978 => '\e\$\@', 1983 => '\e\$B', 1990 => '\e&\@\e\$B', ); my %RE = ( ASCII => '[\x00-\x7f]', BIN => '[\x00-\x06\x7f\xff]', EUC_0212 => '\x8f[\xa1-\xfe][\xa1-\xfe]', EUC_C => '[\xa1-\xfe][\xa1-\xfe]', EUC_KANA => '\x8e[\xa1-\xdf]', JIS_0208 => "$_0208{1978}|$_0208{1983}|$_0208{1990}", JIS_0212 => "\e" . '\$\(D', JIS_ASC => "\e" . '\([BJ]', JIS_KANA => "\e" . '\(I', SJIS_C => '[\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc]', SJIS_KANA => '[\xa1-\xdf]', UTF8 => '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]' ); sub _max { my $result = shift; for my $n (@_){ $result = $n if $n > $result; } return $result; } sub getcode { my $arg = shift; my $r_str = ref $arg ? $arg : \$arg; Encode::is_utf8($$r_str) and return 'utf8'; my ($code, $nmatch, $sjis, $euc, $utf8) = ("", 0, 0, 0, 0); if ($$r_str =~ /$RE{BIN}/o) { # 'binary' my $ucs2; $ucs2 += length($1) while $$r_str =~ /(\x00$RE{ASCII})+/go; if ($ucs2){ # smells like raw unicode ($code, $nmatch) = ('ucs2', $ucs2); }else{ ($code, $nmatch) = ('binary', 0); } } elsif ($$r_str !~ /[\e\x80-\xff]/o) { # not Japanese ($code, $nmatch) = ('ascii', 1); } # 'jis' elsif ($$r_str =~ m[ $RE{JIS_0208}|$RE{JIS_0212}|$RE{JIS_ASC}|$RE{JIS_KANA} ]ox) { ($code, $nmatch) = ('jis', 1); } else { # should be euc|sjis|utf8 # use of (?:) by Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp> $sjis += length($1) while $$r_str =~ /((?:$RE{SJIS_C})+)/go; $euc += length($1) while $$r_str =~ /((?:$RE{EUC_C}|$RE{EUC_KANA}|$RE{EUC_0212})+)/go; $utf8 += length($1) while $$r_str =~ /((?:$RE{UTF8})+)/go; # $utf8 *= 1.5; # M. Takahashi's suggestion $nmatch = _max($utf8, $sjis, $euc); carp ">DEBUG:sjis = $sjis, euc = $euc, utf8 = $utf8" if $DEBUG >= 3; $code = ($euc > $sjis and $euc > $utf8) ? 'euc' : ($sjis > $euc and $sjis > $utf8) ? 'sjis' : ($utf8 > $euc and $utf8 > $sjis) ? 'utf8' : undef; } return wantarray ? ($code, $nmatch) : $code; } sub convert{ my $r_str = (ref $_[0]) ? $_[0] : \$_[0]; my (undef,$ocode,$icode,$opt) = @_; Encode::is_utf8($$r_str) and utf8::encode($$r_str); defined $icode or $icode = getcode($r_str) or return; $icode eq 'binary' and return $$r_str; $jname2e{$icode} and $icode = $jname2e{$icode}; $jname2e{$ocode} and $ocode = $jname2e{$ocode}; if ($opt){ return $opt eq 'z' ? jcode($r_str, $icode)->h2z->$ocode : jcode($r_str, $icode)->z2h->$ocode ; }else{ if (Scalar::Util::readonly($$r_str)){ my $tmp = $$r_str; Encode::from_to($tmp, $icode, $ocode); return $tmp; }else{ Encode::from_to($$r_str, $icode, $ocode); return $$r_str; } } } ####################################### # Constructors ####################################### sub new{ my $class = shift; my $self = {}; bless $self => $class; defined $_[0] or $_[0] = ''; $self->set(@_); } sub set{ my $self = shift; my $str = $_[0]; my $r_str = (ref $str) ? $str : \$str; my $code = $_[1] if(defined $_[1]); my $icode = $code || getcode($r_str) || 'euc'; $self->{icode} = $jname2e{$icode} || $icode; # binary and flagged utf8 are stored as-is unless (Encode::is_utf8($$r_str) || $icode eq 'binary'){ $$r_str = decode($self->{icode}, $$r_str); } $self->{r_str} = $r_str; $self->{nmatch} = 0; $self->{method} = 'Encode'; $self->{fallback} = $FALLBACK; $self; } sub append{ my $self = shift; my $str = $_[0]; my $r_str = (ref $str) ? $str : \$str; my $code = $_[1] if(defined $_[1]); my $icode = $code || getcode($r_str) || 'euc'; $self->{icode} = $jname2e{$icode} || $icode; # binary and flagged utf8 are stored as-is unless (Encode::is_utf8($$r_str) || $icode eq 'binary'){ $$r_str = decode($self->{icode}, $$r_str); } ${ $self->{r_str} } .= $$r_str; $self->{nmatch} = 0; $self->{method} = 'internal'; $self; } ####################################### # Accessors ####################################### for my $method (qw/r_str icode nmatch error_m error_r error_tr/){ no strict 'refs'; *{$method} = sub { $_[0]->{$method} }; } sub fallback{ my $self = shift; @_ or return $self->{fallback}; $self->{fallback} = $_[0]|Encode::LEAVE_SRC; return $self; } ####################################### # Converters ####################################### sub utf8 { encode_utf8( ${$_[0]->{r_str}} ) } # # Those supported in Jcode 0.x are defined as default # for my $enc (keys %jname2e){ no strict 'refs'; my $name = $jname2e{$enc} || $enc; my $e = find_encoding($name) or croak "$enc not supported"; *{$enc} = sub { my $r_str = $_[0]->{r_str}; Encode::is_utf8($$r_str) ? $e->encode($$r_str, $_[0]->{fallback}) : $$r_str; }; } # # The rest is defined on the fly # sub DESTROY {}; sub AUTOLOAD { our $AUTOLOAD; my $self = shift; my $type = ref $self or confess "$self is not an object"; my $myname = $AUTOLOAD; $myname =~ s/.*:://; # strip fully-qualified portion $myname eq 'DESTROY' and return; my $e = find_encoding($myname) or confess __PACKAGE__, ": unknown encoding: $myname"; $DEBUG and warn ref($self), "->$myname defined"; no strict 'refs'; *{$myname} = sub { my $str = ${ $_[0]->{r_str} }; Encode::is_utf8($str) ? $e->encode($str, $_[0]->{fallback}) : $str; }; $myname->($self); } ####################################### # Length, Translation and Fold ####################################### sub jlength{ length( ${$_[0]->{r_str}} ); } sub tr{ my $self = shift; my $str = ${$self->{r_str}}; my $from = Encode::is_utf8($_[0]) ? $_[0] : decode('euc-jp', $_[0]); my $to = Encode::is_utf8($_[1]) ? $_[1] : decode('euc-jp', $_[1]); my $opt = $_[2] || ''; $from =~ s,\\,\\\\,og; $from =~ s,/,\\/,og; $to =~ s,\\,\\\\,og; $to =~ s,/,\\/,og; $opt =~ s,[^a-z],,og; my $match = eval qq{ \$str =~ tr/$from/$to/$opt }; if ($@){ $self->{error_tr} = $@; return $self; } $self->{r_str} = \$str; $self->{nmatch} = $match || 0; return $self; } sub jfold{ my $self = shift; my $r_str = $self->{r_str}; my $bpl = shift || 72; my $nl = shift || "\n"; my $kin = shift; my @lines = (); my %kinsoku = (); my ($len, $i) = (0,0); if( defined $kin and (ref $kin) eq 'ARRAY' ){ %kinsoku = map { my $k = Encode::is_utf8($_) ? $_ : decode('euc-jp' => $_); ($k, 1) } @$kin; } while($$r_str =~ m/(.)/sg){ my $char = $1; # <UFF61> \xA1 |0 # HALFWIDTH IDEOGRAPHIC FULL STOP # <UFF9F> \xDF |0 # HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK my $ord = ord($char); my $clen = $ord < 128 ? 1 : $ord < 0xff61 ? 2 : $ord <= 0xff9f ? 1 : 2; if ($len + $clen > $bpl){ unless($kinsoku{$char}){ $i++; $len = 0; } } $lines[$i] .= $char; $len += $clen; } defined($lines[$i]) or pop @lines; $$r_str = join($nl, @lines); $self->{r_str} = $r_str; my $e = find_encoding($self->{icode}); @lines = map { Encode::is_utf8($_) ? $e->encode($_, $self->{fallback}) : $_ } @lines; return wantarray ? @lines : $self; } ####################################### # Full and Half ####################################### sub h2z{ my $self = shift; my $euc = $self->euc; Encode::JP::H2Z::h2z(\$euc, @_); $self->set($euc => 'euc'); $self; } sub z2h{ my $self = shift; my $euc = $self->euc; Encode::JP::H2Z::z2h(\$euc, @_); $self->set($euc => 'euc'); $self; } ####################################### # MIME-Encoding ####################################### sub mime_decode{ my $self = shift; my $utf8 = Encode::decode('MIME-Header', $self->utf8); $self->set($utf8 =>'utf8'); } sub mime_encode{ my $self = shift; my $str = $self->euc; my $r_str = \$str; my $lf = shift || "\n"; my $bpl = shift || 76; my ($trailing_crlf) = ($$r_str =~ /(\n|\r|\x0d\x0a)$/o); $str = _mime_unstructured_header($$r_str, $lf, $bpl); not $trailing_crlf and $str =~ s/(\n|\r|\x0d\x0a)$//o; $str; } # # shamelessly stolen from # http://www.din.or.jp/~ohzaki/perl.htm#JP_Base64 # sub _add_encoded_word { require MIME::Base64; my($str, $line, $bpl) = @_; my $result = ''; while (length($str)) { my $target = $str; $str = ''; if (length($line) + 22 + ($target =~ /^(?:$RE{EUC_0212}|$RE{EUC_C})/o) * 8 > $bpl) { $line =~ s/[ \t\n\r]*$/\n/; $result .= $line; $line = ' '; } while (1) { my $iso_2022_jp = jcode($target, 'euc')->iso_2022_jp; if (my $count = ($iso_2022_jp =~ tr/\x80-\xff//d)){ $DEBUG and warn $count; $target = jcode($iso_2022_jp, 'iso_2022_jp')->euc; } my $encoded = '=?ISO-2022-JP?B?' . MIME::Base64::encode_base64($iso_2022_jp, '') . '?='; if (length($encoded) + length($line) > $bpl) { $target =~ s/($RE{EUC_0212}|$RE{EUC_KANA}|$RE{EUC_C}|$RE{ASCII})$//o; $str = $1 . $str; } else { $line .= $encoded; last; } } } return $result . $line; } sub _mime_unstructured_header { my ($oldheader, $lf, $bpl) = @_; my(@words, @wordstmp, $i); my $header = ''; $oldheader =~ s/\s+$//; @wordstmp = split /\s+/, $oldheader; for ($i = 0; $i < $#wordstmp; $i++) { if ($wordstmp[$i] !~ /^[\x21-\x7E]+$/ and $wordstmp[$i + 1] !~ /^[\x21-\x7E]+$/) { $wordstmp[$i + 1] = "$wordstmp[$i] $wordstmp[$i + 1]"; } else { push(@words, $wordstmp[$i]); } } push(@words, $wordstmp[-1]); for my $word (@words) { if ($word =~ /^[\x21-\x7E]+$/) { $header =~ /(?:.*\n)*(.*)/; if (length($1) + length($word) > $bpl) { $header .= "$lf $word"; } else { $header .= $word; } } else { $header = _add_encoded_word($word, $header, $bpl); } $header =~ /(?:.*\n)*(.*)/; if (length($1) == $bpl) { $header .= "$lf "; } else { $header .= ' '; } } $header =~ s/\n? $/\n/; $header; } ####################################### # Matching and Replacing ####################################### no warnings 'uninitialized'; sub m{ use utf8; my $self = shift; my $r_str = $self->{r_str}; my $pattern = Encode::is_utf8($_[0]) ? shift : decode("euc-jp" => shift); my $opt = shift || '' ; my @match; $pattern =~ s,\\,\\\\,og; $pattern =~ s,/,\\/,og; $opt =~ s,[^a-z],,og; eval qq{ \@match = (\$\$r_str =~ m/$pattern/$opt) }; if ($@){ $self->{error_m} = $@; return; } # print @match, "\n"; wantarray ? map {encode('euc-jp' => $_)} @match : scalar @match; } sub s{ use utf8; my $self = shift; my $r_str = $self->{r_str}; my $pattern = Encode::is_utf8($_[0]) ? shift : decode("euc-jp" => shift); my $replace = Encode::is_utf8($_[0]) ? shift : decode("euc-jp" => shift); my $opt = shift; $pattern =~ s,\\,\\\\,og; $pattern =~ s,/,\\/,og; $replace =~ s,\\,\\\\,og; $replace =~ s,/,\\/,og; $opt =~ s,[^a-z],,og; eval qq{ (\$\$r_str =~ s/$pattern/$replace/$opt) }; if ($@){ $self->{error_s} = $@; } $self; } 1; __END__ =head1 NAME Jcode - Japanese Charset Handler =head1 SYNOPSIS use Jcode; # # traditional Jcode::convert(\$str, $ocode, $icode, "z"); # or OOP! print Jcode->new($str)->h2z->tr($from, $to)->utf8; =cut =head1 DESCRIPTION B<<Japanese document is now available as L<Jcode::Nihongo>. >> Jcode.pm supports both object and traditional approach. With object approach, you can go like; $iso_2022_jp = Jcode->new($str)->h2z->jis; Which is more elegant than: $iso_2022_jp = $str; &jcode::convert(\$iso_2022_jp, 'jis', &jcode::getcode(\$str), "z"); For those unfamiliar with objects, Jcode.pm still supports C<getcode()> and C<convert().> If the perl version is 5.8.1, Jcode acts as a wrapper to L<Encode>, the standard charset handler module for Perl 5.8 or later. =head1 Methods Methods mentioned here all return Jcode object unless otherwise mentioned. =head2 Constructors =over 2 =item $j = Jcode-E<gt>new($str [, $icode]) Creates Jcode object $j from $str. Input code is automatically checked unless you explicitly set $icode. For available charset, see L<getcode> below. For perl 5.8.1 or better, C<$icode> can be I<any encoding name> that L<Encode> understands. $j = Jcode->new($european, 'iso-latin1'); When the object is stringified, it returns the EUC-converted string so you can <print $j> instead of <print $j->euc>. =over 2 =item Passing Reference Instead of scalar value, You can use reference as Jcode->new(\$str); This saves time a little bit. In exchange of the value of $str being converted. (In a way, $str is now "tied" to jcode object). =back =item $j-E<gt>set($str [, $icode]) Sets $j's internal string to $str. Handy when you use Jcode object repeatedly (saves time and memory to create object). # converts mailbox to SJIS format my $jconv = new Jcode; $/ = 00; while(&lt;&gt;){ print $jconv->set(\$_)->mime_decode->sjis; } =item $j-E<gt>append($str [, $icode]); Appends $str to $j's internal string. =item $j = jcode($str [, $icode]); shortcut for Jcode->new() so you can go like; =back =head2 Encoded Strings In general, you can retrieve I<encoded> string as $j-E<gt>I<encoded>. =over 2 =item $sjis = jcode($str)->sjis =item $euc = $j-E<gt>euc =item $jis = $j-E<gt>jis =item $sjis = $j-E<gt>sjis =item $ucs2 = $j-E<gt>ucs2 =item $utf8 = $j-E<gt>utf8 What you code is what you get :) =item $iso_2022_jp = $j-E<gt>iso_2022_jp Same as C<< $j->h2z->jis >>. Hankaku Kanas are forcibly converted to Zenkaku. For perl 5.8.1 and better, you can also use any encoding names and aliases that Encode supports. For example: $european = $j->iso_latin1; # replace '-' with '_' for names. B<FYI>: L<Encode::Encoder> uses similar trick. =over 2 =item $j-E<gt>fallback($fallback) For perl is 5.8.1 or better, Jcode stores the internal string in UTF-8. Any character that does not map to I<< -E<gt>encoding >> are replaced with a '?', which is L<Encode> standard. my $unistr = "\x{262f}"; # YIN YANG my $j = jcode($unistr); # $j->euc is '?' You can change this behavior by specifying fallback like L<Encode>. Values are the same as L<Encode>. C<Jcode::FB_PERLQQ>, C<Jcode::FB_XMLCREF>, C<Jcode::FB_HTMLCREF> are aliased to those of L<Encode> for convenice. print $j->fallback(Jcode::FB_PERLQQ)->euc; # '\x{262f}' print $j->fallback(Jcode::FB_XMLCREF)->euc; # '&#x262f;' print $j->fallback(Jcode::FB_HTMLCREF)->euc; # '&#9775;' The global variable C<$Jcode::FALLBACK> stores the default fallback so you can override that by assigning the value. $Jcode::FALLBACK = Jcode::FB_PERLQQ; # set default fallback scheme =back =item [@lines =] $jcode-E<gt>jfold([$width, $newline_str, $kref]) folds lines in jcode string every $width (default: 72) where $width is the number of "halfwidth" character. Fullwidth Characters are counted as two. with a newline string spefied by $newline_str (default: "\n"). Rudimentary kinsoku suppport is now available for Perl 5.8.1 and better. =item $length = $jcode-E<gt>jlength(); returns character length properly, rather than byte length. =back =head2 Methods that use MIME::Base64 To use methods below, you need L<MIME::Base64>. To install, simply perl -MCPAN -e 'CPAN::Shell->install("MIME::Base64")' If your perl is 5.6 or better, there is no need since L<MIME::Base64> is bundled. =over 2 =item $mime_header = $j-E<gt>mime_encode([$lf, $bpl]) Converts $str to MIME-Header documented in RFC1522. When $lf is specified, it uses $lf to fold line (default: \n). When $bpl is specified, it uses $bpl for the number of bytes (default: 76; this number must be smaller than 76). For Perl 5.8.1 or better, you can also encode MIME Header as: $mime_header = $j->MIME_Header; In which case the resulting C<$mime_header> is MIME-B-encoded UTF-8 whereas C<< $j->mime_encode() >> returnes MIME-B-encoded ISO-2022-JP. Most modern MUAs support both. =item $j-E<gt>mime_decode; Decodes MIME-Header in Jcode object. For perl 5.8.1 or better, you can also do the same as: Jcode->new($str, 'MIME-Header') =back =head2 Hankaku vs. Zenkaku =over 2 =item $j-E<gt>h2z([$keep_dakuten]) Converts X201 kana (Hankaku) to X208 kana (Zenkaku). When $keep_dakuten is set, it leaves dakuten as is (That is, "ka + dakuten" is left as is instead of being converted to "ga") You can retrieve the number of matches via $j->nmatch; =item $j-E<gt>z2h Converts X208 kana (Zenkaku) to X201 kana (Hankaku). You can retrieve the number of matches via $j->nmatch; =back =head2 Regexp emulators To use C<< -E<gt>m() >> and C<< -E<gt>s() >>, you need perl 5.8.1 or better. =over 2 =item $j-E<gt>tr($from, $to, $opt); Applies C<tr/$from/$to/> on Jcode object where $from and $to are EUC-JP strings. On perl 5.8.1 or better, $from and $to can also be flagged UTF-8 strings. If C<$opt> is set, C<tr/$from/$to/$opt> is applied. C<$opt> must be 'c', 'd' or the combination thereof. You can retrieve the number of matches via $j->nmatch; The following methods are available only for perl 5.8.1 or better. =item $j-E<gt>s($patter, $replace, $opt); Applies C<s/$pattern/$replace/$opt>. C<$pattern> and C<replace> must be in EUC-JP or flagged UTF-8. C<$opt> are the same as regexp options. See L<perlre> for regexp options. Like C<< $j->tr() >>, C<< $j->s() >> returns the object itself so you can nest the operation as follows; $j->tr("a-z", "A-Z")->s("foo", "bar"); =item [@match = ] $j-E<gt>m($pattern, $opt); Applies C<m/$patter/$opt>. Note that this method DOES NOT RETURN AN OBJECT so you can't chain the method like C<< $j->s() >>. =back =head2 Instance Variables If you need to access instance variables of Jcode object, use access methods below instead of directly accessing them (That's what OOP is all about) FYI, Jcode uses a ref to array instead of ref to hash (common way) to optimize speed (Actually you don't have to know as long as you use access methods instead; Once again, that's OOP) =over 2 =item $j-E<gt>r_str Reference to the EUC-coded String. =item $j-E<gt>icode Input charcode in recent operation. =item $j-E<gt>nmatch Number of matches (Used in $j->tr, etc.) =back =cut =head1 Subroutines =over 2 =item ($code, [$nmatch]) = getcode($str) Returns char code of $str. Return codes are as follows ascii Ascii (Contains no Japanese Code) binary Binary (Not Text File) euc EUC-JP sjis SHIFT_JIS jis JIS (ISO-2022-JP) ucs2 UCS2 (Raw Unicode) utf8 UTF8 When array context is used instead of scaler, it also returns how many character codes are found. As mentioned above, $str can be \$str instead. B<jcode.pl Users:> This function is 100% upper-conpatible with jcode::getcode() -- well, almost; * When its return value is an array, the order is the opposite; jcode::getcode() returns $nmatch first. * jcode::getcode() returns 'undef' when the number of EUC characters is equal to that of SJIS. Jcode::getcode() returns EUC. for Jcode.pm there is no in-betweens. =item Jcode::convert($str, [$ocode, $icode, $opt]) Converts $str to char code specified by $ocode. When $icode is specified also, it assumes $icode for input string instead of the one checked by getcode(). As mentioned above, $str can be \$str instead. B<jcode.pl Users:> This function is 100% upper-conpatible with jcode::convert() ! =back =head1 BUGS For perl is 5.8.1 or later, Jcode acts as a wrapper to L<Encode>. Meaning Jcode is subject to bugs therein. =head1 ACKNOWLEDGEMENTS This package owes a lot in motivation, design, and code, to the jcode.pl for Perl4 by Kazumasa Utashiro <utashiro@iij.ad.jp>. Hiroki Ohzaki <ohzaki@iod.ricoh.co.jp> has helped me polish regexp from the very first stage of development. JEncode by makamaka@donzoko.net has inspired me to integrate Encode to Jcode. He has also contributed Japanese POD. And folks at Jcode Mailing list <jcode5@ring.gr.jp>. Without them, I couldn't have coded this far. =head1 SEE ALSO L<Encode> L<Jcode::Nihongo> L<http://www.iana.org/assignments/character-sets> =head1 COPYRIGHT Copyright 1999-2005 Dan Kogai <dankogai@dan.co.jp> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Jcode.pm
Perl
mit
23,095
use MooseX::Declare; use strict; use warnings; class Test::Queue::Master extends Queue::Master with (Test::Agua::Common::Database, Agua::Common::Util) { use Test::Synapse; use Test::Virtual; has 'logfile' => ( isa => 'Str|Undef', is => 'rw', required => 1 ); has 'dumpfile' => ( isa => 'Str|Undef', is => 'rw', required => 1 ); has 'authurl' => ( isa => 'Str|Undef', is => 'rw'); has 'password' => ( isa => 'Str|Undef', is => 'rw'); has 'tenantid' => ( isa => 'Str|Undef', is => 'rw'); has 'tenantname'=> ( isa => 'Str|Undef', is => 'rw'); has 'username' => ( isa => 'Str|Undef', is => 'rw'); has 'synapse' => ( isa => 'Test::Synapse', is => 'rw', lazy => 1, builder => "setSynapse" ); use FindBin qw($Bin); use Test::More; #####////}}}}} method testSendTask { my $task = { "mode" => "executeWorkflow", "status" => "queued", "project" => "CU", "sendtype" => "task", "sample" => "0daf2e9a-2a4f-4572-ac83-859f842680de", "token" => undef, "module" => "Agua::Workflow", "workflownumber" => "2", "processid" => "2251", "username" => "syoung", "workflow" => "Download", "database" => "agua", "sourceid" => "", "callback" => "", "queue" => "syoung.CU.Download", "queued" => "2014-06-26 18:12:28" }; $self->sendTask($task); } method testGetInstanceTypes { diag("getInstanceTypes"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "instances for all queues", project => "CU", tables => [ "project", "provenance", "cluster", "instance", "instancetype", "queuesample" ], expected => { "testuser.CU.Download" => { "memory" => "32", "cluster" => "testuser.CU.Download", "disk" => "20", "instancetype" => "bcf.8c.32g", "cpus" => "8", "ephemeral" => "0", "username" => "testuser" }, "testuser.CU.Bwa" => { "memory" => "32", "cluster" => "testuser.CU.Bwa", "disk" => "20", "instancetype" => "bcf.4c.32g", "cpus" => "4", "ephemeral" => "0", "username" => "testuser" }, "testuser.CU.FreeBayes" => { "memory" => "64", "cluster" => "testuser.CU.FreeBayes", "disk" => "20", "instancetype" => "bcf.1c.64g", "cpus" => "1", "ephemeral" => "0", "username" => "testuser" } } } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $project = $test->{project}; my $testname = $test->{testname}; my $expected = $test->{expected}; #### LOAD TABLES foreach my $table ( @$tables ) { #$self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); my $instancetypes = $self->getInstanceTypes($queues); $self->logDebug("instancetypes", $instancetypes); is_deeply($instancetypes, $expected, $testname) } } method testBalanceInstances { diag("balanceQueues"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "for all running queues", instancecounts => { "testuser.CU.Download" => "4", "testuser.CU.Bwa" => "4", "testuser.CU.FreeBayes" => "2" }, project => "CU", metric => "cpus", tables => [ "project", "provenance", "cluster", "instance", "instancetype", "queuesample" ], expectedinstances => [23,79], expectedcounts => ["178.571428571429","321.428571428571"] } ]; *getResourceQuota = sub { my $self = shift; my $username = shift; my $metric = shift; $self->logDebug("username", $username); #print "Test::Queue::Master::testBalanceQueues OVERRIDE getResourceQuota\n"; #print "Test::Queue::Master::testBalanceQueues username: $username\n"; return 500; }; my $virtual = $self->virtual(); foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $project = $test->{project}; my $testname = $test->{testname}; my $expectedinstances = $test->{expectedinstances}; my $expectedcounts = $test->{expectedcounts}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); my $counts = $self->balanceInstance($queues); $self->logDebug("counts", $counts); is_deeply($counts, $expectedcounts, $testname . " (resourcecounts)"); } } method testGetResourceCounts { diag("getResourceCounts"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "for all running queues", instancecounts => { "testuser.CU.Download" => "4", "testuser.CU.Bwa" => "4", "testuser.CU.FreeBayes" => "2" }, project => "CU", metric => "cpus", queues => [ { "workflownumber" => "1", "workflow" => "Download", "project" => "CU", "username" => "testuser" }, { "workflownumber" => "2", "workflow" => "Bwa", "project" => "CU", "username" => "testuser" }, { "workflownumber" => "3", "workflow" => "FreeBayes", "project" => "CU", "username" => "testuser" } ], durations => { "testuser.CU.Download" => "200", "testuser.CU.Bwa" => "720", "testuser.CU.FreeBayes" => "2100" }, tables => [ "project", "provenance", "cluster", "instance", "instancetype", "queuesample" ], expectedinstances => [23,79], expectedcounts => ["178.571428571429","321.428571428571"] } ]; *getResourceQuota = sub { my $self = shift; my $username = shift; my $metric = shift; $self->logDebug("username", $username); #print "Test::Queue::Master::testGetResourceCounts OVERRIDE getResourceQuota\n"; #print "Test::Queue::Master::testGetResourceCounts username: $username\n"; return 500; }; my $virtual = $self->virtual(); foreach my $test ( @$tests ) { my $tables = $test->{tables}; #my $queues = $test->{queues}; #my $durations = $test->{durations}; my $project = $test->{project}; my $metric = $test->{metric}; #my $instancecounts = $test->{instancecounts}; my $testname = $test->{testname}; my $expectedinstances = $test->{expectedinstances}; my $expectedcounts = $test->{expectedcounts}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); my $durations = $self->getDurations($queues); my $instancetypes = $self->getInstanceTypes($queues); my $counts = $self->getResourceCounts($queues, $durations, $instancetypes); $self->logDebug("counts", $counts); is_deeply($counts, $expectedcounts, $testname . " (resourcecounts)"); my $instancecounts = $self->getInstanceCounts($queues, $instancetypes, $counts); $self->logDebug("instancecounts", $instancecounts); is_deeply($instancecounts, $expectedinstances, $testname . " (instancecounts)"); } } method testGetTenants { diag("getTenants"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "retrieved tenants", expected => [ { username => "testuser", osusername => "OSUSERNAME", osauthurl => "http://10.2.16.Us64:5000/v2.0", ospassword => "OSPASSWORD", ostenantid => "OSTENANTID", ostenantname=> "OSTENANTNAME" } ], tables => [ "tenant" ] } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $testname = $test->{testname}; my $expected = $test->{expected}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $tenants = $self->getTenants(); $self->logDebug("tenants", $tenants); is_deeply($tenants, $expected, "$testname") } } method testGetQueueTasks { diag("getQueueTasks"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $expected = { "testuser.CU.Download" => "8", "testuser.CU.Bwa" => "4", "testuser.CU.FreeBayes" => "0", "testuser.Sleep.Sleep1" => "2", "testuser.Sleep.Sleep2" => "2" }; *getQueueTaskList = sub { return qq{Listing queues ... testuser.CU.Download 8 testuser.CU.Bwa 4 testuser.CU.FreeBayes 0 testuser.Sleep.Sleep1 2 testuser.Sleep.Sleep2 2 ...done.}; }; my $tasks = $self->getQueueTasks(); $self->logDebug("tasks", $tasks); is_deeply($tasks, $expected, "queue tasks hash"); } method testManage { diag("manage"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "latest index", queue => { username => "testuser", project => "CU", workflow => "Download" }, tables => [ "project", "provenance", "cluster", "instancetype", "queuesample" ], expected => 1 } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; my $queue = $test->{queue}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $success = $self->manage(); $self->logDebug("success", $success); ok($success == $expected, "$testname: $success") } } method testGetLatestCompleted { diag("getLatestCompleted"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "latest index", project => "CU", queue => { username => "testuser", project => "CU", workflow => "Download" }, tables => [ "project", "provenance", "cluster", "instancetype", "queuesample" ], expected => 1 } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $project = $test->{project}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; my $queue = $test->{queue}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); my $latestindex = $self->getLatestCompleted($queues); $self->logDebug("latestindex", $latestindex); ok($latestindex == $expected, "$testname: $latestindex") } } method testGetLatestStarted { diag("getLatestStarted"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "latest index", project => "CU", queue => { username => "testuser", project => "CU", workflow => "Download" }, tables => [ "project", "provenance", "cluster", "instancetype", "queuesample" ], expected => 2 } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $project = $test->{project}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; my $queue = $test->{queue}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); my $latestindex = $self->getLatestStarted($queues); $self->logDebug("latestindex", $latestindex); ok($latestindex == $expected, "$testname: $latestindex") } } method testGetRunningUserProjects { diag("getRunningUserProjects"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "retrieved running projects", queue => { username => "testuser", project => "CU", workflow => "Download" }, tables => [ "project", "provenance", "cluster", "instancetype", "queuesample" ], expected => ["CU","Test"] } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; my $queue = $test->{queue}; my $username = $queue->{username}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $projects = $self->getRunningUserProjects($username); $self->logDebug("projects", $projects); is_deeply($projects, $expected, "$testname") } } method testGetQueueInstance { diag("getQueueInstance"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "instance for queue", queue => { username => "testuser", project => "CU", workflow => "Download" }, tables => [ "project", "provenance", "cluster", "instancetype", "queuesample" ], expected => { "memory" => "64", "cluster" => "testuser.CU.Download", "disk" => "20", "instancetype" => "bcf.8c.64g", "cpus" => "8", "ephemeral" => "0", "username" => "testuser" } } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; my $queue = $test->{queue}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $instance = $self->getQueueInstance($queue); is_deeply($instance, $expected, "$testname: $expected->{cluster}") } } method testGetDurations { diag("getDurations"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "average durations for queues", tables => [ "project", "provenance", "queuesample" ], project => "CU", expected => { "testuser.CU.Download" => "200", "testuser.CU.Bwa" => "720", "testuser.CU.FreeBayes" => "2100" } } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $project = $test->{project}; my $expected = $test->{expected}; my $testname = $test->{testname}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues($project); $self->logDebug("queues", $queues); my $durations = $self->getDurations($queues); $self->logDebug("durations", $durations); is_deeply($durations, $expected, $testname) } } method testGetSampleDurations { diag("getSampleDurations"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "durations for sample", sample => "4a438e25-4fa0-4cb4-aa55-591f1f004cfe", workflow => "Download", tables => [ "project", "provenance", "queuesample" ], expected => [ 360, 360 ] } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $sample = $test->{sample}; my $workflow = $test->{workflow}; my $testname = $test->{testname}; my $expected = $test->{expected}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $query = qq{SELECT * FROM provenance WHERE sample='$sample' AND workflow='$workflow' ORDER BY time}; $self->logDebug("query", $query); my $rows = $self->db()->queryhasharray($query); my $durations = $self->getSampleDurations($rows); $self->logDebug("durations", $durations); $self->logDebug("expected", $expected); is_deeply($durations, $expected, "$testname: $sample") } } method testGetQueueDuration { diag("getQueueDuration"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "average duration for queue", tables => [ "project", "provenance", "queuesample" ], expected => [200, 720, 2100, 0] } ]; foreach my $test ( @$tests ) { my $tables = $test->{tables}; my $expected = $test->{expected}; my $testname = $test->{testname}; #### LOAD TABLES foreach my $table ( @$tables ) { $self->logDebug("loading table: $table"); my $query = qq{DELETE FROM $table}; $self->db()->do($query); my $tsvfile = "$Bin/inputs/duration/$table.tsv"; $self->loadTsvFile($table, $tsvfile); } my $queues = $self->getDistinctQueues(); #$self->logDebug("queues", $queues); my $durations = []; for ( my $i = 0; $i < @$queues; $i++ ) { my $queue = $$queues[$i]; my $duration = $self->getQueueDuration($queue); #$self->logDebug("average queue duration", $duration); push @$durations, $duration; ok($duration == $$expected[$i], "$testname $queue->{workflow}: $duration") } } } method testGetSampleDurations { diag("getSampleDurations"); my $rows = [ { "username" => "syoung", "project" => "CU", "workflow" => "Download", "workflownumber"=> "2", "sample" => "2ae8b6c3-99bd-4fe9-a97b-a9026155259f", "time" => "2014-06-27 01:27:56", "status" => "queued", "stdout" => "", "location" => "", "version" => "", "installdir" => "", "stagenumber" => "0", "package" => "", "host" => "", "stage" => "", "stderr" => "" } , { "username" => "syoung", "project" => "CU", "workflow" => "Download", "workflownumber"=> "2", "sample" => "2ae8b6c3-99bd-4fe9-a97b-a9026155259f", "time" => "2014-06-27 01:27:56", "status" => "started", "stdout" => "", "location" => "", "version" => "", "installdir" => "", "stagenumber" => "0", "package" => "", "host" => "", "stage" => "", "stderr" => "" } , { "username" => "syoung", "project" => "CU", "workflow" => "Download", "workflownumber"=> "2", "sample" => "2ae8b6c3-99bd-4fe9-a97b-a9026155259f", "time" => "2014-06-27 01:36:56", "status" => "completed", "stdout" => "", "location" => "", "version" => "", "installdir" => "", "stagenumber" => "0", "package" => "", "host" => "", "stage" => "", "stderr" => "" } ]; my $expected = [540]; my $durations = $self->getSampleDurations($rows); $self->logDebug("durations", $durations); is_deeply($durations, $expected, "sample durations"); } method testParseDate { diag("parseDate"); my $date = "2014-06-12 10:41:15"; my $seconds = $self->parseDate($date); $self->logDebug("seconds", $seconds); my $expected = 1402594875; ok($seconds == $expected, "correct seconds for date: $date"); } method testGetQueues { diag("getQueues"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tests = [ { testname => "return queues for 'running' projects only", projectfile => "$Bin/inputs/getQueues/project.tsv", queuesamplefile => "$Bin/inputs/getQueues/queuesample.tsv", expectedfile => "$Bin/inputs/getQueues/expected.tsv", addedfile => "$Bin/inputs/getQueues/expected-add-Test.tsv" } ]; foreach my $test ( @$tests ) { my $projectfile = $test->{projectfile}; my $queuesamplefile = $test->{queuesamplefile}; my $expectedfile = $test->{expectedfile}; my $addedfile = $test->{addedfile}; my $testname = $test->{testname}; #### CLEAR TABLES my $query = qq{DELETE FROM queuesample}; $self->logDebug("query", $query); $self->db()->do($query); $query = qq{DELETE FROM project}; $self->logDebug("query", $query); $self->db()->do($query); #### LOAD TSVFILES $self->logDebug("BEFORE load tsvfiles"); $self->loadTsvFile("queuesample", $queuesamplefile); $self->loadTsvFile("project", $projectfile); $self->logDebug("AFTER load tsvfiles"); #### SET STATUS TO COMPLETED my $username = "testuser"; my $project = "Test"; $self->setProjectStatus($username, $project, "completed"); #### GET EXPECTED my $fields = $self->db()->fields("queuesample"); my $expected = $self->fileToHasharray($expectedfile, $fields); $self->logDebug("expected", $expected); #### GET QUEUES my $actual = $self->getQueues(); $self->logDebug("actual", $actual); #### VERIFY is_deeply($actual, $expected, $testname); #### SET STATUS TO RUNNING $self->setProjectStatus($username, $project, "running"); #### GET EXPECTED $expected = $self->fileToHasharray($addedfile, $fields); $self->logDebug("expected", $expected); #### GET QUEUES $actual = $self->getQueues(); $self->logDebug("actual", $actual); #### VERIFY is_deeply($actual, $expected, "$testname - added"); } } method testUpdateQueueSamples { diag("updateQueueSamples"); #### SET TEST DATABASE $self->setUpTestDatabase(); #### SAMPLE ID my $sample = "01497a54-775c-479f-a540-d69dd6aa5d8e"; my $query = qq{DELETE FROM queuesample}; $self->db()->do($query); $query = qq{INSERT INTO queuesample VALUES ('syoung'PanCancer', 'Download', '1', '$sample')}; $self->logDebug("query", $query); $self->db()->do($query); my $expected = { username => "syoung", project => "PanCancer", workflow => "Align", workflownumber => 2, sample => $sample, status => "started" }; $self->updateQueueSamples($expected); $query = qq{SELECT * FROM queuesample WHERE sample='$sample'}; my $result = $self->db()->queryhasharray($query); $self->logDebug("result", $result); ok(scalar(@$result) == 1, "one result only"); my $actual = $$result[0]; is_deeply($actual, $expected, "new entry replaced old"); } method testUpdateSamples { diag("updateSamples"); #### SET TEST DATABASE $self->setUpTestDatabase(); #### FRESH START $self->db()->do("DELETE FROM provenance"); $self->db()->do("DELETE FROM queuesample"); #### SET QUEUES my $queues = [ { username => "testuser", project => "PanCancer", workflow => "Download", workflownumber => 1 }, { username => "testuser", project => "PanCancer", workflow => "Split", workflownumber => 2 }, { username => "testuser", project => "PanCancer", workflow => "Align", workflownumber => 3 }]; my $tests = [ { testname => "empty table", tsvfile => "", expectedfile => "$Bin/inputs/updateSamples/expected.tsv" } , { testname => "already populated table - no duplicates", tsvfile => "$Bin/inputs/updateSamples/queuesample.tsv", expectedfile => "$Bin/inputs/updateSamples/expected-added.tsv" } ]; #### PRELOAD 'synapse' ENTRIES INTO FAKE Synapse.pm OBJECT my $assignmentfile = "$Bin/inputs/assignments.txt"; $self->logDebug("assignmentfile", $assignmentfile); my $contents = $self->fileContents($assignmentfile); my @entries = split "\n", $contents; $self->logDebug("No. entries", $#entries + 1); $self->synapse()->outputs([\@entries, \@entries]); foreach my $test ( @$tests ) { my $tsvfile = $test->{tsvfile}; my $testname = $test->{testname}; #### LOAD TABLE my $query = qq{DELETE FROM queuesample}; $self->logDebug("query", $query); $self->db()->do($query); #### LOAD TSVFILE IF NOT EMPTY $self->loadTsvFile("queuesample", $tsvfile) if $tsvfile ne ""; #### UPDATE SAMPLES $self->updateSamples($queues); $query = qq{SELECT * FROM queuesample}; $self->logDebug("query", $query); my $samples = $self->db()->queryhasharray($query); my $expectedfile= $test->{expectedfile}; my $fields = $self->db()->fields("queuesample"); my $expected = $self->fileToHasharray($expectedfile, $fields); is_deeply($samples, $expected, $testname); } } method fileToHasharray ($file, $fields) { $self->logDebug("file", $file); my $hasharray = []; my $contents = $self->fileContents($file); my @lines = split "\n", $contents; foreach my $line ( @lines ) { next if $line =~ /^\s*$/; my $hash; my @elements = split "\t", $line; for ( my $i = 0; $i < @$fields; $i++ ) { my $value = $elements[$i] || ""; $hash->{$$fields[$i]} = $value; } push @$hasharray, $hash; } return $hasharray; } method testUpdateQueueSamples { diag("updateQueueSamples"); #### SET UP DATABASE my $database = $self->conf()->getKey("database:TESTDATABASE", undef); $self->logDebug("database", $database); $self->database($database); $self->setTestDbh(); $self->db()->do("DELETE FROM queuesample"); my $data = { "username" => "testuser", "project" => "PanCancer", "workflow" => "Align", "workflownumber"=> "1", "sample" => "a9012345678", "stage" => "align", "stagenumber"=> "1", "application"=> "sleep", "owner" => "syoung", "package" => "package", "version" => "0.8.0", "installdir"=> "/agua/apps/bioapps", "location" => "bin/test/sleep.sh", "host" => "10.0.2.15", "queued" => "2014-05-03 06:49:30", "started" => "2014-05-03 06:49:30", "completed" => "2014-05-03 06:51:10", "status" => "completed", "stdout" => "ubuntu.example.com\\nSat May 3 06:53:26 UTC 2014\\nCompleted\\n", "stderr" => "" }; ok($self->updateQueueSamples($data), "updated queuesample table"); } method testGetSynapseStatus { diag("getSynapseStatus"); my $data = { "username" => "testuser", "project" => "PanCancer", "workflow" => "Align", "workflownumber"=> "1", "sample" => "a9012345678", "stage" => "align", "stagenumber"=> "1", "application"=> "sleep", "owner" => "syoung", "package" => "package", "version" => "0.8.0", "installdir"=> "/agua/apps/bioapps", "location" => "bin/test/sleep.sh", "host" => "10.0.2.15", "queued" => "2014-05-03 06:49:30", "started" => "2014-05-03 06:49:30", "completed" => "2014-05-03 06:51:10", "status" => "completed", "stdout" => "ubuntu.example.com\\nSat May 3 06:53:26 UTC 2014\\nCompleted\\n", "stderr" => "" }; my $expected = "aligned"; my $synapsestatus = $self->getSynapseStatus($data); $self->logDebug("synapsestatus", $synapsestatus); ok($synapsestatus eq $expected, "aligned"); } method testHandleTopic { diag("handleTopic"); #### HANDLE SEQUENTIAL ADDITIONS TO THE provenance TABLE #### SET TEST DATABASE $self->setUpTestDatabase(); #### SET UP DATABASE my $database = $self->conf()->getKey("database:TESTDATABASE", undef); $self->logDebug("database", $database); $self->database($database); $self->setTestDbh(); my $tests = [ { file => "$Bin/inputs/handleTopic/topic-split.json", testname=> "split topic" } , { file => "$Bin/inputs/handleTopic/topic-align.json", testname=> "align topic" } ]; #### FRESH START $self->db()->do("DELETE FROM provenance"); $self->db()->do("DELETE FROM queuesample"); my $expectedarray = []; foreach my $test ( @$tests ) { my $file = $test->{file}; my $testname = $test->{testname}; $self->logDebug("file", $file); #### GET TEST DATA $self->logDebug("file not found: $file") and die if not -f $file; my $json = $self->fileContents($file); $self->logDebug("json length", length($json)); #### HANDLE TOPIC $self->handleTopic($json); #### SET EXPECTED my $expected = $self->jsonparser()->decode($json); delete $expected->{mode}; delete $expected->{number}; $self->logDebug("expected->owner", $expected->{owner}); $self->logDebug("expected", $expected); push (@$expectedarray, $expected); #### GET ACTUAL my $query = "SELECT * FROM provenance ORDER BY workflownumber DESC"; $self->logDebug("query", $query); my $actualarray = $self->db()->queryhasharray($query); $self->logDebug("actualarray", $actualarray); #### COMPARE is_deeply($actualarray, $expectedarray, "$testname added to provenance table"); } } method testReceiveTopic { diag("receiveTopic"); $self->receiveTopic(); } method testListenTopics { diag("listenTopics"); $self->listenTopics(); } method testMaintainQueue { diag("maintainQueue"); #### SET TEST DATABASE $self->setUpTestDatabase(); my $tsvfile = "$Bin/inputs/queuesample.tsv"; $self->loadTsvFile("queuesample", $tsvfile); my $queuedata = { username => "testuser", project => "PanCancer", workflow => "Sleep", workflownumber => 1, database => "aguatest" }; #my $queuedata = { # username => "syoung", # project => "PanCancer", # workflow => "Align", # workflownumber => 3, # database => "agua" #}; $self->maintainQueue($queuedata); #### TO DO: MOCK OUT QUEUE REPONSES } method testGetNumberQueuedJobs { diag("getNumberQueuedJobs"); my $queuelist = qq{amq.gen-dQQNw7zLy1jLpGMLpnue3g 0 amq.gen-fbZhLQXxwwSxTp6z3Oj0BQ 0 amq.gen-mv6DB2AzWKA9tt8txfcz5g 0 amq.gen-p1uC9ZDwNUCmZr4stDBsEQ 0 amq.gen-pWogrdvCMkSEvJgvBzvFcg 0 amq.gen-pbszDnl91iOfUU0QBNd1Kw 0 amq.gen-xXCpu19zUBC2sZWVXuPOHQ 0 syoung.PanCancer.Align 8 syoung.PanCancer.Download 9 syoung.PanCancer.Split 10 ...done. }; my $tests = [ { testname=> "align queue", queue => "syoung.PanCancer.Align", expected => 8 }, { testname=> "download queue", queue => "syoung.PanCancer.Download", expected => 9 }, { testname=> "split queue", queue => "syoung.PanCancer.Split", expected => 10 }, { testname=> "queue not found - undef expected", queue => "syoung.PanCancer.QueueNotFound", expected => undef } ]; foreach my $test ( @$tests ) { my $queue = $test->{queue}; my $queuedjobs = $self->getNumberQueuedJobs($queuelist, $queue); my $expected = $test->{expected}; $self->logDebug("queuedjobs", $queuedjobs); $self->logDebug("expected", $expected); is_deeply($queuedjobs, $expected, $test->{testname}); } } method testWorkflowStatus { diag("workflowStatus"); my $configfile = "$Bin/inputs/config.yaml"; $self->conf()->inputfile($configfile); $self->workflowStatus(); } method testDownloadPercent { diag("downloadPercent"); my $status = q{Status: 195 GB downloaded (40.401% complete) current rate: /s }; my $expected = "40.401"; my $percent = $self->downloadPercent($status); is($percent, $expected, "percent"); } method testParseUuid { diag("parseUuid"); my $contents = qq{root 18375 0.0 0.0 4400 604 ? S Apr12 0:00 sh -c time /usr/bin/gtdownload \?--max-children 8 \?-c /home/ubuntu/annai-cghub.key \?-v -d \?eba7900a-2e1d-4a55-a3ba-e900be55642e \?-l syslog:full? root 18376 0.0 0.0 4168 348 ? S Apr12 0:00 time /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18377 0.0 0.0 156940 11796 ? S Apr12 0:23 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18378 1.4 0.4 641056 321376 ? Sl Apr12 55:57 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18382 1.5 0.4 641060 324292 ? Sl Apr12 56:36 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18386 1.3 0.4 641064 324900 ? Sl Apr12 51:28 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18390 1.4 0.4 641068 324672 ? Sl Apr12 54:10 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18394 1.6 0.4 641072 323988 ? Sl Apr12 62:22 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18398 1.3 0.4 641076 323128 ? Sl Apr12 50:52 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18402 1.3 0.4 641080 321196 ? Sl Apr12 51:05 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full root 18406 1.4 0.4 641084 325152 ? Sl Apr12 56:02 /usr/bin/gtdownload --max-children 8 -c /home/ubuntu/annai-cghub.key -v -d eba7900a-2e1d-4a55-a3ba-e900be55642e -l syslog:full ubuntu 20477 0.0 0.0 11144 1540 pts/1 Ss+ 13:50 0:00 bash -c ps aux | grep /usr/bin/gtdownload ubuntu 20482 0.0 0.0 8112 920 pts/1 S+ 13:50 0:00 grep /usr/bin/gtdownload }; my @lines = split "\n", $contents; my $expected = "eba7900a-2e1d-4a55-a3ba-e900be55642e"; $self->logDebug("expected", $expected); my $uuid = $self->parseUuid(\@lines); $self->logDebug("uuid", $uuid); ok($uuid eq $expected, "uuid"); } method testRandomHostname { my $randomname = $self->randomHostname("testnode"); $self->logDebug("randomname", $randomname); my $success = $self->hostExists($randomname); $self->logDebug("success", $success); ok($success == 0, "random host name does not exist already"); } method testRandomHexadecimal { my $random = $self->randomHexadecimal(12); $self->logDebug("random", $random); } method fileContents ($file) { $self->logNote("file", $file); return undef if not -f $file; my $contents; open(FILE, $file) or die "Can't open file: $file\n"; { $/ = undef; $contents = <FILE>; } close(FILE) or die "Can't close file: $file\n"; $self->logNote("contents", $contents); return $contents; } method identicalFiles ($actualfile, $expectedfile) { $self->logDebug("actualfile", $actualfile); $self->logDebug("expectedfile", $expectedfile); my $command = "diff -wB $actualfile $expectedfile"; $self->logDebug("command", $command); my $diff = `$command`; return 1 if $diff eq ''; return 0; } method setSynapse { $self->logDebug(""); my $synapse = Test::Synapse->new({ conf => $self->conf(), log => $self->log(), printlog => $self->printlog(), logfile => $self->logfile() }); $self->synapse($synapse); } method setVirtual { my $virtualtype = $self->conf()->getKey("agua", "VIRTUALTYPE"); $self->logDebug("virtualtype", $virtualtype); #### RETURN IF TYPE NOT SUPPORTED $self->logDebug("virtual virtualtype not supported: $virtualtype") and return if $virtualtype !~ /^(openstack|vagrant)$/; #### CREATE DB OBJECT USING DBASE FACTORY my $virtual = Test::Virtual->new( $virtualtype, { conf => $self->conf(), username => $self->username(), logfile => $self->logfile(), log => 2, printlog => 2 } ) or die "Can't create virtual of type: $virtualtype. $!\n"; #$self->logDebug("virtual", $virtual); $self->virtual($virtual); } }
aguadev/aguadev
t/unit/lib/Test/Queue/Master.pm
Perl
mit
35,906
# -*- cperl-indent-level: 4; cperl-continued-brace-offset: -4; cperl-continued-statement-offset: 4 -*- # Copyright (c) 1998-2005 by Jonathan Swartz. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. package HTML::Mason::Interp; use strict; use warnings; use File::Basename; use File::Path; use File::Spec; use File::Temp; use HTML::Mason; use HTML::Mason::Escapes; use HTML::Mason::Request; use HTML::Mason::Resolver::File; use HTML::Mason::Tools qw(read_file taint_is_on load_pkg); use HTML::Mason::Exceptions( abbr => [qw(param_error system_error wrong_compiler_error compilation_error error)] ); use Params::Validate qw(:all); Params::Validate::validation_options( on_fail => sub { param_error join '', @_ } ); use Class::Container; use base qw(Class::Container); BEGIN { # Fields that can be set in new method, with defaults __PACKAGE__->valid_params ( autohandler_name => { parse => 'string', default => 'autohandler', type => SCALAR, descr => "The filename to use for Mason's 'autohandler' capability" }, buffer_preallocate_size => { parse => 'string', default => 0, type => SCALAR, descr => "Number of bytes to preallocate in request buffer" }, code_cache_max_size => { parse => 'string', default => 'unlimited', type => SCALAR, descr => "The maximum number of components in the code cache" }, comp_root => { parse => 'list', type => SCALAR|ARRAYREF, default => File::Spec->rel2abs( Cwd::cwd ), descr => "A string or array of arrays indicating the search path for component calls" }, compiler => { isa => 'HTML::Mason::Compiler', descr => "A Compiler object for compiling components" }, data_dir => { parse => 'string', optional => 1, type => SCALAR, descr => "A directory for storing cache files and other state information" }, dynamic_comp_root => { parse => 'boolean', default => 0, type => BOOLEAN, descr => "Indicates whether the comp_root may be changed between requests" }, escape_flags => { parse => 'hash_list', optional => 1, type => HASHREF, descr => "A list of escape flags to set (as if calling the set_escape() method" }, object_file_extension => { parse => 'string', type => SCALAR, default => '.obj', descr => "Extension to add to the end of object files" }, # OBJECT cause qr// returns an object ignore_warnings_expr => { parse => 'string', type => SCALAR|OBJECT, default => qr/Subroutine .* redefined/i, descr => "A regular expression describing Perl warning messages to ignore" }, preloads => { parse => 'list', optional => 1, type => ARRAYREF, descr => "A list of components to load immediately when creating the Interpreter" }, resolver => { isa => 'HTML::Mason::Resolver', descr => "A Resolver object for fetching components from storage" }, static_source => { parse => 'boolean', default => 0, type => BOOLEAN, descr => "When true, we only compile source files once" }, static_source_touch_file => { parse => 'string', optional => 1, type => SCALAR, descr => "A file that, when touched, causes Mason to clear its component caches" }, use_object_files => { parse => 'boolean', default => 1, type => BOOLEAN, descr => "Whether to cache component objects on disk" }, ); __PACKAGE__->contained_objects ( resolver => { class => 'HTML::Mason::Resolver::File', descr => "This class is expected to return component information based on a component path" }, compiler => { class => 'HTML::Mason::Compiler::ToObject', descr => "This class is used to translate component source into code" }, request => { class => 'HTML::Mason::Request', delayed => 1, descr => "Objects returned by make_request are members of this class" }, ); } use HTML::Mason::MethodMaker ( read_only => [ qw( autohandler_name buffer_preallocate_size code_cache code_cache_min_size code_cache_max_size compiler data_dir dynamic_comp_root object_file_extension preallocated_output_buffer preloads resolver source_cache static_source static_source_touch_file use_internal_component_caches use_object_files ) ], read_write => [ map { [ $_ => __PACKAGE__->validation_spec->{$_} ] } qw( ignore_warnings_expr ) ], read_write_contained => { request => [ [ autoflush => { type => BOOLEAN } ], [ data_cache_api => { type => SCALAR } ], [ data_cache_defaults => { type => HASHREF } ], [ dhandler_name => { type => SCALAR } ], [ error_format => { type => SCALAR } ], [ error_mode => { type => SCALAR } ], [ max_recurse => { type => SCALAR } ], [ out_method => { type => SCALARREF | CODEREF } ], [ plugins => { type => ARRAYREF } ], ] }, ); sub new { my $class = shift; my $self = $class->SUPER::new(@_); $self->_initialize; return $self; } sub _initialize { my ($self) = shift; $self->{code_cache} = {}; $self->{source_cache} = {}; $self->{files_written} = []; $self->{static_source_touch_file_lastmod} = 0; $self->_assign_comp_root($self->{comp_root}); $self->_check_data_dir(); $self->_create_data_subdirs(); $self->_initialize_escapes(); # # Create preallocated buffer for requests. # $self->{preallocated_output_buffer} = ' ' x $self->buffer_preallocate_size; $self->_set_code_cache_attributes(); # # If static_source=1, unlimited_code_cache=1, and # dynamic_comp_root=0, we can safely cache component objects keyed # on path throughout the framework (e.g. within other component # objects). These internal caches can be cleared in # $interp->flush_code_cache (the only legimiate place for a # component to be eliminated from the cache), eliminating any # chance for leaked objects. # # static_source has to be on or else we might keep around # old versions of components that have changed. # # unlimited_code_cache has to be on or else we might leak # components when we discard. # # dynamic_comp_root has to be 0 because the cache would not be # valid for different combinations of component root across # different requests. # $self->{use_internal_component_caches} = ($self->{static_source} && $self->{unlimited_code_cache} && !$self->{dynamic_comp_root}); $self->_preload_components(); } sub _check_data_dir { my $self = shift; return unless $self->{data_dir}; $self->{data_dir} = File::Spec->canonpath( $self->{data_dir} ); param_error "data_dir '$self->{data_dir}' must be an absolute directory" unless File::Spec->file_name_is_absolute( $self->{data_dir} ); } sub _create_data_subdirs { my $self = shift; if ($self->data_dir) { $self->_make_object_dir; $self->_make_cache_dir; } else { $self->{use_object_files} = 0; } } sub _initialize_escapes { my $self = shift; # # Add the escape flags (including defaults) # foreach ( [ h => \&HTML::Mason::Escapes::html_entities_escape ], [ u => \&HTML::Mason::Escapes::url_escape ], ) { $self->set_escape(@$_); } if ( my $e = delete $self->{escape_flags} ) { while ( my ($flag, $code) = each %$e ) { $self->set_escape( $flag => $code ); } } } sub _set_code_cache_attributes { my $self = shift; $self->{unlimited_code_cache} = ($self->{code_cache_max_size} eq 'unlimited'); unless ($self->{unlimited_code_cache}) { $self->{code_cache_min_size} = $self->{code_cache_max_size} * 0.75; } } sub _preload_components { my $self = shift; return unless $self->preloads; foreach my $pattern (@{$self->preloads}) { error "preload pattern '$pattern' must be an absolute path" unless File::Spec->file_name_is_absolute($pattern); my %path_hash; foreach my $pair ($self->comp_root_array) { my $root = $pair->[1]; foreach my $path ($self->resolver->glob_path($pattern, $root)) { $path_hash{$path}++; } } my @paths = keys(%path_hash); warn "Didn't find any components for preload pattern '$pattern'" unless @paths; foreach (@paths) { $self->load($_) or error "Cannot load component $_, found via pattern $pattern"; } } } # # Functions for retrieving and creating data subdirectories. # sub object_dir { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'obj' ) : ''; } sub object_create_marker_file { my $self = shift; return $self->object_dir ? File::Spec->catfile($self->object_dir, '.__obj_create_marker') : ''; } sub cache_dir { my $self = shift; return $self->data_dir ? File::Spec->catdir( $self->data_dir, 'cache' ) : ''; } sub _make_data_subdir { my ($self, $dir) = @_; unless (-d $dir) { my @newdirs = eval { mkpath( $dir, 0, 0775 ) }; if ($@) { my $user = getpwuid($<); my $group = getgrgid($(); my $data_dir = $self->data_dir; error "Cannot create directory '$dir' ($@) for user '$user', group '$group'. " . "Perhaps you need to create or set permissions on your data_dir ('$data_dir'). "; } $self->push_files_written(@newdirs); } } sub _make_object_dir { my ($self) = @_; my $object_dir = $self->object_dir; $self->_make_data_subdir($object_dir); my $object_create_marker_file = $self->object_create_marker_file; unless (-f $object_create_marker_file) { open my $fh, ">$object_create_marker_file" or system_error "Could not create '$object_create_marker_file': $!"; $self->push_files_written($object_create_marker_file); } } sub _make_cache_dir { my ($self) = @_; my $cache_dir = $self->cache_dir; $self->_make_data_subdir($cache_dir); } # # exec is the initial entry point for executing a component # in a new request. # sub exec { my $self = shift; my $comp = shift; $self->make_request(comp=>$comp, args=>\@_)->exec; } sub make_request { my $self = shift; return $self->create_delayed_object( 'request', interp => $self, @_ ); } sub comp_exists { my ($self, $path) = @_; return $self->resolve_comp_path_to_source($path); } # # Load <$path> into a component, possibly parsing the source and/or # caching the code. Returns a component object or undef if the # component was not found. # sub load { my ($self, $path) = @_; my ($maxfilemod, $objfile, $objfilemod); my $code_cache = $self->{code_cache}; my $resolver = $self->{resolver}; # # Path must be absolute. # unless (substr($path, 0, 1) eq '/') { error "Component path given to Interp->load must be absolute (was given $path)"; } # # Get source info from resolver. # my $source = $self->resolve_comp_path_to_source($path); # No component matches this path. return unless defined $source; # comp_id is the unique name for the component, used for cache key # and object file name. my $comp_id = $source->comp_id; # # Get last modified time of source. # my $srcmod = $source->last_modified; # # If code cache contains an up to date entry for this path, use # the cached comp. Always use the cached comp in static_source # mode. # if ( exists $code_cache->{$comp_id} && ( $self->static_source || $code_cache->{$comp_id}->{lastmod} >= $srcmod ) ) { return $code_cache->{$comp_id}->{comp}; } if ($self->{use_object_files}) { $objfile = $self->comp_id_to_objfile($comp_id); my @stat = stat $objfile; if ( @stat && ! -f _ ) { error "The object file '$objfile' exists but it is not a file!"; } if ($self->static_source) { # No entry in the code cache so if the object file exists, # we will use it, otherwise we must create it. These # values make that happen. $objfilemod = @stat ? $srcmod : 0; } else { # If the object file exists, get its modification time. # Otherwise (it doesn't exist or it is a directory) we # must create it. $objfilemod = @stat ? $stat[9] : 0; } } my $comp; if ($objfile) { # # We are using object files. Update object file if necessary # and load component from there. # # If loading the object file generates an error, or results in # a non-component object, try regenerating the object file # once before giving up and reporting an error. This can be # handy in the rare case of an empty or corrupted object file. # if ($objfilemod < $srcmod) { $self->compiler->compile_to_file( file => $objfile, source => $source); } $comp = eval { $self->eval_object_code( object_file => $objfile ) }; if (!UNIVERSAL::isa($comp, 'HTML::Mason::Component')) { $self->compiler->compile_to_file( file => $objfile, source => $source); $comp = eval { $self->eval_object_code( object_file => $objfile ) }; if (!UNIVERSAL::isa($comp, 'HTML::Mason::Component')) { my $error = $@ ? $@ : "Could not get HTML::Mason::Component object from object file '$objfile'"; $self->_compilation_error( $source->friendly_name, $error ); } } } else { # # Not using object files. Load component directly into memory. # my $object_code = $source->object_code( compiler => $self->compiler ); $comp = eval { $self->eval_object_code( object_code => $object_code ) }; $self->_compilation_error( $source->friendly_name, $@ ) if $@; } $comp->assign_runtime_properties($self, $source); # # Delete any stale cached version of this component, then # cache it. # $self->delete_from_code_cache($comp_id); $code_cache->{$comp_id} = { lastmod => $srcmod, comp => $comp }; return $comp; } sub delete_from_code_cache { my ($self, $comp_id) = @_; return unless defined $self->{code_cache}{$comp_id}{comp}; delete $self->{code_cache}{$comp_id}; return; } sub comp_id_to_objfile { my ($self, $comp_id) = @_; return File::Spec->catfile ( $self->object_dir, $self->compiler->object_id, ( split /\//, $comp_id ), ) . $self->object_file_extension; } # # Empty in-memory code cache. # sub flush_code_cache { my $self = shift; # Necessary for preventing memory leaks if ($self->use_internal_component_caches) { foreach my $entry (values %{$self->{code_cache}}) { my $comp = $entry->{comp}; $comp->flush_internal_caches; } } $self->{code_cache} = {}; $self->{source_cache} = {}; } # # If code cache has exceeded maximum, remove least frequently used # elements from cache until size falls below minimum. # sub purge_code_cache { my ($self) = @_; return if $self->{unlimited_code_cache}; my $current_size = scalar(keys(%{$self->{code_cache}})); if ($current_size > $self->code_cache_max_size) { my $code_cache = $self->{code_cache}; my $min_size = $self->code_cache_min_size; my $decay_factor = 0.75; my @elems; while (my ($path,$href) = each(%{$code_cache})) { push(@elems,[$path,$href->{comp}->mfu_count,$href->{comp}]); } @elems = sort { $a->[1] <=> $b->[1] } @elems; while (($current_size > $min_size) and @elems) { $self->delete_from_code_cache(shift(@elems)->[0]); $current_size--; } # # Multiply each remaining cache item's count by a decay factor, # to gradually reduce impact of old information. # foreach my $elem (@elems) { $elem->[2]->mfu_count( $elem->[2]->mfu_count * $decay_factor ); } } } # # Clear the object directory of all current files and subdirectories. # Do this by renaming the object directory to a temporary name, # immediately recreating an empty object directory, then removing # the empty object directory. If another process tries to write # the object file in between these steps, it'll create the top # object directory instead. # # Would be nice to fork off a separate process to do the removing so # that it doesn't affect a request's response time, but difficult to # do this in an environment-generic way. # sub remove_object_files { my $self = shift; my $object_dir = $self->object_dir; if (-d $object_dir) { my $temp_dir = File::Temp::tempdir(DIR => $self->data_dir); rename($object_dir, File::Spec->catdir( $temp_dir, 'target' ) ) or die "could not rename '$object_dir' to '$temp_dir': $@"; $self->_make_object_dir(); rmtree($temp_dir); } else { $self->_make_object_dir(); } } # # Check the static_source_touch_file, if one exists, to see if it has # changed since we last checked. If it has, clear the code cache and # object files if appropriate. # sub check_static_source_touch_file { my $self = shift; if (my $touch_file = $self->static_source_touch_file) { return unless -f $touch_file; my $touch_file_lastmod = (stat($touch_file))[9]; if ($touch_file_lastmod > $self->{static_source_touch_file_lastmod}) { # File has been touched since we last checked. First, # clear the object file directory if the last mod of # its ._object_create_marker is earlier than the touch file, # or if the marker doesn't exist. # if ($self->use_object_files) { my $object_create_marker_file = $self->object_create_marker_file; if (!-e $object_create_marker_file || (stat($object_create_marker_file))[9] < $touch_file_lastmod) { $self->remove_object_files; } } # Next, clear the in-memory component cache. # $self->flush_code_cache; # Reset lastmod value. # $self->{static_source_touch_file_lastmod} = $touch_file_lastmod; } } } # # Construct a component on the fly. Virtual if 'path' parameter is # given, otherwise anonymous. # sub make_component { my $self = shift; my %p = validate(@_, { comp_source => { type => SCALAR, optional => 1 }, comp_file => { type => SCALAR, optional => 1 }, name => { type => SCALAR, optional => 1 } }); $p{comp_source} = read_file(delete $p{comp_file}) if exists $p{comp_file}; param_error "Must specify either 'comp_source' or 'comp_file' parameter to 'make_component()'" unless defined $p{comp_source}; $p{name} ||= '<anonymous component>'; my $source = HTML::Mason::ComponentSource->new( friendly_name => $p{name}, comp_path => $p{name}, comp_id => undef, last_modified => time, comp_class => 'HTML::Mason::Component', source_callback => sub { $p{comp_source} }, ); my $object_code = $source->object_code( compiler => $self->compiler); my $comp = eval { $self->eval_object_code( object_code => $object_code ) }; $self->_compilation_error( $p{name}, $@ ) if $@; $comp->assign_runtime_properties($self, $source); return $comp; } sub set_global { my ($self, $decl, @values) = @_; param_error "Interp->set_global: expects a variable name and one or more values" unless @values; my ($prefix, $name) = ($decl =~ s/^([\$@%])//) ? ($1, $decl) : ('$', $decl); my $varname = sprintf("%s::%s",$self->compiler->in_package,$name); no strict 'refs'; if ($prefix eq '$') { $$varname = $values[0]; } elsif ($prefix eq '@') { @$varname = @values; } else { %$varname = @values; } } sub comp_root { my $self = shift; if (my $new_comp_root = shift) { die "cannot assign new comp_root unless dynamic_comp_root parameter is set" unless $self->dynamic_comp_root; $self->_assign_comp_root($new_comp_root); } if (@{$self->{comp_root}} == 1 and $self->{comp_root}[0][0] eq 'MAIN') { return $self->{comp_root}[0][1]; } else { return $self->{comp_root}; } } sub comp_root_array { return @{ $_[0]->{comp_root} }; } sub _assign_comp_root { my ($self, $new_comp_root) = @_; # Force into lol format. if (!ref($new_comp_root)) { $new_comp_root = [[ MAIN => $new_comp_root ]]; } elsif (ref($new_comp_root) ne 'ARRAY') { die "Component root $new_comp_root must be a scalar or array reference"; } # Validate key/path pairs, and check to see if any of them # conflict with old pairs. my $comp_root_key_map = $self->{comp_root_key_map} ||= {}; foreach my $pair (@$new_comp_root) { param_error "Multiple-path component root must consist of a list of two-element lists" if ref($pair) ne 'ARRAY'; param_error "Component root key '$pair->[0]' cannot contain slash" if $pair->[0] =~ /\//; $pair->[1] = File::Spec->canonpath( $pair->[1] ); param_error "comp_root path '$pair->[1]' is not an absolute directory" unless File::Spec->file_name_is_absolute( $pair->[1] ); my ($key, $path) = @$pair; if (my $orig_path = $comp_root_key_map->{$key}) { if ($path ne $orig_path) { die "comp_root key '$key' was originally associated with '$path', cannot change to '$orig_path'"; } } else { $comp_root_key_map->{$key} = $path; } } $self->{comp_root} = $new_comp_root; } sub resolve_comp_path_to_source { my ($self, $path) = @_; my $source; if ($self->{static_source}) { # Maintain a separate source_cache for each component root, # because the set of active component roots can change # from request to request. # my $source_cache = $self->{source_cache}; foreach my $pair (@{$self->{comp_root}}) { my $source_cache_for_root = $source_cache->{$pair->[0]} ||= {}; unless (exists($source_cache_for_root->{$path})) { $source_cache_for_root->{$path} = $self->{resolver}->get_info($path, @$pair); } last if $source = $source_cache_for_root->{$path}; } } else { my $resolver = $self->{resolver}; foreach my $pair ($self->comp_root_array) { last if $source = $resolver->get_info($path, @$pair); } } return $source; } sub files_written { my $self = shift; return @{$self->{files_written}}; } # # Push onto list of written files. # sub push_files_written { my $self = shift; my $fref = $self->{'files_written'}; push(@$fref,@_); } # # Look for component <$name> starting in <$startpath> and moving upwards # to the root. Return component object or undef. # sub find_comp_upwards { my ($self, $startpath, $name) = @_; $startpath =~ s{/+$}{}; # Don't use File::Spec here, this is a URL path. do { my $comp = $self->load("$startpath/$name"); return $comp if $comp; } while $startpath =~ s{/+[^/]*$}{}; return; # Nothing found } ################################################################### # The eval_object_code & write_object_file methods used to be in # Parser.pm. This is a temporary home only. They need to be moved # again at some point in the future (during some sort of interp # re-architecting). ################################################################### # # eval_object_code # (object_code, object_file, error) # Evaluate an object file or object text. Return a component object # or undef if error. # # I think this belongs in the resolver (or comp loader) - Dave # sub eval_object_code { my ($self, %p) = @_; # # Evaluate object file or text with warnings on, unless # ignore_warnings_expr is '.'. # my $ignore_expr = $self->ignore_warnings_expr; my ($comp, $err); my $warnstr = ''; { local $^W = $ignore_expr eq '.' ? 0 : 1; local $SIG{__WARN__} = ( $ignore_expr ? ( $ignore_expr eq '.' ? sub { } : sub { $warnstr .= $_[0] if $_[0] !~ /$ignore_expr/ } ) : sub { $warnstr .= $_[0] } ); $comp = $self->_do_or_eval(\%p); } $err = $warnstr . $@; # # Return component or error # if ($err) { # attempt to stem very long eval errors $err =~ s/has too many errors\..+/has too many errors./s; compilation_error $err; } else { return $comp; } } sub _do_or_eval { my ($self, $p) = @_; if ($p->{object_file}) { return do $p->{object_file}; } else { # If in taint mode, untaint the object text (${$p->{object_code}}) = ${$p->{object_code}} =~ /^(.*)/s if taint_is_on; return eval ${$p->{object_code}}; } } sub _compilation_error { my ($self, $filename, $err) = @_; HTML::Mason::Exception::Compilation->throw(error=>$err, filename=>$filename); } sub object_file { my ($self, $comp) = @_; return $comp->persistent ? $self->comp_id_to_objfile($comp->comp_id) : undef; } sub use_autohandlers { my $self = shift; return defined $self->{autohandler_name} and length $self->{autohandler_name}; } # Generate HTML that describes Interp's current status. # This is used in things like Apache::Status reports. Currently shows: # -- Interp properties # -- loaded (cached) components sub status_as_html { my ($self, %p) = @_; # Should I be scared about this? =) my $comp_source = <<'EOF'; <h3>Interpreter properties:</h3> <blockquote> <h4>Startup options:</h4> <tt> <table width="100%"> <%perl> foreach my $property (sort keys %$interp) { my $val = $interp->{$property}; my $default = ( defined $val && defined $valid{$property}{default} && $val eq $valid{$property}{default} ) || ( ! defined $val && exists $valid{$property}{default} && ! defined $valid{$property}{default} ); my $display = $val; if (ref $val) { $display = '<font color="darkred">'; # only object can ->can, others die my $is_object = eval { $val->can('anything'); 1 }; if ($is_object) { $display .= ref $val . ' object'; } else { if (UNIVERSAL::isa($val, 'ARRAY')) { $display .= 'ARRAY reference - [ '; $display .= join ', ', @$val; $display .= '] '; } elsif (UNIVERSAL::isa($val, 'HASH')) { $display .= 'HASH reference - { '; my @pairs; while (my ($k, $v) = each %$val) { push @pairs, "$k => $v"; } $display .= join ', ', @pairs; $display .= ' }'; } else { $display = ref $val . ' reference'; } } $display .= '</font>'; } defined $display && $display =~ s,([\x00-\x1F]),'<font color="purple">control-' . chr( ord('A') + ord($1) - 1 ) . '</font>',eg; # does this work for non-ASCII? </%perl> <tr valign="top" cellspacing="10"> <td> <% $property | h %> </td> <td> <% defined $display ? $display : '<i>undef</i>' %> <% $default ? '<font color=green>(default)</font>' : '' %> </td> </tr> % } </table> </tt> <h4>Components in memory cache:</h4> <tt> % my $cache; % if ($cache = $interp->code_cache and %$cache) { % foreach my $key (sort keys %$cache) { <% $key |h%> (modified <% scalar localtime $cache->{$key}->{lastmod} %>) <br> % } % } else { <I>None</I> % } </tt> </blockquote> <%args> $interp # The interpreter we'll elucidate %valid # Default values for interp member data </%args> EOF my $comp = $self->make_component(comp_source => $comp_source); my $out; my $args = [interp => $self, valid => $self->validation_spec]; $self->make_request(comp=>$comp, args=>$args, out_method=>\$out, %p)->exec; return $out; } sub set_escape { my $self = shift; my %p = @_; while ( my ($name, $sub) = each %p ) { my $flag_regex = $self->compiler->lexer->escape_flag_regex; param_error "Invalid escape name ($name)" if $name !~ /^$flag_regex$/ || $name =~ /^n$/; my $coderef; if ( ref $sub ) { $coderef = $sub; } else { if ( $sub =~ /^\w+$/ ) { no strict 'refs'; unless ( defined &{"HTML::Mason::Escapes::$sub"} ) { param_error "Invalid escape: $sub (no matching subroutine in HTML::Mason::Escapes"; } $coderef = \&{"HTML::Mason::Escapes::$sub"}; } else { $coderef = eval $sub; param_error "Invalid escape: $sub ($@)" if $@; } } $self->{escapes}{$name} = $coderef; } } sub remove_escape { my $self = shift; delete $self->{escapes}{ shift() }; } sub apply_escapes { my $self = shift; my $text = shift; foreach my $flag (@_) { param_error "Invalid escape flag: $flag" unless exists $self->{escapes}{$flag}; $self->{escapes}{$flag}->(\$text); } return $text; } 1; __END__ =head1 NAME HTML::Mason::Interp - Mason Component Interpreter =head1 SYNOPSIS my $i = HTML::Mason::Interp->new (data_dir=>'/usr/local/mason', comp_root=>'/usr/local/www/htdocs/', ...other params...); =head1 DESCRIPTION Interp is the Mason workhorse, executing components and routing their output and errors to all the right places. In a mod_perl environment, Interp objects are handed off immediately to an ApacheHandler object which internally calls the Interp implementation methods. In that case the only user method is the new() constructor. =head1 PARAMETERS TO THE new() CONSTRUCTOR =over =item autohandler_name File name used for L<autohandlers|HTML::Mason::Devel/autohandlers>. Default is "autohandler". If this is set to an empty string ("") then autohandlers are turned off entirely. =item buffer_preallocate_size =for html <a name="item_buffer_preallocate_size"></a> Number of bytes to preallocate in the output buffer for each request. Defaults to 0. Setting this to, say, your maximum page size (or close to it) can reduce the number of reallocations Perl performs as components add to the output buffer. =item code_cache_max_size =for html <a name="item_code_cache_max_size"></a> Specifies the maximum number of components that should be held in the in-memory code cache. The default is 'unlimited', meaning no components will ever be discarded; Mason can perform certain optimizations in this mode. Setting this to zero disables the code cache entirely. See the L<code cache|HTML::Mason::Admin/code cache> section of the administrator's manual for further details. =item comp_root =for html <a name="item_comp_root"></a> The component root marks the top of your component hierarchy and defines how component paths are translated into real file paths. For example, if your component root is F</usr/local/httpd/docs>, a component path of F</products/index.html> translates to the file F</usr/local/httpd/docs/products/index.html>. Under L<Apache|HTML::Mason::ApacheHandler> and L<CGI|HTML::Mason::CGIHandler>, comp_root defaults to the server's document root. In standalone mode comp_root defaults to the current working directory. This parameter may be either a scalar or an array reference. If it is a scalar, it should be a filesystem path indicating the component root. If it is an array reference, it should be of the following form: [ [ foo => '/usr/local/foo' ], [ bar => '/usr/local/bar' ] ] This is an array of two-element array references, not a hash. The "keys" for each path must be unique and their "values" must be filesystem paths. These paths will be searched in the provided order whenever a component path is resolved. For example, given the above component roots and a component path of F</products/index.html>, Mason would search first for F</usr/local/foo/products/index.html>, then for F</usr/local/bar/products/index.html>. The keys are used in several ways. They help to distinguish component caches and object files between different component roots, and they appear in the C<title()> of a component. When you specify a single path for a component root, this is actually translated into [ [ MAIN => path ] ] If you have turned on L<dynamic_comp_root|HTML::Mason::Params/dynamic_comp_root>, you may modify the component root(s) of an interpreter between requests by calling C<$interp-E<gt>comp_root> with a value. However, the path associated with any given key may not change between requests. For example, if the initial component root is [ [ foo => '/usr/local/foo' ], [ bar => '/usr/local/bar' ], ] then it may not be changed to [ [ foo => '/usr/local/bar' ], [ bar => '/usr/local/baz' ], but it may be changed to [ [ foo => '/usr/local/foo' ], [ blarg => '/usr/local/blarg' ] ] In other words, you may add or remove key/path pairs but not modify an already-used key/path pair. The reason for this restriction is that the interpreter maintains a component cache per key that would become invalid if the associated paths were to change. =item compiler The Compiler object to associate with this Interpreter. By default a new object of class L<compiler_class|HTML::Mason::Params/compiler_class> will be created. =item compiler_class The class to use when creating a compiler. Defaults to L<HTML::Mason::Compiler|HTML::Mason::Compiler>. =item data_dir The data directory is a writable directory that Mason uses for various features and optimizations: for example, component object files and data cache files. Mason will create the directory on startup, if necessary, and set its permissions according to the web server User/Group. Under L<Apache|HTML::Mason::ApacheHandler>, data_dir defaults to a directory called "mason" under the Apache server root. You will need to change this on certain systems that assign a high-level server root such as F</usr>! In non-Apache environments, data_dir has no default. If it is left unspecified, Mason will not use L<object files|HTML::Mason::Admin/object files>, and the default L<data cache class|HTML::Mason::Request/item_cache> will be C<MemoryCache> instead of C<FileCache>. =item dynamic_comp_root True or false, defaults to false. Indicates whether the L<comp_root|HTML::Mason::Params/comp_root> can be modified on this interpreter between requests. Mason can perform a few optimizations with a fixed component root, so you should only set this to true if you actually need it. =item escape_flags A hash reference of escape flags to set for this object. See the section on the L<set_escape method|HTML::Mason::Interp/item_set_escape> for more details. =item ignore_warnings_expr Regular expression indicating which warnings to ignore when loading components. Any warning that is not ignored will prevent the component from being loaded and executed. For example: ignore_warnings_expr => 'Global symbol.*requires explicit package' If set to undef, all warnings are heeded. If set to '.', warnings are turned off completely as a specially optimized case. By default, this is set to 'Subroutine .* redefined'. This allows you to declare global subroutines inside <%once> sections and not receive an error when the component is reloaded. =item object_file_extension Extension to add to the end of object files. Default is ".obj". =item preloads A list of component paths, optionally with glob wildcards, to load when the interpreter initializes. e.g. preloads => ['/foo/index.html','/bar/*.pl'] Default is the empty list. For maximum performance, this should only be used for components that are frequently viewed and rarely updated. See the L<preloading components|HTML::Mason::Admin/preloading components> section of the administrator's manual for further details. As mentioned in the developer's manual, a component's C<< <%once> >> section is executed when it is loaded. For preloaded components, this means that this section will be executed before a Mason or Apache request exist, so preloading a component that uses C<$m> or C<$r> in a C<< <%once> >> section will fail. =item request_class The class to use when creating requests. Defaults to L<HTML::Mason::Request|HTML::Mason::Request>. =item resolver The Resolver object to associate with this Compiler. By default a new object of class L<resolver_class|HTML::Mason::Params/resolver_class> will be created. =item resolver_class The class to use when creating a resolver. Defaults to L<HTML::Mason::Resolver::File|HTML::Mason::Resolver::File>. =item static_source True or false, default is false. When false, Mason checks the timestamp of the component source file each time the component is used to see if it has changed. This provides the instant feedback for source changes that is expected for development. However it does entail a file stat for each component executed. When true, Mason assumes that the component source tree is unchanging: it will not check component source files to determine if the memory cache or object file has expired. This can save many file stats per request. However, in order to get Mason to recognize a component source change, you must flush the memory cache and remove object files. See L<static_source_touch_file|HTML::Mason::Params/static_source_touch_file> for one easy way to arrange this. We recommend turning this mode on in your production sites if possible, if performance is of any concern. =item static_source_touch_file Specifies a filename that Mason will check once at the beginning of of every request. When the file timestamp changes, Mason will (1) clear its in-memory component cache, and (2) remove object files if they have not already been deleted by another process. This provides a convenient way to implement L<static_source|HTML::Mason::Params/static_source> mode. All you need to do is make sure that a single file gets touched whenever components change. For Mason's part, checking a single file at the beginning of a request is much cheaper than checking every component file when static_source=0. =item use_object_files True or false, default is true. Specifies whether Mason creates object files to save the results of component parsing. You may want to turn off object files for disk space reasons, but otherwise this should be left alone. =back =head1 ACCESSOR METHODS All of the above properties have standard accessor methods of the same name. Only comp_root and ignore_warnings_expr can be modified in an existing interpreter; the rest are read-only. =head1 ESCAPE FLAG METHODS =over =item apply_escapes ($text, $flags, [more flags...]) =for html <a name="item_apply_escapes"></a> This method applies a one or more escapes to a piece of text. The escapes are specified by giving their flag. Each escape is applied to the text in turn, after which the now-modified text is returned. =item remove_escape ($name) =for html <a name="item_remove_escape"></a> Given an escape name, this removes that escape from the interpreter's known escapes. If the name is not recognized, it is simply ignored. =item set_escape ($name => see below]) =for html <a name="item_set_escape"></a> This method is called to add an escape flag to the list of known escapes for the interpreter. The flag may only consist of the characters matching C<\w> and the dash (-). It must start with an alpha character or an underscore (_). The right hand side may be one of several things. It can be a subroutine reference. It can also be a string match C</^\w+$/>, in which case it is assumed to be the name of a subroutine in the C<HTML::Mason::Escapes> module. Finally, if it is a string that does not match the above regex, then it is assumed to be C<eval>able code, which will return a subroutine reference. When setting these with C<PerlSetVar> directives in an Apache configuration file, you can set them like this: PerlSetVar MasonEscapeFlags "h => \&HTML::Mason::Escapes::basic_html_escape" PerlSetVar MasonEscapeFlags "flag => \&subroutine" PerlSetVar MasonEscapeFlags "uc => sub { ${$_[0]} = uc ${$_[0]}; }" PerlAddVar MasonEscapeFlags "thing => other_thing" =back =head1 OTHER METHODS =over =item comp_exists (path) =for html <a name="item_comp_exists"></a> Given an I<absolute> component path, this method returns a boolean value indicating whether or not a component exists for that path. =item exec (comp, args...) =for html <a name="item_exec"></a> Creates a new HTML::Mason::Request object for the given I<comp> and I<args>, and executes it. The return value is the return value of I<comp>, if any. This is useful for running Mason outside of a web environment. See L<HTML::Mason::Admin/using Mason from a standalone script> for examples. This method isn't generally useful in a mod_perl environment; see L<subrequests|HTML::Mason::Devel/Subrequests> instead. =item flush_code_cache =for html <a name="flush_code_cache"></a> Empties the component cache. When using Perl 5.00503 or earlier, you should call this when finished with an interpreter, in order to remove circular references that would prevent the interpreter from being destroyed. =item load (path) =for html <a name="item_load"></a> Returns the component object corresponding to an absolute component C<path>, or undef if none exists. Dies with an error if the component fails to load because of a syntax error. =item make_component (comp_source => ... ) =item make_component (comp_file => ... ) =for html <a name="item_make_component"></a> This method compiles Mason component source code and returns a Component object. The source may be passed in as a string in C<comp_source>, or as a filename in C<comp_file>. When using C<comp_file>, the filename is specified as a path on the file system, not as a path relative to Mason's component root (see L<$m-E<gt>fetch_comp|HTML::Mason::Request/item_fetch_comp> for that). If Mason encounters an error during processing, an exception will be thrown. Example of usage: # Make an anonymous component my $anon_comp = eval { $interp->make_component ( comp_source => '<%perl>my $name = "World";</%perl>Hello <% $name %>!' ) }; die $@ if $@; $m->comp($anon_comp); =item make_request (@request_params) =for html <a name="item_make_request"></a> This method creates a Mason request object. The arguments to be passed are the same as those for the C<< HTML::Mason::Request->new >> constructor or its relevant subclass. This method will likely only be of interest to those attempting to write new handlers or to subclass C<HTML::Mason::Interp>. If you want to create a I<subrequest>, see L<subrequests|HTML::Mason::Devel/Subrequests> instead. =item purge_code_cache () =for html <a name="purge_code_cache"></a> Called during request execution in order to clear out the code cache. Mainly useful to subclasses that may want to take some custom action upon clearing the cache. =item set_global ($varname, [values...]) =for html <a name="item_set_global"></a> This method sets a global to be used in components. C<varname> is a variable name, optionally preceded with a prefix (C<$>, C<@>, or C<%>); if the prefix is omitted then C<$> is assumed. C<varname> is followed by a value, in the case of a scalar, or by one or more values in the case of a list or hash. For example: # Set a global variable $dbh containing the database handle $interp->set_global(dbh => DBI->connect(...)); # Set a global hash %session from a local hash $interp->set_global('%session', %s); The global is set in the package that components run in: usually C<HTML::Mason::Commands>, although this can be overridden via the L<in_package|HTML::Mason::Params/in_package> parameter. The lines above, for example, are equivalent to: $HTML::Mason::Commands::dbh = DBI->connect(...); %HTML::Mason::Commands::session = %s; assuming that L<in_package|HTML::Mason::Params/in_package> has not been changed. Any global that you set should also be registered with the L<allow_globals|HTML::Mason::Params/allow_globals> parameter; otherwise you'll get warnings from C<strict>. =back =head1 SEE ALSO L<HTML::Mason|HTML::Mason>, L<HTML::Mason::Admin|HTML::Mason::Admin>, L<HTML::Mason::ApacheHandler|HTML::Mason::ApacheHandler> =cut
carlgao/lenga
images/lenny64-peon/usr/share/perl5/HTML/Mason/Interp.pm
Perl
mit
46,828
package WWW::Livesite::OutputStream; use strict; use Perl::Module; use Data::Hub qw($Hub); use Data::Format::XFR; use Algorithm::KeyGen; our $BoundaryGen = Algorithm::KeyGen->new(36, '0-9a-zA-Z'); sub new { my $class = ref($_[0]) ? ref(shift) : shift; my $r = $Hub->get('/sys/request/obj'); my $data_encoding = 'base64'; my $boundary = $data_encoding eq 'base64' ? ';' : $BoundaryGen->create(); my $xfr = Data::Format::XFR->new($data_encoding); my $self = bless { 'r' => $r, 'boundary' => $boundary, 'xfr' => $xfr, 'data_encoding' => $data_encoding, 'has_begun' => 0, }, $class; $self; } sub begin_output { my $self = shift; my $r = $$self{r}; $Hub->set('/sys/response/standalone', 1); $r->headers_out->set('X-Content-Format', 'text/data-xfr'); $r->headers_out->set('X-Content-Encoding', $$self{data_encoding}); $r->headers_out->set('X-Content-Charset', 'UTF-8'); $r->content_type("multipart/data-xfr; boundary=$$self{boundary}"); $r->rflush(); $$self{has_begun} = 1; return $self; } sub append { my $self = shift; $self->begin_output() unless $$self{has_begun}; my $r = $$self{r}; $r->print($$self{xfr}->format(@_), $$self{boundary}); $r->rflush(); return $self; } 1;
ryangies/lsn-www-hub
src/lib/WWW/Livesite/OutputStream.pm
Perl
mit
1,242
package Paws::OpsWorks::DescribeStacks; use Moose; has StackIds => (is => 'ro', isa => 'ArrayRef[Str|Undef]'); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeStacks'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::OpsWorks::DescribeStacksResult'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::OpsWorks::DescribeStacks - Arguments for method DescribeStacks on Paws::OpsWorks =head1 DESCRIPTION This class represents the parameters used for calling the method DescribeStacks on the AWS OpsWorks service. Use the attributes of this class as arguments to method DescribeStacks. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeStacks. As an example: $service_obj->DescribeStacks(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 StackIds => ArrayRef[Str|Undef] An array of stack IDs that specify the stacks to be described. If you omit this parameter, C<DescribeStacks> returns a description of every stack. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method DescribeStacks in L<Paws::OpsWorks> =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/OpsWorks/DescribeStacks.pm
Perl
apache-2.0
1,707
###########################################$ # Copyright 2008-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"). You may not # use this file except in compliance with the License. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompanying this file. This file 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. ###########################################$ # __ _ _ ___ # ( )( \/\/ )/ __) # /__\ \ / \__ \ # (_)(_) \/\/ (___/ # # Amazon EC2 Perl Library # API Version: 2010-06-15 # Generated: Wed Jul 21 13:37:54 PDT 2010 # package Amazon::EC2::Model::CreateSubnetResult; use base qw (Amazon::EC2::Model); # # Amazon::EC2::Model::CreateSubnetResult # # Properties: # # # Subnet: Amazon::EC2::Model::Subnet # # # sub new { my ($class, $data) = @_; my $self = {}; $self->{_fields} = { Subnet => {FieldValue => undef, FieldType => "Amazon::EC2::Model::Subnet"}, }; bless ($self, $class); if (defined $data) { $self->_fromHashRef($data); } return $self; } sub getSubnet { return shift->{_fields}->{Subnet}->{FieldValue}; } sub setSubnet { my ($self, $value) = @_; $self->{_fields}->{Subnet}->{FieldValue} = $value; } sub withSubnet { my ($self, $value) = @_; $self->setSubnet($value); return $self; } sub isSetSubnet { return defined (shift->{_fields}->{Subnet}->{FieldValue}); } 1;
electric-cloud/EC-EC2
src/main/resources/project/lib/Amazon/EC2/Model/CreateSubnetResult.pm
Perl
apache-2.0
1,887
package Rpmdrake::gurpm; #***************************************************************************** # # Copyright (c) 2002 Guillaume Cottenceau # Copyright (c) 2002-2007 Thierry Vignaud <tvignaud@mandriva.com> # Copyright (c) 2003, 2004, 2005 MandrakeSoft SA # Copyright (c) 2005-2007 Mandriva SA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # #***************************************************************************** # # $Id: gurpm.pm 248121 2008-10-11 11:19:36Z tv $ use lib qw(/usr/lib/libDrakX); use mygtk2 qw(gtknew); #- do not import anything else, especially gtkadd() which conflicts with ugtk2 one use ugtk2 qw(:all); use base qw(ugtk2); sub new { my ($self, $title, $initializing, %options) = @_; my $mainw = bless(ugtk2->new($title, %options, default_width => 600, width => 600), $self); $::main_window = $mainw->{real_window}; $mainw->{label} = gtknew('Label', text => $initializing, alignment => [ 0.5, 0 ]); # size label's heigh to 2 lines in order to prevent dummy vertical resizing: my $context = $mainw->{label}->get_layout->get_context; my $metrics = $context->get_metrics($mainw->{label}->style->font_desc, $context->get_language); $mainw->{label}->set_size_request(-1, 2 * Gtk2::Pango->PANGO_PIXELS($metrics->get_ascent + $metrics->get_descent)); $mainw->{progressbar} = gtknew('ProgressBar'); gtkadd($mainw->{window}, $mainw->{vbox} = gtknew('VBox', spacing => 5, border_width => 6, children_tight => [ $mainw->{label}, $mainw->{progressbar} ])); mygtk2::enable_sync_flush($mainw->{rwindow}); $mainw->{rwindow}->set_position('center-on-parent'); $mainw->{real_window}->show_all; mygtk2::sync_flush($mainw->{rwindow}); $mainw; } sub label { my ($self, $label) = @_; $self->{label}->set($label); select(undef, undef, undef, 0.1); #- hackish :-( $self->flush; } sub progress { my ($self, $fraction) = @_; $fraction = 0 if $fraction < 0; $fraction = 1 if 1 < $fraction; $self->{progressbar}->set_fraction($fraction); $self->flush; } sub DESTROY { my ($self) = @_; mygtk2::may_destroy($self); $self and $self->destroy; $self = undef; $self->{cancel} = undef; #- in case we'll do another one later } sub validate_cancel { my ($self, $cancel_msg, $cancel_cb) = @_; if (!$self->{cancel}) { gtkpack__( $self->{vbox}, $self->{hbox_cancel} = gtkpack__( gtknew('HButtonBox'), $self->{cancel} = gtknew('Button', text => $cancel_msg, clicked => \&$cancel_cb), ), ); } $self->{cancel}->set_sensitive(1); $self->{cancel}->show; } sub invalidate_cancel { my ($self) = @_; $self->{cancel} and $self->{cancel}->set_sensitive(0); } sub invalidate_cancel_forever { my ($self) = @_; $self->{hbox_cancel} or return; $self->{hbox_cancel}->destroy; # FIXME: temporary workaround that prevents # Gtk2::Label::set_text() set_text_internal() -> queue_resize() -> # size_allocate() call chain to mess up when ->shrink_topwindow() # has been called (#32613): #$self->shrink_topwindow; } 1;
blackPantherOS/packagemanagement
rpmanager/edit-repos/Rpmdrake/gurpm.pm
Perl
apache-2.0
3,737
use Modern::Perl; use File::Slurp qw(read_file write_file); use Data::Dumper qw(Dumper); my $filename = 'short_example.dsx'; my $data = read_file($filename); my $header_and_job = split_by_header_and_job($data); my $header_fields = split_fields_by_new_line( $header_and_job->{header} ); say Dumper $header_fields; sub split_by_header_and_job { my $data = shift; local $/ = ''; # Paragraph mode my %header_and_job = (); my @fields = (); #@fields = ( $data =~ / (?<header> BEGIN[ ]HEADER .*? END[ ]HEADER ) .*? (?<job> BEGIN[ ]DSJOB .*? END[ ]DSJOB ) /xsg ; %header_and_job = %+; return \%header_and_job; } sub split_fields_by_new_line { my ($curr_record) = @_; my %fields_and_values = (); my @fields = (); while ( $curr_record =~ m/ (?<name>\w+)[ ]"(?<value>.*?)(?<!\\)"| ((?<name>\w+)[ ]\Q=+=+=+=\E (?<value>.*?) \Q=+=+=+=\E) /xsg ) { my $name = $+{name}; my $value = $+{value}; my %hash_value = (); push @fields, \%hash_value; } return \@fields; }
mishin/presentation
regex_recursion/014.pl
Perl
apache-2.0
1,353
#!/usr/local/ensembl/bin/perl -w use strict; use Getopt::Long; use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor; # ok this is a hack, but I'm going to pretend I've got an object here # by creating a blessed hash ref and passing it around like an object # this is to avoid using global variables in functions, and to consolidate # the globals into a nice '$self' package my $self = bless {}; $self->{'compara_conf'} = {}; $self->{'compara_conf'}->{'-user'} = 'ensro'; $self->{'compara_conf'}->{'-port'} = 3306; $self->{'speciesList'} = (); $self->{'removeXedSeqs'} = undef; $self->{'outputFasta'} = undef; $self->{'noSplitSeqLines'} = undef; my $aaPerLine = 60; my $conf_file; my ($help, $host, $user, $pass, $dbname, $port, $adaptor); GetOptions('help' => \$help, 'conf=s' => \$conf_file, 'dbhost=s' => \$host, 'dbport=i' => \$port, 'dbuser=s' => \$user, 'dbpass=s' => \$pass, 'dbname=s' => \$dbname, 'g=s' => \$self->{'gene_stable_id'}, 'sp=s' => \$self->{'species'}, 'l=i' => \$aaPerLine, ); if ($help) { usage(); } $self->{'member_stable_id'} = shift if(@_); parse_conf($self, $conf_file); if($host) { $self->{'compara_conf'}->{'-host'} = $host; } if($port) { $self->{'compara_conf'}->{'-port'} = $port; } if($dbname) { $self->{'compara_conf'}->{'-dbname'} = $dbname; } if($user) { $self->{'compara_conf'}->{'-user'} = $user; } if($pass) { $self->{'compara_conf'}->{'-pass'} = $pass; } unless(defined($self->{'compara_conf'}->{'-host'}) and defined($self->{'compara_conf'}->{'-user'}) and defined($self->{'compara_conf'}->{'-dbname'})) { print "\nERROR : must specify host, user, and database to connect to compara\n\n"; usage(); } unless(defined($self->{'gene_stable_id'}) and defined($self->{'species'})) { print "\nERROR : must specify query gene and target species\n\n"; usage(); } $self->{'comparaDBA'} = new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(%{$self->{'compara_conf'}}); my $member; $member = $self->{'comparaDBA'}->get_MemberAdaptor->fetch_by_source_stable_id('ENSEMBLGENE', $self->{'gene_stable_id'}); #$member->print_member() if($member); my ($homology) = @{$self->{'comparaDBA'}->get_HomologyAdaptor->fetch_by_Member_paired_species($member, $self->{'species'})}; #$homology->print_homology() if($homology); my $queryMA; my $orthMA; foreach my $ma (@{$homology->get_all_Member_Attribute}) { my ($other_member, $attribute) = @{$ma}; $attribute->{'gene'} = $other_member; $attribute->{'peptide'} = $self->{'comparaDBA'}->get_MemberAdaptor->fetch_by_dbID($attribute->peptide_member_id); $attribute->{'pep_len'} = $attribute->{'peptide'}->seq_length; if($other_member->dbID ne $member->dbID) { $orthMA = $attribute; } else { $queryMA = $attribute; } } print("Homology between ", $queryMA->{'gene'}->stable_id, "(",$queryMA->cigar_start, ",", $queryMA->cigar_end, ",", $queryMA->{'pep_len'}, ")" , " and ", $orthMA->{'gene'}->stable_id, "(",$orthMA->cigar_start, ",", $orthMA->cigar_end, ",", $orthMA->{'pep_len'}, ")\n\n"); #print($queryMA->{'peptide'}->sequence, "\n"); #print($orthMA->{'peptide'}->sequence, "\n"); # # now get the alignment region # my $alignment = $homology->get_SimpleAlign(); my ($seq1, $seq2) = $alignment->each_seq; my $seqStr1 = "|".$seq1->seq().'|'; my $seqStr2 = "|".$seq2->seq().'|'; if($queryMA->cigar_start>1) { my $missingSeq = substr($queryMA->{'peptide'}->sequence, 0, $queryMA->cigar_start-1); $seqStr1 = $missingSeq . $seqStr1; } if($orthMA->cigar_start>1) { my $missingSeq = substr($orthMA->{'peptide'}->sequence, 0, $orthMA->cigar_start-1); $seqStr2 = $missingSeq . $seqStr2; } my $startdiff = $orthMA->cigar_start - $queryMA->cigar_start; while($startdiff>0) { $seqStr1 = " ".$seqStr1; $startdiff--; } while($startdiff<0) { $seqStr2 = " ".$seqStr2; $startdiff++; } if($queryMA->cigar_end < $queryMA->{'pep_len'}) { my $missingSeq = substr($queryMA->{'peptide'}->sequence, $queryMA->cigar_end, $queryMA->{'pep_len'}-$queryMA->cigar_end); $seqStr1 .= $missingSeq; } if($orthMA->cigar_end < $orthMA->{'pep_len'}) { my $missingSeq = substr($orthMA->{'peptide'}->sequence, $orthMA->cigar_end, $orthMA->{'pep_len'}-$orthMA->cigar_end); $seqStr2 .= $missingSeq; } my $enddiff = length($seqStr1) - length($seqStr2); while($enddiff>0) { $seqStr2 .= " "; $enddiff--; } while($enddiff<0) { $seqStr1 .= " "; $enddiff++; } my $label1 = sprintf("%20s : ", $seq1->id); my $label2 = sprintf("%20s : ", ""); my $label3 = sprintf("%20s : ", $seq2->id); my $line2 = ""; for(my $x=0; $x<length($seqStr1); $x++) { if(substr($seqStr1,$x,1) eq substr($seqStr2, $x,1)) { $line2.='|'; } else { $line2.=' '; } } my $offset=0; my $numLines = (length($seqStr1) / $aaPerLine); while($numLines>0) { printf("$label1 %s\n", substr($seqStr1,$offset,$aaPerLine)); printf("$label2 %s\n", substr($line2,$offset,$aaPerLine)); printf("$label3 %s\n", substr($seqStr2,$offset,$aaPerLine)); print("\n\n"); $offset+=$aaPerLine; $numLines--; } exit(0); ####################### # # subroutines # ####################### sub usage { print "getHomologyAlignment.pl [options] <member stable_id>\n"; print " -help : print this help\n"; print " -conf <path> : config file describing compara, templates, and external genome databases\n"; print " -dbhost <machine> : compara mysql database host <machine>\n"; print " -dbport <port#> : compara mysql port number\n"; print " -dbname <name> : compara mysql database <name>\n"; print " -dbuser <name> : compara mysql connection user <name>\n"; print " -dbpass <pass> : compara mysql connection password\n"; print " -g <id> : stable_id of query gene\n"; print " -sp <name> : name of target species\n"; print " -l <num> : number if bases per line for pretty output\n"; print "getHomologyAlignment.pl v1.1\n"; exit(1); } sub parse_conf { my $self = shift; my $conf_file = shift; if($conf_file and (-e $conf_file)) { #read configuration file from disk my @conf_list = @{do $conf_file}; foreach my $confPtr (@conf_list) { #print("HANDLE type " . $confPtr->{TYPE} . "\n"); if($confPtr->{TYPE} eq 'COMPARA') { $self->{'compara_conf'} = $confPtr; } if($confPtr->{TYPE} eq 'BLAST_TEMPLATE') { $self->{'analysis_template'} = $confPtr; } if($confPtr->{TYPE} eq 'SPECIES') { push @{$self->{'speciesList'}}, $confPtr; } } } } sub dump_fasta { my $self = shift; my $sql = "SELECT member.stable_id, member.description, sequence.sequence " . " FROM member, sequence, source " . " WHERE member.source_id=source.source_id ". " AND source.source_name='ENSEMBLPEP' ". " AND member.sequence_id=sequence.sequence_id " . " GROUP BY member.member_id ORDER BY member.stable_id;"; my $fastafile = $self->{'outputFasta'}; open FASTAFILE, ">$fastafile" or die "Could open $fastafile for output\n"; print("writing fasta to loc '$fastafile'\n"); my $sth = $self->{'comparaDBA'}->prepare( $sql ); $sth->execute(); my ($stable_id, $description, $sequence); $sth->bind_columns( undef, \$stable_id, \$description, \$sequence ); while( $sth->fetch() ) { $sequence =~ s/(.{72})/$1\n/g unless($self->{'noSplitSeqLines'}); #if removedXedSeqs defined then it contains the minimum num of # Xs in a row that is not acceptable, the regex X{#,}? says # if X occurs # or more times (not exhaustive search) unless($self->{'removeXedSeqs'} and ($sequence =~ /X{$self->{'removeXedSeqs'},}?/)) { print FASTAFILE ">$stable_id $description\n$sequence\n"; } } close(FASTAFILE); $sth->finish(); }
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-compara/scripts/homology/getHomologyAlignment.pl
Perl
apache-2.0
7,923
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::netapp::restapi::mode::listvolumes; use base qw(centreon::plugins::templates::counter); 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 => { "filter-name:s" => { name => 'filter_name' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); } sub manage_selection { my ($self, %options) = @_; my $result = $options{custom}->get(path => '/volumes'); foreach my $volume (@{$result}) { if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $volume->{name} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping '" . $volume->{name} . "': no matching filter name.", debug => 1); next; } $self->{volumes}->{$volume->{key}} = { name => $volume->{name}, state => $volume->{state}, vol_type => $volume->{vol_type}, style => $volume->{style}, is_replica_volume => $volume->{is_replica_volume}, size_total => $volume->{size_total}, } } } sub run { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $volume (sort keys %{$self->{volumes}}) { $self->{output}->output_add(long_msg => sprintf("[name = %s] [state = %s] [vol_type = %s] [style = %s] [is_replica_volume = %s] [size_total = %s]", $self->{volumes}->{$volume}->{name}, $self->{volumes}->{$volume}->{state}, $self->{volumes}->{$volume}->{vol_type}, $self->{volumes}->{$volume}->{style}, $self->{volumes}->{$volume}->{is_replica_volume}, $self->{volumes}->{$volume}->{size_total})); } $self->{output}->output_add(severity => 'OK', short_msg => 'List volumes:'); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['name', 'state', 'vol_type', 'style', 'is_replica_volume', 'size_total']); } sub disco_show { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $volume (sort keys %{$self->{volumes}}) { $self->{output}->add_disco_entry( name => $self->{volumes}->{$volume}->{name}, state => $self->{volumes}->{$volume}->{state}, vol_type => $self->{volumes}->{$volume}->{vol_type}, style => $self->{volumes}->{$volume}->{style}, is_replica_volume => $self->{volumes}->{$volume}->{is_replica_volume}, size_total => $self->{volumes}->{$volume}->{size_total}, ); } } 1; __END__ =head1 MODE List volumes. =over 8 =item B<--filter-name> Filter volume name (can be a regexp). =back =cut
wilfriedcomte/centreon-plugins
storage/netapp/restapi/mode/listvolumes.pm
Perl
apache-2.0
4,173
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::Exception; ### Exception object with type, message, stack trace and some optional extra data saved inside the blessed hash ### If used as a string, returns all information about the Exception object in formatted string ### Use this along with EnsEMBL::Web::Exceptions module to throw and catch exceptions using try catch syntax ### This class can be inherited, but is recommended only if the handle method needs to be overridden ### In Ideal conditions: ### Every exceptions thrown should have a message and at least one type tag specified ### Type should literally tell about the type of the exception eg. DOMException is a type of exception thrown in EnsEMBL::Web::DOM code ### Message should be informative message that can either be displayed on user screen, or saved in logs (depending upon how it's handled in catch statement) use strict; use warnings; use overload qw("" to_string); use HTML::Entities qw(encode_entities); sub new { ## @constructor ## Creates a new exception object ## @note Use 'throw exception' syntax provided by EnsEMBL::Web::Exceptions instead of this method to throw an exception ## @param Hashref with keys: type, message and data my ($class, $params) = @_; $params = _normalize_exception_object($params || {}); # build and save stack trace my $i = 0; my $stack = []; while (my @caller = caller($i++)) { next if $caller[0] eq 'EnsEMBL::Web::Exceptions' || $caller[3] =~ /^EnsEMBL::Web::Exceptions::/ || UNIVERSAL::isa($caller[0], __PACKAGE__); push @$stack, [splice @caller, 0, 4]; } return bless { '_type' => $params->{'type'} || 'Unknown', '_message' => $params->{'message'} || '', '_data' => $params->{'data'} || undef, '_stack' => $stack }, $params->{'package'} || $class; } sub handle { ## Handles the exception in a desired way ## Override this in the child class to provide better exception handling ## @return Boolean true if exception handled successfully, false otherwise my $self = shift; warn sprintf "%s Exception:\n %s %s", $self->{'_type'}, $self->{'_message'} // 'No message', $self->stack_trace; return 0; } sub type { ## Gets/Sets the type of the Exception ## @param String (if setting) ## @return String my $self = shift; $self->{'_type'} = "$_[0]" if @_; return $self->{'_type'}; } sub isa { ## Checks whether the exception belongs to a given type ## @param Type (or class) to be checked against ## @return True if the exception object contains the given type in its type string or if it is inherited from the given class, false otherwise my ($self, $type) = @_; return 1 if $self->type eq $type; return 1 if ref($self) =~ /::$type$/; return $self->SUPER::isa($type); } sub message { ## Gets the message passed in the exception object ## @param Flag if on will return the message without any encoding (use if message not being displayed) - Off by default ## @return Message string my $message = shift->{'_message'}; return shift @_ ? $message : encode_entities($message); } sub data { ## Gets/Sets the data saved with the Exception ## @return whatever was saved in the 'data' key my $self = shift; $self->{'_data'} = $_[0] if @_; return $self->{'_data'}; } sub stack_trace_array { ## Gets the stack trace for the exception ## @return Array of arrays return shift->{'_stack'}; } sub stack_trace { ## Gets string representation of stack trace for printing purposes ## @return String stack trace my $stack = shift->stack_trace_array; return join "\n", map sprintf('%s by %5$s in module %s at %s on line %s', ($_ ? ' Called' : 'Thrown'), @{$stack->[$_]}), 0..scalar @$stack - 1; } sub to_string { ## Converts the Exception object into a human-readable string my $self = shift; return sprintf("Uncaught exception '%s' with %smessage%s\n %s", $self->{'_type'}, $self->{'_message'} ? '' : 'no ', $self->{'_message'} ? sprintf(" '%s'", $self->{'_message'}) : '', $self->stack_trace ); } sub _normalize_exception_object { ## @private ## Converts external exceptions caught by try/catch into arguments as excepted by EnsEMBL::Web::Exception->new ## @param Object, possible an external exception object ## @return Hashref (as excepted by EnsEMBL::Web::Exception->new) my $object = shift; my $ref = ref $object; # string only if (!$ref) { if ($object =~ /\n\-+\s*EXCEPTION\s*\-+\n/) { return { 'type' => 'APIException', 'message' => $object }; } return { 'message' => $object }; } # standard hash as expected if ($ref eq 'HASH') { return $object; } # ORM exceptions if (UNIVERSAL::isa($object, 'ORM::EnsEMBL::Utils::Exception')) { require EnsEMBL::Web::Exception::ORMException; return { 'type' => $object->type, 'message' => $object->message, 'package' => 'EnsEMBL::Web::Exception::ORMException', }; } # any other exception for which we don't have a rule warn sprintf q(Recommendation: No rule found to convert exception of type %s to %s. To improve verbosity, add a rule to %2$s::_normalize_exception_object.%s), $ref, __PACKAGE__, "\n"; return {'message' => "$object"}; } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Web/Exception.pm
Perl
apache-2.0
5,978
package Google::Ads::AdWords::v201402::ManagedCustomerServiceError; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/mcm/v201402' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201402::ApiError); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %fieldPath_of :ATTR(:get<fieldPath>); my %trigger_of :ATTR(:get<trigger>); my %errorString_of :ATTR(:get<errorString>); my %ApiError__Type_of :ATTR(:get<ApiError__Type>); my %reason_of :ATTR(:get<reason>); my %customerIds_of :ATTR(:get<customerIds>); __PACKAGE__->_factory( [ qw( fieldPath trigger errorString ApiError__Type reason customerIds ) ], { 'fieldPath' => \%fieldPath_of, 'trigger' => \%trigger_of, 'errorString' => \%errorString_of, 'ApiError__Type' => \%ApiError__Type_of, 'reason' => \%reason_of, 'customerIds' => \%customerIds_of, }, { 'fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiError__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'reason' => 'Google::Ads::AdWords::v201402::ManagedCustomerServiceError::Reason', 'customerIds' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', }, { 'fieldPath' => 'fieldPath', 'trigger' => 'trigger', 'errorString' => 'errorString', 'ApiError__Type' => 'ApiError.Type', 'reason' => 'reason', 'customerIds' => 'customerIds', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::ManagedCustomerServiceError =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType ManagedCustomerServiceError from the namespace https://adwords.google.com/api/adwords/mcm/v201402. Error for {@link ManagedCustomerService} =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * reason =item * customerIds =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/ManagedCustomerServiceError.pm
Perl
apache-2.0
2,532
package Paws::Support::CreateCase; use Moose; has AttachmentSetId => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'attachmentSetId' ); has CategoryCode => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'categoryCode' ); has CcEmailAddresses => (is => 'ro', isa => 'ArrayRef[Str|Undef]', traits => ['NameInRequest'], request_name => 'ccEmailAddresses' ); has CommunicationBody => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'communicationBody' , required => 1); has IssueType => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'issueType' ); has Language => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'language' ); has ServiceCode => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'serviceCode' ); has SeverityCode => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'severityCode' ); has Subject => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'subject' , required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'CreateCase'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Support::CreateCaseResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::Support::CreateCase - Arguments for method CreateCase on Paws::Support =head1 DESCRIPTION This class represents the parameters used for calling the method CreateCase on the AWS Support service. Use the attributes of this class as arguments to method CreateCase. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to CreateCase. As an example: $service_obj->CreateCase(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 AttachmentSetId => Str The ID of a set of one or more attachments for the case. Create the set by using AddAttachmentsToSet. =head2 CategoryCode => Str The category of problem for the AWS Support case. =head2 CcEmailAddresses => ArrayRef[Str|Undef] A list of email addresses that AWS Support copies on case correspondence. =head2 B<REQUIRED> CommunicationBody => Str The communication body text when you create an AWS Support case by calling CreateCase. =head2 IssueType => Str The type of issue for the case. You can specify either "customer-service" or "technical." If you do not indicate a value, the default is "technical." =head2 Language => Str The ISO 639-1 code for the language in which AWS provides support. AWS Support currently supports English ("en") and Japanese ("ja"). Language parameters must be passed explicitly for operations that take them. =head2 ServiceCode => Str The code for the AWS service returned by the call to DescribeServices. =head2 SeverityCode => Str The code for the severity level returned by the call to DescribeSeverityLevels. The availability of severity levels depends on each customer's support subscription. In other words, your subscription may not necessarily require the urgent level of response time. =head2 B<REQUIRED> Subject => Str The title of the AWS Support case. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method CreateCase in L<Paws::Support> =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/Support/CreateCase.pm
Perl
apache-2.0
3,824
# 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::SmartCampaignSettingService::MutateSmartCampaignSettingsRequest; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { customerId => $args->{customerId}, operations => $args->{operations}, partialFailure => $args->{partialFailure}, responseContentType => $args->{responseContentType}, validateOnly => $args->{validateOnly}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Services/SmartCampaignSettingService/MutateSmartCampaignSettingsRequest.pm
Perl
apache-2.0
1,294
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =pod =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::ProteinTrees::GroupGenomesUnderTaxa =head1 DESCRIPTION Simple Runnable that flows all the components of a polyploid genome =cut package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::ComponentGenomeDBFactory; use strict; use warnings; use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); sub param_defaults { return { 'fan_branch_code' => 2, } } sub fetch_input { my $self = shift @_; my $genome_db = $self->compara_dba->get_GenomeDBAdaptor->fetch_by_dbID($self->param_required('genome_db_id')) or die "Could not fetch genome_db with dbID=".$self->param('genome_db_id'); die $genome_db->name." is not a polyploid !\n" unless $genome_db->is_polyploid; $self->param('genome_db', $genome_db); } sub write_output { my $self = shift; # Dataflow the GenomeDBs my $principal_genome_db = $self->param('genome_db'); foreach my $gdb (@{$principal_genome_db->component_genome_dbs}) { $self->dataflow_output_id( { 'component_genome_db_id' => $gdb->dbID, 'principal_genome_db_id' => $principal_genome_db->dbID }, $self->param('fan_branch_code')); } } 1;
danstaines/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/GeneTrees/ComponentGenomeDBFactory.pm
Perl
apache-2.0
1,892
# # 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::ruckus::ap::snmp::mode::memory; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub custom_usage_perfdata { my ($self, %options) = @_; if ($self->{result_values}->{total} > 0) { $self->{output}->perfdata_add(label => 'used', unit => 'B', value => $self->{result_values}->{used}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1), min => 0, max => $self->{result_values}->{total}); } else { $self->{output}->perfdata_add(label => 'used', unit => '%', value => $self->{result_values}->{prct_used}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{label}), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{label}), min => 0, max => 100); } } sub custom_usage_threshold { my ($self, %options) = @_; my $exit = $self->{perfdata}->threshold_check(value => $self->{result_values}->{prct_used}, threshold => [ { label => 'critical-' . $self->{label}, exit_litteral => 'critical' }, { label => 'warning-' . $self->{label}, exit_litteral => 'warning' } ]); return $exit; } sub custom_usage_output { my ($self, %options) = @_; my $msg = 'Memory Used: ' . $self->{result_values}->{prct_used} . '%'; if ($self->{result_values}->{total} > 0) { my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total}); my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used}); my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free}); $msg = sprintf("Memory Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_size_value . " " . $total_size_unit, $total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used}, $total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free}); } return $msg; } sub custom_usage_calc { my ($self, %options) = @_; $self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_total'}; $self->{result_values}->{prct_used} = $options{new_datas}->{$self->{instance} . '_prct_used'}; if ($self->{result_values}->{total} > 0) { $self->{result_values}->{used} = int($self->{result_values}->{prct_used} * $self->{result_values}->{total} / 100); $self->{result_values}->{free} = $self->{result_values}->{total} - $self->{result_values}->{used}; $self->{result_values}->{prct_free} = 100 - $self->{result_values}->{prct_used}; } return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'memory', type => 0 } ]; $self->{maps_counters}->{memory} = [ { label => 'usage', set => { key_values => [ { name => 'prct_used' }, { name => 'total' } ], closure_custom_calc => $self->can('custom_usage_calc'), closure_custom_output => $self->can('custom_usage_output'), closure_custom_perfdata => $self->can('custom_usage_perfdata'), closure_custom_threshold_check => $self->can('custom_usage_threshold'), } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub manage_selection { my ($self, %options) = @_; my $oid_ruckusSystemMemoryUtil = '.1.3.6.1.4.1.25053.1.1.11.1.1.1.2.0'; my $oid_ruckusSystemMemSize = '.1.3.6.1.4.1.25053.1.1.11.1.1.1.10.0'; my $oid_ruckusUnleashedSystemStatsMemoryUtil = '.1.3.6.1.4.1.25053.1.15.1.1.1.15.14.0'; my $snmp_result = $options{snmp}->get_leef(oids => [$oid_ruckusSystemMemoryUtil, $oid_ruckusSystemMemSize, $oid_ruckusUnleashedSystemStatsMemoryUtil], nothing_quit => 1); $self->{memory} = { prct_used => defined($snmp_result->{$oid_ruckusSystemMemoryUtil}) ? $snmp_result->{$oid_ruckusSystemMemoryUtil} : $snmp_result->{$oid_ruckusUnleashedSystemStatsMemoryUtil}, total => defined($snmp_result->{$oid_ruckusSystemMemSize}) ? $snmp_result->{$oid_ruckusSystemMemSize} : 0, }; } 1; __END__ =head1 MODE Check memory usage. =over 8 =item B<--warning-usage> Threshold warning (in percent). =item B<--critical-usage> Threshold critical (in percent). =back =cut
centreon/centreon-plugins
network/ruckus/ap/snmp/mode/memory.pm
Perl
apache-2.0
5,965
# # 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::sensors::sensorip::snmp::mode::components::sp; use strict; use warnings; my %map_sp_status = ( 1 => 'noStatus', 2 => 'normal', 3 => 'warning', 4 => 'critical', 5 => 'sensorError', ); my $oid_spStatus = '.1.3.6.1.4.1.3854.1.1.2'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_spStatus }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking sp"); $self->{components}->{sp} = { name => 'sp', total => 0, skip => 0 }; return if ($self->check_filter(section => 'sp')); return if (scalar(keys %{$self->{results}->{$oid_spStatus}}) <= 0); my $instance = 0; my $sp_status = defined($map_sp_status{$self->{results}->{$oid_spStatus}->{$oid_spStatus . '.' . $instance}}) ? $map_sp_status{$self->{results}->{$oid_spStatus}->{$oid_spStatus . '.' . $instance}} : 'unknown'; return if ($self->check_filter(section => 'sp', instance => $instance)); return if ($sp_status =~ /noStatus/i && $self->absent_problem(section => 'sp', instance => $instance)); $self->{components}->{sp}->{total}++; $self->{output}->output_add(long_msg => sprintf("Sensor probe '%s' status is '%s'", $instance, $sp_status)); my $exit = $self->get_severity(section => 'sp', value => $sp_status); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Sensor probe '%s' status is '%s'", $instance, $sp_status)); } } 1;
Sims24/centreon-plugins
hardware/sensors/sensorip/snmp/mode/components/sp.pm
Perl
apache-2.0
2,420
package Paws::WAF::SqlInjectionMatchSetUpdate; use Moose; has Action => (is => 'ro', isa => 'Str', required => 1); has SqlInjectionMatchTuple => (is => 'ro', isa => 'Paws::WAF::SqlInjectionMatchTuple', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::WAF::SqlInjectionMatchSetUpdate =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::WAF::SqlInjectionMatchSetUpdate object: $service_obj->Method(Att1 => { Action => $value, ..., SqlInjectionMatchTuple => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::WAF::SqlInjectionMatchSetUpdate object: $result = $service_obj->Method(...); $result->Att1->Action =head1 DESCRIPTION Specifies the part of a web request that you want to inspect for snippets of malicious SQL code and indicates whether you want to add the specification to a SqlInjectionMatchSet or delete it from a C<SqlInjectionMatchSet>. =head1 ATTRIBUTES =head2 B<REQUIRED> Action => Str Specify C<INSERT> to add a SqlInjectionMatchSetUpdate to a SqlInjectionMatchSet. Use C<DELETE> to remove a C<SqlInjectionMatchSetUpdate> from a C<SqlInjectionMatchSet>. =head2 B<REQUIRED> SqlInjectionMatchTuple => L<Paws::WAF::SqlInjectionMatchTuple> Specifies the part of a web request that you want AWS WAF to inspect for snippets of malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used 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/SqlInjectionMatchSetUpdate.pm
Perl
apache-2.0
2,019
package Paws::OpsWorksCM::RestoreServer; use Moose; has BackupId => (is => 'ro', isa => 'Str', required => 1); has InstanceType => (is => 'ro', isa => 'Str'); has KeyPair => (is => 'ro', isa => 'Str'); has ServerName => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'RestoreServer'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::OpsWorksCM::RestoreServerResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::OpsWorksCM::RestoreServer - Arguments for method RestoreServer on Paws::OpsWorksCM =head1 DESCRIPTION This class represents the parameters used for calling the method RestoreServer on the AWS OpsWorks for Chef Automate service. Use the attributes of this class as arguments to method RestoreServer. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to RestoreServer. As an example: $service_obj->RestoreServer(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> BackupId => Str The ID of the backup that you want to use to restore a server. =head2 InstanceType => Str The type of the instance to create. Valid values must be specified in the following format: C<^([cm][34]|t2).*> For example, C<m4.large>. Valid values are C<t2.medium>, C<m4.large>, and C<m4.2xlarge>. If you do not specify this parameter, RestoreServer uses the instance type from the specified backup. =head2 KeyPair => Str The name of the key pair to set on the new EC2 instance. This can be helpful if the administrator no longer has the SSH key. =head2 B<REQUIRED> ServerName => Str The name of the server that you want to restore. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method RestoreServer in L<Paws::OpsWorksCM> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/OpsWorksCM/RestoreServer.pm
Perl
apache-2.0
2,371
package KorAP::XML::Annotation::RWK::Morpho; use KorAP::XML::Annotation::Base; sub parse { my $self = shift; $$self->add_tokendata( foundry => 'rwk', layer => 'morpho', cb => sub { my ($stream, $token) = @_; my $mtt = $stream->pos($token->get_pos); my $content = $token->get_hash->{fs}->{f} or return; my $found; foreach my $f (@{$content->{fs}->{f}}) { my $name = lc($f->{-name}); # pos tag if (($name eq 'pos') && ($found = $f->{'#text'})) { $mtt->add_by_term('rwk/p:' . $found); } # normtok tag elsif (($name eq 'normtok') && ($found = $f->{'#text'})) { $mtt->add_by_term('rwk/norm:' . $found); } # lemma tag elsif (($name eq 'lemma') && ($found = $f->{'#text'}) && $found ne '--') { $mtt->add_by_term('rwk/l:' . $found); } # ana tag elsif (($found = $f->{'#text'}) && $name =~ m/^(?:bc|(?:sub)?type|usage|person|pos|case|number|gender|tense|mood|degree)$/o) { $mtt->add_by_term('rwk/m:' . $name . ':' . $found); }; }; }) or return; return 1; }; sub layer_info { ['rwk/l=tokens', 'rwk/p=tokens', 'rwk/m=tokens', 'rwk/normtok=tokens'] } 1;
KorAP/KorAP-XML-Krill
lib/KorAP/XML/Annotation/RWK/Morpho.pm
Perl
bsd-2-clause
1,337
#!/usr/bin/perl # # Takes SDM, target dir, and a scan list, and creates an edited full # SDM in targetdir. # # What it actually does is replace BDF names in Main.xml with 'X1', # the indicator for "no BDF available". This effectively chops out the # scans marked thus. # # Sarah B Spolaor July 2015 # Adapted from Bryan Butler's choose_SDM_scans.pl # use strict; my $progname = 'sdm\_chop-n-serve.pl'; if ($#ARGV < 2) { print "\n\tUSAGE ERROR ($progname):\n\t sdm_chop-n-serve.pl inputSDM targetDir [scanList] inputSDM SDM name including full path. Script will not change this SDM. targetDir Where to put the edited SDM. Will make full copy of the SDM to (name)\_edited. scanList (optional) examples: 1; 1~2; 1,3,5; 1,2,3~6\n"; exit 1; } my $sdm_directory= $ARGV[0]; my $target_dir = $ARGV[1]; # Check SDM source directory if (! -d $sdm_directory) { print "\n\tERROR ($progname):\n\tSDM directory not found.\n\n"; exit 1; } if (!-e "$sdm_directory/Main.xml") { print "\n\tERROR ($progname):\n\tCouldn't find Main.xml in $sdm_directory\n\n"; exit 2; } my @dummy = split('/',$sdm_directory); # Check target dir system "touch $target_dir/temp.garbage"; if (!-e "$target_dir/temp.garbage"){ print "\n\tERROR ($progname):\n\tYou do not have write permission in requested target dir $target_dir\n\n"; exit 4; } system "rm -f $target_dir/temp.garbage"; # Does target SDM already exist? my $target_sdm = "$target_dir/".$dummy[-1]."\_edited"; if (-e "$target_sdm"){ print "\n\tERROR ($progname):\n\tRequested target file $target_sdm already exists; we do not overwrite.\n\n"; exit 3; } # Copy SDM to a dir we know we can edit in place. # Do not copy any bdfpkls directory. system "mkdir $target_sdm"; open(SDMDIR, "ls -1 $sdm_directory |"); while(<SDMDIR>){ chomp; my $sdm_content = $_; if ($sdm_content !~ /bdfpkls/ && $sdm_content !~ /ASDMBinary/){ system "cp -r $sdm_directory/$sdm_content $target_sdm"; chmod 0777, "$target_sdm/$sdm_content"; } } close(SDMDIR); chmod 0777, "$target_sdm"; my $main_xml_filename = "$target_sdm/Main.xml"; system "rm $target_sdm/Main.xml"; open (OUTPUT, ">$main_xml_filename"); chdir $sdm_directory; open (INPUT, '<Main.xml'); # print "Enter the scan list (casa format): "; # my $scan_list = <STDIN>; my $scan_list = $ARGV[2]; chomp $scan_list; # # figure out desired scans # my @scan_segments = split(',',$scan_list); my @desired_scans = (); foreach my $scan_segment ( @scan_segments ) { if (index($scan_segment,'~') >= 0) { my ($start_scan,$stop_scan) = split('~',$scan_segment); for my $ii ( $start_scan .. $stop_scan ) { push @desired_scans, $ii; } } else { push @desired_scans, $scan_segment; } } #print "\ndesired scans: @desired_scans\n"; #foreach my $ii ( 1 .. scalar(@desired_scans)-1 ) { # print ", $desired_scans[$ii]"; #} #print "\n"; # # find the first <row> element # LOOP: while ( <INPUT> ) { while (index($_,'<row>') < 0) { print OUTPUT "$_"; $_ = <INPUT> or last LOOP; } # # skip down to the scanNumber element # while ( index($_,'<scanNumber>') < 0 ) { print OUTPUT "$_"; $_ = <INPUT> or last LOOP; } my @Flds = split('\<', $_); my $scan_number = (split('\>',$Flds[1]))[1]; my $is_desired_scan = 0; foreach my $scan ( @desired_scans ) { if ( $scan_number == $scan ) { $is_desired_scan = 1; last; } } print OUTPUT "$_"; $_ = <INPUT> or last LOOP; # # skip down to the datasize element # while ( index($_,'<dataSize>') < 0 ) { print OUTPUT "$_"; $_ = <INPUT> or last LOOP; } if (! $is_desired_scan ) { $_ =~ s/\d//g; $_ =~ s/></>0</; } # # skip down to the EntityRef element # while ( index($_,'<EntityRef ') < 0 ) { print OUTPUT "$_"; $_ = <INPUT> or last LOOP; } # # if it's not already missing, or an undesired scan, put in 'X1' for the BDF ID # if ( index($_,'X1') < 0 ) { my $entity_id = (split('"',$_))[1]; if (! $is_desired_scan ) { # print "marking scan $scan_number as MISSING its BDF data...\n"; $entity_id =~ /[0-9]/; my $bdf_id = substr($entity_id,$-[0]); $_ =~ s/$bdf_id/X1/; $_ =~ s/\/\/\//\/\//; } else { # print "marking scan $scan_number as HAVING its BDF data...\n"; } } else { # print "scan $scan_number is missing its original BDF data...\n"; } print OUTPUT "$_"; } close INPUT; close OUTPUT; chmod 0777, $main_xml_filename; exit 0;
caseyjlaw/realfast
scripts/sdm_chop-n-serve.pl
Perl
bsd-3-clause
4,673
# ************************************************************************* # Copyright (c) 2014-2015-2015, SUSE LLC # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of SUSE LLC nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. # ************************************************************************* # special testing module for use with t/4xx/403-Forbidden.t package Web::MREST::Test::Forbidden; use 5.012; use strict; use warnings; use App::CELL qw( $log ); use Web::MREST::Dispatch qw( init_router ); use parent 'Web::MREST::Resource'; =head1 NAME Web::MREST::Test::Forbidden - Override forbidden method =head1 SYNOPSIS Provide a forbidden method to override the default one. =head1 FUNCTIONS =head2 forbidden A forbidden method that always returns 1. =cut sub forbidden { my ( $self ) = @_; $log->debug( "Entering " . __PACKAGE__ . "::forbidden" ); return 1; } 1;
smithfarm/mrest
lib/Web/MREST/Test/Forbidden.pm
Perl
bsd-3-clause
2,293
#!/usr/bin/perl use strict; use warnings; #With this script you can print the ammount of the elements that are up to each scaffold for every chromosome or to print the elements (if you change the comments) my $chromosome = $ARGV[0]; my $target = $ARGV[1]; my @mykeys = `cat OUTPUT_$target/unique_hces_final_$target/$chromosome.txt| awk '{print \$1}'| sort -u`; foreach (@mykeys) { my $key = $_; chomp($key); my $command = "cat OUTPUT_$target/unique_hces_final_$target/$chromosome.txt|grep -w $key"; my @belongs= `$command`; chomp(@belongs); my $count = scalar(@belongs); my $final_line = $belongs[0]; # if ($count == 1) print "$key\t$chromosome\t$count\n"; #print "$key\n"; #if you want to print the scaffold with the elements #print join("\n", @belongs), "\n"; }
vasilislenis/CElMap
bin/grepScaffUnique.pl
Perl
mit
862
package Google::Ads::AdWords::v201406::Operation; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %operator_of :ATTR(:get<operator>); my %Operation__Type_of :ATTR(:get<Operation__Type>); __PACKAGE__->_factory( [ qw( operator Operation__Type ) ], { 'operator' => \%operator_of, 'Operation__Type' => \%Operation__Type_of, }, { 'operator' => 'Google::Ads::AdWords::v201406::Operator', 'Operation__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', }, { 'operator' => 'operator', 'Operation__Type' => 'Operation.Type', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::Operation =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType Operation from the namespace https://adwords.google.com/api/adwords/cm/v201406. This represents an operation that includes an operator and an operand specified type. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * operator =item * Operation__Type Note: The name of this property has been altered, because it didn't match perl's notion of variable/subroutine names. The altered name is used in perl code only, XML output uses the original name: Operation.Type =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/Operation.pm
Perl
apache-2.0
1,842
package Paws::Config::DescribeConfigRulesResponse; use Moose; has ConfigRules => (is => 'ro', isa => 'ArrayRef[Paws::Config::ConfigRule]'); has NextToken => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::Config::DescribeConfigRulesResponse =head1 ATTRIBUTES =head2 ConfigRules => ArrayRef[L<Paws::Config::ConfigRule>] The details about your AWS Config rules. =head2 NextToken => Str The string that you use in a subsequent request to get the next page of results in a paginated response. =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/Config/DescribeConfigRulesResponse.pm
Perl
apache-2.0
629
# please insert nothing before this line: -*- mode: cperl; cperl-indent-level: 4; cperl-continued-statement-offset: 4; indent-tabs-mode: nil -*- package TestFilter::in_init_basic; use strict; use warnings FATAL => 'all'; use Apache::Test; use Apache::TestUtil; use Apache2::RequestRec (); use Apache2::RequestIO (); use base qw(Apache2::Filter); use TestCommon::Utils (); use Apache2::Const -compile => qw(OK M_POST); use constant READ_SIZE => 1024; # this filter is expected to be called once # it'll set a note, with the count sub transparent_init : FilterInitHandler { my $filter = shift; my $ctx = $filter->ctx; $ctx->{init}++; $filter->r->notes->set(init => $ctx->{init}); $filter->ctx($ctx); return Apache2::Const::OK; } # this filter passes the data through unmodified and sets a note # counting how many times it was invoked sub transparent : FilterRequestHandler FilterHasInitHandler(\&transparent_init) { my ($filter, $bb, $mode, $block, $readbytes) = @_; my $ctx = $filter->ctx; $ctx->{run}++; $filter->r->notes->set(run => $ctx->{run}); $filter->ctx($ctx); $filter->next->get_brigade($bb, $mode, $block, $readbytes); return Apache2::Const::OK; } # this filter is not supposed to get a chance to run, since its init # handler immediately removes it sub suicide_init : FilterInitHandler { shift->remove(); Apache2::Const::OK } sub suicide : FilterHasInitHandler(\&suicide_init) { die "this filter is not supposed to have a chance to run"; } sub response { my $r = shift; $r->content_type('text/plain'); if ($r->method_number == Apache2::Const::M_POST) { $r->print(TestCommon::Utils::read_post($r)); } my @keys = qw(init run); my %times = map { $_ => $r->notes->get($_)||0 } @keys; $r->print("$_ $times{$_}\n") for @keys; Apache2::Const::OK; } 1; __DATA__ SetHandler modperl PerlModule TestFilter::in_init_basic PerlResponseHandler TestFilter::in_init_basic::response PerlInputFilterHandler TestFilter::in_init_basic::suicide PerlInputFilterHandler TestFilter::in_init_basic::transparent
dreamhost/dpkg-ndn-perl-mod-perl
t/filter/TestFilter/in_init_basic.pm
Perl
apache-2.0
2,158
#!/usr/bin/perl # ----------------------------------------------------------------------------- # Project : OpenGTS - Open GPS Tracking System # URL : http://www.opengts.org # File : admin.pl # Description: Command-line DB table administrative tool. # ----------------------------------------------------------------------------- # Database administrative tool. # Usage: # % bin/admin.pl <TableName> [<Options>] # ----------------------------------------------------------------------------- # If present, this command will use the following environment variables: # GTS_HOME - The GTS installation directory (defaults to ("<commandDir>/..") # GTS_CONF - The runtime config file (defaults to "$GTS_HOME/default.conf") # ----------------------------------------------------------------------------- $GTS_HOME = $ENV{"GTS_HOME"}; if ("$GTS_HOME" eq "") { print "WARNING: GTS_HOME not defined!\n"; use Cwd 'realpath'; use File::Basename; my $REAL_PATH = realpath($0); my $EXEC_BIN = dirname($REAL_PATH); require "$EXEC_BIN/common.pl"; } else { require "$GTS_HOME/bin/common.pl"; } # ----------------------------------------------------------------------------- $Standard_Tables = "$GTS_STD_PKG.db.tables"; $OpenDMTP_Tables = "$GTS_STD_PKG.db.dmtp"; $Extra_Tables = "$GTS_STD_PKG.extra.tables"; $Rule_Tables = "$GTS_STD_PKG.rule.tables"; $BCross_Tables = "$GTS_STD_PKG.bcross.tables"; # --- Entry points %Class_names = ( "Account" => $Standard_Tables . ".Account", "AccountString" => $Standard_Tables . ".AccountString", "Device" => $Standard_Tables . ".Device", "DeviceGroup" => $Standard_Tables . ".DeviceGroup", "DeviceList" => $Standard_Tables . ".DeviceList", "Driver" => $Standard_Tables . ".Driver", "Geozone" => $Standard_Tables . ".Geozone", "Resource" => $Standard_Tables . ".Resource", "Role" => $Standard_Tables . ".Role", "RoleAcl" => $Standard_Tables . ".RoleAcl", "StatusCode" => $Standard_Tables . ".StatusCode", "SystemProps" => $Standard_Tables . ".SystemProps", "Transport" => $Standard_Tables . ".Transport", "UniqueXID" => $Standard_Tables . ".UniqueXID", "User" => $Standard_Tables . ".User", "UserAcl" => $Standard_Tables . ".UserAcl", # -- "PendingPacket" => $OpenDMTP_Tables . ".PendingPacket", "Property" => $OpenDMTP_Tables . ".Property", # -- "Entity" => $Extra_Tables . ".Entity", "SessionStats" => $Extra_Tables . ".SessionStats", "UnassignedDevices" => $Extra_Tables . ".UnassignedDevices", # -- "GeoCorridor" => $Rule_Tables . ".GeoCorridor", "GeoCorridorList" => $Rule_Tables . ".GeoCorridorList", "Rule" => $Rule_Tables . ".Rule", "RuleList" => $Rule_Tables . ".RuleList", # -- "BorderCrossing" => $BCross_Tables . ".BorderCrossing", ); # --- Named entry point $TableName = $ARGV[0]; $Entry_point = $Class_names{$TableName}; if ("$Entry_point" eq "") { print "TableName not found: $TableName\n"; exit(1); } shift; # --- debug $DebugMode = ""; $_DebugMode = $ARGV[0]; if (("$_DebugMode" eq "-debug") || ("$_DebugMode" eq "-debugMode")) { $GTS_DEBUG = 1; $DebugMode = "-debugMode=true"; } # --- Java command $CP = "-classpath '$CLASSPATH'"; $Command = "$cmd_java $CP $Entry_point -conf=$GTS_CONF $DebugMode -log.file.enable=false"; # --- execute my $args = join(' ', @ARGV); my $cmd = $Command . " $args"; &sysCmd($cmd, $GTS_DEBUG); exit(0); # -----------------------------------------------------------------------------
aldridged/gtg-gts-bhp
bin/admin.pl
Perl
apache-2.0
3,796
#! /usr/bin/perl -w use strict; use CGI; use CGI::Ajax; use CoGeX; use CoGe::Accessory::Web; use HTML::Template; use Data::Dumper; use File::Basename; use Text::Wrap qw($columns &wrap); use JSON::XS; no warnings 'redefine'; use vars qw($P $TEMPDIR $TEMPURL $FORM $USER $LINK $coge $PAGE_TITLE $PAGE_NAME); $FORM = new CGI; ( $coge, $USER, $P, $LINK ) = CoGe::Accessory::Web->init( cgi => $FORM, page_title => $PAGE_TITLE ); $PAGE_TITLE = 'FastaView'; $PAGE_NAME = "$PAGE_TITLE.pl"; $ENV{PATH} = $P->{COGEDIR}; $TEMPDIR = $P->{TEMPDIR} . "$PAGE_TITLE/"; $TEMPURL = $P->{TEMPURL} . "$PAGE_TITLE/"; my %ajax = CoGe::Accessory::Web::ajax_func(); my %FUNCTIONS = ( gen_html => \&gen_html, get_seqs => \&get_seqs, gen_file => \&gen_file, test => \&test, %ajax, ); #CoGe::Accessory::Web->dispatch( $FORM, \%FUNCTION, \&gen_html ); my $pj = new CGI::Ajax(%FUNCTIONS); $pj->js_encode_function('escape'); if ( $FORM->param('jquery_ajax') ) { my %args = $FORM->Vars; my $fname = $args{'fname'}; #print STDERR Dumper \%args; if ( $fname and defined $FUNCTIONS{$fname} ) { if ( $args{args} ) { my @args_list = split( /,/, $args{args} ); print $FORM->header, $FUNCTIONS{$fname}->(@args_list); } else { print $FORM->header, $FUNCTIONS{$fname}->(%args); } } } elsif ( $FORM->param('text') ) { my $header = "Content-disposition: attachement; filename=CoGe_"; #test.gff\n\n"; $header .= int( rand(100000) ); $header .= ".faa\n\n"; print $header; print gen_html(); } else { print $pj->build_html( $FORM, \&gen_html ); #print $FORM->header,gen_html(); } sub gen_html { my $html; my $form = $FORM; my $prot = $form->param('prot'); my $text = $form->param('text'); my $name_only = $form->param('no'); my $id_only = $form->param('io'); my $upstream = $form->param('up') || 0; my $downstream = $form->param('down') || 0; my $textbox = $text ? 0 : 1; my $template = HTML::Template->new( filename => $P->{TMPLDIR} . 'generic_page.tmpl' ); # $template->param(TITLE=>'Fasta Viewer'); $template->param( PAGE_TITLE => 'FastaView', TITLE => 'FastaView', PAGE_LINK => $LINK, SUPPORT_EMAIL => $P->{SUPPORT_EMAIL}, HOME => $P->{SERVER}, HELP => 'FastaView', WIKI_URL => $P->{WIKI_URL} || '', USER => $USER->display_name || '' ); $template->param( LOGON => 1 ) unless $USER->user_name eq "public"; my @fids; push @fids, $form->param('featid') if $form->param('featid'); push @fids, $form->param('fid') if $form->param('fid'); my $gstid = $form->param('gstid') if $form->param('gstid'); my ( $seqs, $seq_count, $feat_count, $warning ) = get_seqs( prot => $prot, fids => \@fids, textbox => $textbox, gstid => $gstid, name_only => $name_only, id_only => $id_only, upstream => $upstream, downstream => $downstream ); my $json = get_json( prot => $prot, fids => \@fids, textbox => $textbox, gstid => $gstid, name_only => $name_only, id_only => $id_only, upstream => $upstream, downstream => $downstream ); if ($text) { return $seqs; } $template->param( BODY => gen_body( fids => \@fids, seqs => $seqs, json => $json, seq_count => $seq_count, feat_count => $feat_count, gstid => $gstid, prot => $prot, up => $upstream, down => $downstream, message => $warning, ) ); $template->param( ADMIN_ONLY => $USER->is_admin, CAS_URL => $P->{CAS_URL} || '', COOKIE_NAME => $P->{COOKIE_NAME} || '' ); $html .= $template->output; return $html; } sub get_seqs { my %opts = @_; my $fids = $opts{fids}; my $prot = $opts{prot}; my $textbox = $opts{textbox}; my $name_only = $opts{name_only}; my $id_only = $opts{id_only}; my $gstid = $opts{gstid}; my $upstream = $opts{upstream}; my $downstream = $opts{downstream}; my @fids = ref($fids) =~ /array/i ? @$fids : split( /,/, $fids ); my %seen = (); @fids = grep { !$seen{$_}++ } @fids; my $seqs; my $seq_count = 0; my $fid_count = 0; foreach my $item (@fids) { foreach my $featid ( split( /,/, $item ) ) { $fid_count++; my ( $fid, $gstidt ); if ( $featid =~ /_/ ) { ( $fid, $gstidt ) = split /_/, $featid; } else { ( $fid, $gstidt ) = ( $featid, $gstid ); } my ($feat) = $coge->resultset('Feature')->find($fid); unless ($feat) { $seqs .= ">Not found: $featid\n"; next; } my ($dsg) = $feat->dataset->genomes; if ( !$USER->has_access_to_genome($dsg) ) { $seqs .= ">Restricted: $featid\n"; next; } my $tmp = $feat->fasta( col => 100, prot => $prot, name_only => $name_only, fid_only => $id_only, gstid => $gstidt, upstream => $upstream, downstream => $downstream ); $seq_count += $tmp =~ tr/>/>/; $seqs .= $tmp; } } my $warning; %seen = (); while ( $seqs =~ /(>.*\n)/g ) { $warning = "Warning: Duplicate sequence names" if $seen{$1}; $seen{$1} = 1; } $seqs = qq{<textarea id=seq_text name=seq_text class="ui-widget-content ui-corner-all backbox" ondblclick="this.select();" style="height: 400px; width: 800px; overflow: auto;">$seqs</textarea>} if $textbox; return $seqs, $seq_count, $fid_count, $warning; } sub get_json { # mdb added 2/28/14 for genfam integration my %opts = @_; my $fids = $opts{fids}; my $prot = $opts{prot}; my $gstid = $opts{gstid}; my $upstream = $opts{upstream}; my $downstream = $opts{downstream}; my @fids = ref($fids) =~ /array/i ? @$fids : split( /,/, $fids ); my %seen = (); @fids = grep { !$seen{$_}++ } @fids; my @obj; foreach my $item (@fids) { foreach my $featid ( split( /,/, $item ) ) { my ( $fid, $gstidt ); if ( $featid =~ /_/ ) { ( $fid, $gstidt ) = split /_/, $featid; } else { ( $fid, $gstidt ) = ( $featid, $gstid ); } my ($feat) = $coge->resultset('Feature')->find($fid); next unless ($feat); my ($dsg) = $feat->dataset->genomes; next if ( !$USER->has_access_to_genome($dsg) ); my $tmp = $feat->fasta_object( col => 100, prot => $prot, gstid => $gstidt, upstream => $upstream, downstream => $downstream ); push @obj, $tmp; } } return encode_json({fasta => \@obj}); } sub gen_file { my %opts = @_; my $fids = $opts{fids}; my $prot = $opts{prot}; my $textbox = $opts{textbox}; my $name_only = $opts{name_only}; my $id_only = $opts{id_only}; my $gstid = $opts{gstid}; my $upstream = $opts{upstream}; my $downstream = $opts{downstream}; my @fids = ref($fids) =~ /array/i ? @$fids : split(/,/, $fids); my ($seqs) = get_seqs( prot => $prot, fids => \@fids, gstid => $gstid, name_only => $name_only, id_only => $id_only, upstream => $upstream, downstream => $downstream ); my $file = $TEMPDIR . "Seqs_" . int( rand(100000000) ) . ".faa"; eval { open( OUT, ">" . $file ); print OUT $seqs; close OUT; }; return $P->{SERVER} . "/tmp/$PAGE_TITLE/" . basename($file); } sub gen_body { my %opts = @_; my $seqs = $opts{seqs}; my $json = $opts{json}; my $seq_count = $opts{seq_count}; my $feat_count = $opts{feat_count}; my $message = $opts{message}; my $fids = $opts{fids}; my $gstid = $opts{gstid} || 1; my $prot = $opts{prot} || 0; my $up = $opts{up} || 0; my $down = $opts{down} || 0; $fids = join( ",", @$fids ) if ref($fids) =~ /array/i; my $template = HTML::Template->new( filename => $P->{TMPLDIR} . 'FastaView.tmpl' ); $template->param( BOTTOM_BUTTONS => 1 ); $template->param( SEQ => $seqs ) if $seqs; $template->param( FASTA_JSON => $json ) if $json; $template->param( SEQ_COUNT => $seq_count ) if defined $seq_count; $template->param( FEAT_COUNT => $feat_count ) if defined $feat_count; $template->param( WARNING => $message ) if defined $message; $template->param( FIDS => qq{<input type=hidden id=fids value=$fids><input type=hidden id=gstid value=$gstid>} ); $template->param( PROT => $prot ); $template->param( UP => $up ); $template->param( DOWN => $down ); $template->param( genfam => $P->{GENFAMURL}); return $template->output; }
asherkhb/coge
web/FastaView.pl
Perl
bsd-2-clause
9,744
package # Date::Manip::Offset::off268; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:45 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-03:00:00'; %Offset = ( 0 => [ 'america/sao_paulo', 'america/araguaina', 'america/bahia', 'america/belem', 'america/fortaleza', 'america/maceio', 'america/recife', 'america/godthab', 'america/montevideo', 'america/cayenne', 'america/argentina/buenos_aires', 'america/argentina/catamarca', 'america/argentina/cordoba', 'america/argentina/jujuy', 'america/argentina/la_rioja', 'america/argentina/mendoza', 'america/argentina/rio_gallegos', 'america/argentina/salta', 'america/argentina/san_juan', 'america/argentina/tucuman', 'america/argentina/ushuaia', 'america/miquelon', 'america/paramaribo', 'america/santarem', 'etc/gmt-3', 'c', 'antarctica/rothera', 'america/argentina/san_luis', 'america/danmarkshavn', 'america/guyana', 'atlantic/stanley', 'america/asuncion', 'antarctica/palmer', ], 1 => [ 'america/halifax', 'america/glace_bay', 'america/moncton', 'america/argentina/san_luis', 'america/campo_grande', 'america/cuiaba', 'atlantic/stanley', 'america/goose_bay', 'america/santiago', 'atlantic/bermuda', 'america/asuncion', 'america/thule', 'antarctica/palmer', 'america/argentina/buenos_aires', 'america/argentina/catamarca', 'america/argentina/cordoba', 'america/argentina/jujuy', 'america/argentina/la_rioja', 'america/argentina/mendoza', 'america/argentina/rio_gallegos', 'america/argentina/salta', 'america/argentina/san_juan', 'america/argentina/tucuman', 'america/argentina/ushuaia', 'america/boa_vista', 'america/manaus', 'america/pangnirtung', 'america/porto_velho', 'america/santarem', 'america/barbados', 'america/martinique', 'america/iqaluit', 'america/blanc-sablon', 'america/puerto_rico', 'america/montevideo', ], ); 1;
nriley/Pester
Source/Manip/Offset/off268.pm
Perl
bsd-2-clause
2,846
package Mojo::Snoo::Link; use Moo; extends 'Mojo::Snoo::Base'; use Mojo::Collection; use Mojo::Snoo::Comment; use constant FIELD => 'name'; has [ qw( approved_by archived author author_flair_css_class author_flair_text banned_by clicked created created_utc distinguished domain downs edited from from_id from_kind gilded hidden id is_self likes link_flair_css_class link_flair_text media media_embed mod_reports name num_comments num_reports over_18 permalink removal_reason report_reasons saved score secure_media secure_media_embed selftext selftext_html stickied subreddit subreddit_id suggested_sort thumbnail title ups url user_reports visited ) ] => (is => 'ro', predicate => 1); sub BUILDARGS { shift->SUPER::BUILDARGS(@_ == 1 ? (id => shift) : @_) } sub _get_comments { my $cb; # callback optional my ($self, $limit, $sort, $time) = map { # ref($_) eq 'CODE' && ($cb = $_) ? () : $_; } @_; my $path = '/comments/' . $self->id; my %params; $params{sort} = $sort if $sort; $params{t} = $time if $time; $params{limit} = $limit if $limit; my $res = $self->_do_request('GET', $path, %params); $res->$cb if $cb; my @children = map { $_->{kind} eq 't1' ? $_->{data} : () } map { @{$_->{data}{children}} } @{$res->json}; my %args = map { $_ => $self->$_ } ( qw( username password client_id client_secret ) ); Mojo::Collection->new(map { Mojo::Snoo::Comment->new(%args, %$_) } @children); } sub _vote { my ($self, $direction) = @_; my %params = ( dir => $direction, id => $self->name, ); $self->_do_request('POST', '/api/vote', %params); } # defaults to comments_hot? # TODO pass params: # http://www.reddit.com/dev/api#GET_comments_{article} sub comments { shift->_get_comments(@_) } sub upvote { shift->_vote(1) } sub downvote { shift->_vote(-1) } sub unvote { shift->_vote(0) } # TODO support category (gold accounts only) sub save { my $self = shift; $self->_do_request('POST', '/api/save', id => $self->name); } # TODO support category (gold accounts only) sub unsave { my $self = shift; $self->_do_request('POST', '/api/unsave', id => $self->name); } 1; __END__ =head1 NAME Mojo::Snoo::Link - Mojo wrapper for Reddit Links (t3_ Things) =head1 SYNOPSIS use Mojo::Snoo::Link; # OAuth ONLY. Reddit is deprecating cookie auth soon. my $link = Mojo::Snoo::Link->new( id => '36x619', username => 'foobar', password => 'very_secret', client_id => 'oauth_client_id', client_secret => 'very_secret_oauth', ); # save this link $link->save(); =head1 ATTRIBUTES =head2 id The ID of the link. This is required for object instantiation. The constructor can accept a single string value or key/value pairs. Examples: Mojo::Snoo::Link->new('36x619')->id; Mojo::Snoo::Link->new(id => '36x619')->id; =head1 METHODS =head2 comments Returns a L<Mojo::Collection> object containing a list of L<Mojo::Snoo::Comment> objects. GET /r/$subreddit/comments/article Accepts arguments for limit and callback (in that order). =head1 API DOCUMENTATION Please see the official L<Reddit API documentation|http://www.reddit.com/dev/api> for more details regarding the usage of endpoints. For a better idea of how OAuth works, see the L<Quick Start|https://github.com/reddit/reddit/wiki/OAuth2-Quick-Start-Example> and the L<full documentation|https://github.com/reddit/reddit/wiki/OAuth2>. There is also a lot of useful information of the L<redditdev subreddit|http://www.reddit.com/r/redditdev>. =head1 LICENSE The (two-clause) FreeBSD License. See LICENSE for details.
mcmillhj/Mojo-Snoo
lib/Mojo/Snoo/Link.pm
Perl
bsd-2-clause
4,089
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 2600 26FF END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/MiscSymb.pl
Perl
mit
433
package File::Spec::OS2; use strict; use vars qw(@ISA $VERSION); require File::Spec::Unix; $VERSION = '3.63_01'; $VERSION =~ tr/_//d; @ISA = qw(File::Spec::Unix); sub devnull { return "/dev/nul"; } sub case_tolerant { return 1; } sub file_name_is_absolute { my ($self,$file) = @_; return scalar($file =~ m{^([a-z]:)?[\\/]}is); } sub path { my $path = $ENV{PATH}; $path =~ s:\\:/:g; my @path = split(';',$path); foreach (@path) { $_ = '.' if $_ eq '' } return @path; } sub _cwd { # In OS/2 the "require Cwd" is unnecessary bloat. return Cwd::sys_cwd(); } sub tmpdir { my $cached = $_[0]->_cached_tmpdir(qw 'TMPDIR TEMP TMP'); return $cached if defined $cached; my @d = @ENV{qw(TMPDIR TEMP TMP)}; # function call could autovivivy $_[0]->_cache_tmpdir( $_[0]->_tmpdir( @d, '/tmp', '/' ), qw 'TMPDIR TEMP TMP' ); } sub catdir { my $self = shift; my @args = @_; foreach (@args) { tr[\\][/]; # append a backslash to each argument unless it has one there $_ .= "/" unless m{/$}; } return $self->canonpath(join('', @args)); } sub canonpath { my ($self,$path) = @_; return unless defined $path; $path =~ s/^([a-z]:)/\l$1/s; $path =~ s|\\|/|g; $path =~ s|([^/])/+|$1/|g; # xx////xx -> xx/xx $path =~ s|(/\.)+/|/|g; # xx/././xx -> xx/xx $path =~ s|^(\./)+(?=[^/])||s; # ./xx -> xx $path =~ s|/\Z(?!\n)|| unless $path =~ m#^([a-z]:)?/\Z(?!\n)#si;# xx/ -> xx $path =~ s{^/\.\.$}{/}; # /.. -> / 1 while $path =~ s{^/\.\.}{}; # /../xx -> /xx return $path; } sub splitpath { my ($self,$path, $nofile) = @_; my ($volume,$directory,$file) = ('','',''); if ( $nofile ) { $path =~ m{^( (?:[a-zA-Z]:|(?:\\\\|//)[^\\/]+[\\/][^\\/]+)? ) (.*) }xs; $volume = $1; $directory = $2; } else { $path =~ m{^ ( (?: [a-zA-Z]: | (?:\\\\|//)[^\\/]+[\\/][^\\/]+ )? ) ( (?:.*[\\\\/](?:\.\.?\Z(?!\n))?)? ) (.*) }xs; $volume = $1; $directory = $2; $file = $3; } return ($volume,$directory,$file); } sub splitdir { my ($self,$directories) = @_ ; split m|[\\/]|, $directories, -1; } sub catpath { my ($self,$volume,$directory,$file) = @_; # If it's UNC, make sure the glue separator is there, reusing # whatever separator is first in the $volume $volume .= $1 if ( $volume =~ m@^([\\/])[\\/][^\\/]+[\\/][^\\/]+\Z(?!\n)@s && $directory =~ m@^[^\\/]@s ) ; $volume .= $directory ; # If the volume is not just A:, make sure the glue separator is # there, reusing whatever separator is first in the $volume if possible. if ( $volume !~ m@^[a-zA-Z]:\Z(?!\n)@s && $volume =~ m@[^\\/]\Z(?!\n)@ && $file =~ m@[^\\/]@ ) { $volume =~ m@([\\/])@ ; my $sep = $1 ? $1 : '/' ; $volume .= $sep ; } $volume .= $file ; return $volume ; } sub abs2rel { my($self,$path,$base) = @_; # Clean up $path if ( ! $self->file_name_is_absolute( $path ) ) { $path = $self->rel2abs( $path ) ; } else { $path = $self->canonpath( $path ) ; } # Figure out the effective $base and clean it up. if ( !defined( $base ) || $base eq '' ) { $base = $self->_cwd(); } elsif ( ! $self->file_name_is_absolute( $base ) ) { $base = $self->rel2abs( $base ) ; } else { $base = $self->canonpath( $base ) ; } # Split up paths my ( $path_volume, $path_directories, $path_file ) = $self->splitpath( $path, 1 ) ; my ( $base_volume, $base_directories ) = $self->splitpath( $base, 1 ) ; return $path unless $path_volume eq $base_volume; # Now, remove all leading components that are the same my @pathchunks = $self->splitdir( $path_directories ); my @basechunks = $self->splitdir( $base_directories ); while ( @pathchunks && @basechunks && lc( $pathchunks[0] ) eq lc( $basechunks[0] ) ) { shift @pathchunks ; shift @basechunks ; } # No need to catdir, we know these are well formed. $path_directories = CORE::join( '/', @pathchunks ); $base_directories = CORE::join( '/', @basechunks ); # $base_directories now contains the directories the resulting relative # path must ascend out of before it can descend to $path_directory. So, # replace all names with $parentDir #FA Need to replace between backslashes... $base_directories =~ s|[^\\/]+|..|g ; # Glue the two together, using a separator if necessary, and preventing an # empty result. #FA Must check that new directories are not empty. if ( $path_directories ne '' && $base_directories ne '' ) { $path_directories = "$base_directories/$path_directories" ; } else { $path_directories = "$base_directories$path_directories" ; } return $self->canonpath( $self->catpath( "", $path_directories, $path_file ) ) ; } sub rel2abs { my ($self,$path,$base ) = @_; if ( ! $self->file_name_is_absolute( $path ) ) { if ( !defined( $base ) || $base eq '' ) { $base = $self->_cwd(); } elsif ( ! $self->file_name_is_absolute( $base ) ) { $base = $self->rel2abs( $base ) ; } else { $base = $self->canonpath( $base ) ; } my ( $path_directories, $path_file ) = ($self->splitpath( $path, 1 ))[1,2] ; my ( $base_volume, $base_directories ) = $self->splitpath( $base, 1 ) ; $path = $self->catpath( $base_volume, $self->catdir( $base_directories, $path_directories ), $path_file ) ; } return $self->canonpath( $path ) ; } 1; __END__ =head1 NAME File::Spec::OS2 - methods for OS/2 file specs =head1 SYNOPSIS require File::Spec::OS2; # Done internally by File::Spec if needed =head1 DESCRIPTION See L<File::Spec> and L<File::Spec::Unix>. This package overrides the implementation of these methods, not the semantics. Amongst the changes made for OS/2 are... =over 4 =item tmpdir Modifies the list of places temp directory information is looked for. $ENV{TMPDIR} $ENV{TEMP} $ENV{TMP} /tmp / =item splitpath Volumes can be drive letters or UNC sharenames (\\server\share). =back =head1 COPYRIGHT Copyright (c) 2004 by the Perl 5 Porters. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
operepo/ope
bin/usr/lib/perl5/core_perl/File/Spec/OS2.pm
Perl
mit
6,859
# # 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 snmp_standard::mode::mtausage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Digest::MD5 qw(md5_hex); sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 1, cb_prefix_output => 'prefix_global_output', message_multiple => 'All MTA are ok', skipped_code => { -10 => 1 } }, { name => 'mtagrp', type => 1, cb_prefix_output => 'prefix_mtagrp_output', message_multiple => 'All MTA groups are ok', skipped_code => { -10 => 1 } } ]; $self->{maps_counters}->{global} = [ { label => 'total-received-messages', set => { key_values => [ { name => 'mtaReceivedMessages', diff => 1 }, { name => 'display' } ], output_template => 'Total Received Messages : %s', output_error_template => "Total Received Messages : %s", perfdatas => [ { label => 'total_received_messages', value => 'mtaReceivedMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-received-volume', set => { key_values => [ { name => 'mtaReceivedVolume', diff => 1 }, { name => 'display' } ], output_template => 'Total Received Volume : %s %s', output_error_template => "Total Received Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'total_received_volume', value => 'mtaReceivedVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-stored-messages', set => { key_values => [ { name => 'mtaStoredMessages' }, { name => 'display' } ], output_template => 'Total Stored Messages : %s', output_error_template => "Total Stored Messages : %s", perfdatas => [ { label => 'total_stored_messages', value => 'mtaStoredMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-stored-volume', set => { key_values => [ { name => 'mtaStoredVolume' }, { name => 'display' } ], output_template => 'Total Stored Volume : %s %s', output_error_template => "Total Stored Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'total_stored_volume', value => 'mtaStoredVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-transmitted-messages', set => { key_values => [ { name => 'mtaTransmittedMessages', diff => 1 }, { name => 'display' } ], output_template => 'Total Transmitted Messages : %s', output_error_template => "Total Transmitted Messages : %s", perfdatas => [ { label => 'total_transmitted_messages', value => 'mtaTransmittedMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-transmitted-volume', set => { key_values => [ { name => 'mtaTransmittedVolume', diff => 1 }, { name => 'display' } ], output_template => 'Total Transmitted Volume : %s %s', output_error_template => "Total Transmitted Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'total_transmitted_volume', value => 'mtaTransmittedVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, ]; $self->{maps_counters}->{mtagrp} = [ { label => 'received-messages', set => { key_values => [ { name => 'mtaGroupReceivedMessages', diff => 1 }, { name => 'display' } ], output_template => 'Received Messages : %s', output_error_template => "Received Messages : %s", perfdatas => [ { label => 'received_messages', value => 'mtaGroupReceivedMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'received-volume', set => { key_values => [ { name => 'mtaGroupReceivedVolume', diff => 1 }, { name => 'display' } ], output_template => 'Received Volume : %s %s', output_error_template => "Received Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'received_volume', value => 'mtaGroupReceivedVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'stored-messages', set => { key_values => [ { name => 'mtaGroupStoredMessages' }, { name => 'display' } ], output_template => 'Stored Messages : %s', output_error_template => "Stored Messages : %s", perfdatas => [ { label => 'stored_messages', value => 'mtaGroupStoredMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'stored-volume', set => { key_values => [ { name => 'mtaGroupStoredVolume' }, { name => 'display' } ], output_template => 'Stored Volume : %s %s', output_error_template => "Stored Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'stored_volume', value => 'mtaGroupStoredVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'transmitted-messages', set => { key_values => [ { name => 'mtaGroupTransmittedMessages', diff => 1 }, { name => 'display' } ], output_template => 'Transmitted Messages : %s', output_error_template => "Transmitted Messages : %s", perfdatas => [ { label => 'transmitted_messages', value => 'mtaGroupTransmittedMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'transmitted-volume', set => { key_values => [ { name => 'mtaGroupTransmittedVolume', diff => 1 }, { name => 'display' } ], output_template => 'Transmitted Volume : %s %s', output_error_template => "Transmitted Volume : %s", output_change_bytes => 1, perfdatas => [ { label => 'transmitted_volume', value => 'mtaGroupTransmittedVolume_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'rejected-messages', set => { key_values => [ { name => 'mtaGroupRejectedMessages', diff => 1 }, { name => 'display' } ], output_template => 'Rejected Messages : %s', output_error_template => "Rejected Messages : %s", perfdatas => [ { label => 'rejected_messages', value => 'mtaGroupRejectedMessages_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, ]; } sub prefix_global_output { my ($self, %options) = @_; return "MTA '" . $options{instance_value}->{display} . "' "; } sub prefix_mtagrp_output { my ($self, %options) = @_; return "MTA group '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "filter-name:s" => { name => 'filter_name' }, }); return $self; } my $mapping = { mtaReceivedMessages => { oid => '.1.3.6.1.2.1.28.1.1.1' }, mtaStoredMessages => { oid => '.1.3.6.1.2.1.28.1.1.2' }, mtaTransmittedMessages => { oid => '.1.3.6.1.2.1.28.1.1.3' }, mtaReceivedVolume => { oid => '.1.3.6.1.2.1.28.1.1.4' }, mtaStoredVolume => { oid => '.1.3.6.1.2.1.28.1.1.5' }, mtaTransmittedVolume => { oid => '.1.3.6.1.2.1.28.1.1.6' }, }; my $mapping2 = { mtaGroupReceivedMessages => { oid => '.1.3.6.1.2.1.28.2.1.2' }, mtaGroupRejectedMessages => { oid => '.1.3.6.1.2.1.28.2.1.3' }, mtaGroupStoredMessages => { oid => '.1.3.6.1.2.1.28.2.1.4' }, mtaGroupTransmittedMessages => { oid => '.1.3.6.1.2.1.28.2.1.5' }, mtaGroupReceivedVolume => { oid => '.1.3.6.1.2.1.28.2.1.6' }, mtaGroupStoredVolume => { oid => '.1.3.6.1.2.1.28.2.1.7' }, mtaGroupTransmittedVolume => { oid => '.1.3.6.1.2.1.28.2.1.8' }, mtaGroupName => { oid => '.1.3.6.1.2.1.28.2.1.25' }, }; my $oid_mtaEntry = '.1.3.6.1.2.1.28.1.1'; my $oid_mtaGroupEntry = '.1.3.6.1.2.1.28.2.1'; sub manage_selection { my ($self, %options) = @_; my $snmp_result = $options{snmp}->get_multiple_table(oids => [ { oid => $oid_mtaEntry }, { oid => $oid_mtaGroupEntry }, ], nothing_quit => 1); $self->{global} = {}; foreach my $oid (keys %{$snmp_result->{$oid_mtaEntry}}) { next if ($oid !~ /^$mapping->{mtaReceivedMessages}->{oid}\.(.*)$/); my $instance = $1; my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result->{$oid_mtaEntry}, instance => $instance); foreach (('mtaReceivedVolume', 'mtaStoredVolume', 'mtaTransmittedVolume')) { $result->{$_} *= 1024 if (defined($result->{$_})); } $self->{global}->{$instance} = { display => $instance, %$result }; } $self->{mtagrp} = {}; foreach my $oid (keys %{$snmp_result->{$oid_mtaGroupEntry}}) { next if ($oid !~ /^$mapping2->{mtaGroupName}->{oid}\.(.*?)\.(.*?)$/); my ($applIndex, $mtaGroupIndex) = ($1, $2); my $result = $options{snmp}->map_instance(mapping => $mapping2, results => $snmp_result->{$oid_mtaGroupEntry}, instance => $applIndex . '.' . $mtaGroupIndex); if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $result->{mtaGroupName} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping '" . $result->{mtaGroupName} . "': no matching filter.", debug => 1); next; } foreach (('mtaGroupReceivedVolume', 'mtaGroupStoredVolume', 'mtaGroupTransmittedVolume')) { $result->{$_} *= 1024 if (defined($result->{$_})); } $self->{mtagrp}->{$applIndex . '.' . $result->{mtaGroupName}} = { display => $applIndex . '.' . $result->{mtaGroupName}, %$result }; } $self->{cache_name} = $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' . (defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all')); } 1; __END__ =head1 MODE Check MTA usage. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='received' =item B<--filter-name> Filter MTA group name (can be a regexp). =item B<--warning-*> Threshold warning. Can be: 'total-received-messages', 'total-received-volume', 'total-stored-messages', 'total-stored-volume', 'total-transmitted-messages', 'total-transmitted-volume', 'received-messages', 'received-volume', 'stored-messages', 'stored-volume', 'transmitted-messages', 'transmitted-volume', 'rejected-messages'. =item B<--critical-*> Threshold critical. Can be: 'total-received-messages', 'total-received-volume', 'total-stored-messages', 'total-stored-volume', 'total-transmitted-messages', 'total-transmitted-volume', 'received-messages', 'received-volume', 'stored-messages', 'stored-volume', 'transmitted-messages', 'transmitted-volume', 'rejected-messages'. =back =cut
nichols-356/centreon-plugins
snmp_standard/mode/mtausage.pm
Perl
apache-2.0
13,996
#!/usr/bin/env perl # Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html # # ==================================================================== # Written by Andy Polyakov <appro@openssl.org> for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # ==================================================================== # # [ABI- and endian-neutral] Keccak-1600 for C64x. # # June 2017. # # This is straightforward KECCAK_1X_ALT variant (see sha/keccak1600.c) # with bit interleaving. 64-bit values are simply split between A- and # B-files, with A-file holding least significant halves. This works # out perfectly, because all operations including cross-communications # [in rotate operations] are always complementary. Performance is # [incredible for a 32-bit processor] 10.9 cycles per processed byte # for r=1088, which corresponds to SHA3-256. This is >15x faster than # compiler-generated KECCAK_1X_ALT code, and >10x than other variants. # On average processor ends up issuing ~4.5 instructions per cycle... my @A = map([ $_, ($_+1), ($_+2), ($_+3), ($_+4) ], (5,10,16,21,26)); $A[1][4] = 31; # B14 is reserved, A14 is used as iota[] ($A[3][0],$A[4][1]) = ($A[4][1],$A[3][0]); my @C = (0..4,$A[3][0],$A[4][0]); my $iotas = "A14"; my @rhotates = ([ 0, 1, 62, 28, 27 ], [ 36, 44, 6, 55, 20 ], [ 3, 10, 43, 25, 39 ], [ 41, 45, 15, 21, 8 ], [ 18, 2, 61, 56, 14 ]); sub ROL64 { my ($src,$rot,$dst,$p) = @_; if ($rot&1) { $code.=<<___; $p ROTL B$src,$rot/2+1,A$dst || ROTL A$src,$rot/2, B$dst ___ } else { $code.=<<___; $p ROTL A$src,$rot/2,A$dst || ROTL B$src,$rot/2,B$dst ___ } } ######################################################################## # Stack frame layout # # SP--->+------+------+ # | | | # +1--->+------+------+<- -9 below 4 slots are used by KeccakF1600_int # | | | # +2--->+------+------+<- -8 # | | | # +3--->+------+------+<- -7 # | A2 | A3 | A3:A2 are preserved by KeccakF1600_int # +4--->+------+------+<- -6 # | B2 | B3 | B3:B2 are preserved by KeccakF1600_int # +5--->+------+------+<- -5 below is ABI-compliant layout # | A10 | A11 | # +6--->+------+------+<- -4 # | A12 | A13 | # +7--->+------+------+<- -3 # | A14 | B3 | # +8--->+------+------+<- -2 # | B10 | B11 | # +9--->+------+------+<- -1 # | B12 | B13 | # +------+------+<---FP # | A15 | # +------+-- $code.=<<___; .text .if .ASSEMBLER_VERSION<7000000 .asg 0,__TI_EABI__ .endif .if __TI_EABI__ .nocmp .asg KeccakF1600,_KeccakF1600 .asg SHA3_absorb,_SHA3_absorb .asg SHA3_squeeze,_SHA3_squeeze .endif .asg B3,RA .asg A15,FP .asg B15,SP .align 32 _KeccakF1600_int: .asmfunc STDW A3:A2,*FP[-7] || STDW B3:B2,*SP[4] _KeccakF1600_cheat: .if __TI_EABI__ ADDKPC _KeccakF1600_int,B0 || MVKL \$PCR_OFFSET(iotas,_KeccakF1600_int),$iotas MVKH \$PCR_OFFSET(iotas,_KeccakF1600_int),$iotas .else ADDKPC _KeccakF1600_int,B0 || MVKL (iotas-_KeccakF1600_int),$iotas MVKH (iotas-_KeccakF1600_int),$iotas .endif ADD B0,$iotas,$iotas loop?: XOR A$A[0][2],A$A[1][2],A$C[2] ; Theta || XOR B$A[0][2],B$A[1][2],B$C[2] || XOR A$A[0][3],A$A[1][3],A$C[3] || XOR B$A[0][3],B$A[1][3],B$C[3] || XOR A$A[0][0],A$A[1][0],A$C[0] || XOR B$A[0][0],B$A[1][0],B$C[0] XOR A$A[2][2],A$C[2],A$C[2] || XOR B$A[2][2],B$C[2],B$C[2] || XOR A$A[2][3],A$C[3],A$C[3] || XOR B$A[2][3],B$C[3],B$C[3] || XOR A$A[2][0],A$C[0],A$C[0] || XOR B$A[2][0],B$C[0],B$C[0] XOR A$A[3][2],A$C[2],A$C[2] || XOR B$A[3][2],B$C[2],B$C[2] || XOR A$A[3][3],A$C[3],A$C[3] || XOR B$A[3][3],B$C[3],B$C[3] || XOR A$A[3][0],A$C[0],A$C[0] || XOR B$A[3][0],B$C[0],B$C[0] XOR A$A[4][2],A$C[2],A$C[2] || XOR B$A[4][2],B$C[2],B$C[2] || XOR A$A[4][3],A$C[3],A$C[3] || XOR B$A[4][3],B$C[3],B$C[3] || XOR A$A[4][0],A$C[0],A$C[0] || XOR B$A[4][0],B$C[0],B$C[0] XOR A$A[0][4],A$A[1][4],A$C[4] || XOR B$A[0][4],B$A[1][4],B$C[4] || XOR A$A[0][1],A$A[1][1],A$C[1] || XOR B$A[0][1],B$A[1][1],B$C[1] || STDW A$A[3][0]:A$A[4][0],*SP[1] ; offload some data STDW B$A[3][0]:B$A[4][0],*SP[2] || XOR A$A[2][4],A$C[4],A$C[4] || XOR B$A[2][4],B$C[4],B$C[4] || XOR A$A[2][1],A$C[1],A$C[1] || XOR B$A[2][1],B$C[1],B$C[1] || ROTL B$C[2],1,A$C[5] ; ROL64(C[2],1) || ROTL A$C[2],0,B$C[5] XOR A$A[3][4],A$C[4],A$C[4] || XOR B$A[3][4],B$C[4],B$C[4] || XOR A$A[3][1],A$C[1],A$C[1] || XOR B$A[3][1],B$C[1],B$C[1] || ROTL B$C[3],1,A$C[6] ; ROL64(C[3],1) || ROTL A$C[3],0,B$C[6] XOR A$A[4][4],A$C[4],A$C[4] || XOR B$A[4][4],B$C[4],B$C[4] || XOR A$A[4][1],A$C[1],A$C[1] || XOR B$A[4][1],B$C[1],B$C[1] || XOR A$C[0],A$C[5],A$C[5] ; C[0] ^ ROL64(C[2],1) || XOR B$C[0],B$C[5],B$C[5] XOR A$C[5],A$A[0][1],A$A[0][1] || XOR B$C[5],B$A[0][1],B$A[0][1] || XOR A$C[5],A$A[1][1],A$A[1][1] || XOR B$C[5],B$A[1][1],B$A[1][1] || XOR A$C[5],A$A[2][1],A$A[2][1] || XOR B$C[5],B$A[2][1],B$A[2][1] XOR A$C[5],A$A[3][1],A$A[3][1] || XOR B$C[5],B$A[3][1],B$A[3][1] || XOR A$C[5],A$A[4][1],A$A[4][1] || XOR B$C[5],B$A[4][1],B$A[4][1] || ROTL B$C[4],1,A$C[5] ; ROL64(C[4],1) || ROTL A$C[4],0,B$C[5] || XOR A$C[1],A$C[6],A$C[6] ; C[1] ^ ROL64(C[3],1) || XOR B$C[1],B$C[6],B$C[6] XOR A$C[6],A$A[0][2],A$A[0][2] || XOR B$C[6],B$A[0][2],B$A[0][2] || XOR A$C[6],A$A[1][2],A$A[1][2] || XOR B$C[6],B$A[1][2],B$A[1][2] || XOR A$C[6],A$A[2][2],A$A[2][2] || XOR B$C[6],B$A[2][2],B$A[2][2] || ROTL B$C[1],1,A$C[1] ; ROL64(C[1],1) || ROTL A$C[1],0,B$C[1] XOR A$C[6],A$A[3][2],A$A[3][2] || XOR B$C[6],B$A[3][2],B$A[3][2] || XOR A$C[6],A$A[4][2],A$A[4][2] || XOR B$C[6],B$A[4][2],B$A[4][2] || ROTL B$C[0],1,A$C[6] ; ROL64(C[0],1) || ROTL A$C[0],0,B$C[6] || XOR A$C[5],A$C[2],A$C[2] ; C[2] ^= ROL64(C[4],1) || XOR B$C[5],B$C[2],B$C[2] XOR A$C[2],A$A[0][3],A$A[0][3] || XOR B$C[2],B$A[0][3],B$A[0][3] || XOR A$C[2],A$A[1][3],A$A[1][3] || XOR B$C[2],B$A[1][3],B$A[1][3] || XOR A$C[2],A$A[2][3],A$A[2][3] || XOR B$C[2],B$A[2][3],B$A[2][3] XOR A$C[6],A$C[3],A$C[3] ; C[3] ^= ROL64(C[0],1) || XOR B$C[6],B$C[3],B$C[3] || LDDW *FP[-9],A$A[3][0]:A$A[4][0] ; restore offloaded data || LDDW *SP[2],B$A[3][0]:B$A[4][0] || XOR A$C[2],A$A[3][3],A$A[3][3] || XOR B$C[2],B$A[3][3],B$A[3][3] XOR A$C[2],A$A[4][3],A$A[4][3] || XOR B$C[2],B$A[4][3],B$A[4][3] || XOR A$C[3],A$A[0][4],A$A[0][4] || XOR B$C[3],B$A[0][4],B$A[0][4] || XOR A$C[3],A$A[1][4],A$A[1][4] || XOR B$C[3],B$A[1][4],B$A[1][4] XOR A$C[3],A$A[2][4],A$A[2][4] || XOR B$C[3],B$A[2][4],B$A[2][4] || XOR A$C[3],A$A[3][4],A$A[3][4] || XOR B$C[3],B$A[3][4],B$A[3][4] || XOR A$C[3],A$A[4][4],A$A[4][4] || XOR B$C[3],B$A[4][4],B$A[4][4] XOR A$C[1],A$C[4],A$C[4] ; C[4] ^= ROL64(C[1],1) || XOR B$C[1],B$C[4],B$C[4] || MV A$A[0][1],A$C[1] ; Rho+Pi, "early start" || MV B$A[0][1],B$C[1] ___ &ROL64 ($A[1][1],$rhotates[1][1],$A[0][1],"||"); $code.=<<___; XOR A$C[4],A$A[0][0],A$A[0][0] || XOR B$C[4],B$A[0][0],B$A[0][0] || XOR A$C[4],A$A[1][0],A$A[1][0] || XOR B$C[4],B$A[1][0],B$A[1][0] || MV A$A[0][3],A$C[3] || MV B$A[0][3],B$C[3] ___ &ROL64 ($A[3][3],$rhotates[3][3],$A[0][3],"||"); $code.=<<___; XOR A$C[4],A$A[2][0],A$A[2][0] || XOR B$C[4],B$A[2][0],B$A[2][0] || XOR A$C[4],A$A[3][0],A$A[3][0] || XOR B$C[4],B$A[3][0],B$A[3][0] || MV A$A[0][2],A$C[2] || MV B$A[0][2],B$C[2] ___ &ROL64 ($A[2][2],$rhotates[2][2],$A[0][2],"||"); $code.=<<___; XOR A$C[4],A$A[4][0],A$A[4][0] || XOR B$C[4],B$A[4][0],B$A[4][0] || MV A$A[0][4],A$C[4] || MV B$A[0][4],B$C[4] ___ &ROL64 ($A[4][4],$rhotates[4][4],$A[0][4],"||"); &ROL64 ($A[1][4],$rhotates[1][4],$A[1][1]); $code.=<<___; || LDW *${iotas}++[2],A$C[0] ___ &ROL64 ($A[2][3],$rhotates[2][3],$A[2][2]); $code.=<<___; || LDW *${iotas}[-1],B$C[0] ___ &ROL64 ($A[3][2],$rhotates[3][2],$A[3][3]); &ROL64 ($A[4][1],$rhotates[4][1],$A[4][4]); &ROL64 ($A[4][2],$rhotates[4][2],$A[1][4]); &ROL64 ($A[3][4],$rhotates[3][4],$A[2][3]); &ROL64 ($A[2][1],$rhotates[2][1],$A[3][2]); &ROL64 ($A[1][3],$rhotates[1][3],$A[4][1]); &ROL64 ($A[2][4],$rhotates[2][4],$A[4][2]); &ROL64 ($A[4][3],$rhotates[4][3],$A[3][4]); &ROL64 ($A[1][2],$rhotates[1][2],$A[2][1]); &ROL64 ($A[3][1],$rhotates[3][1],$A[1][3]); &ROL64 ($A[4][0],$rhotates[4][0],$A[2][4]); &ROL64 ($A[3][0],$rhotates[3][0],$A[4][3]); &ROL64 ($A[2][0],$rhotates[2][0],$A[1][2]); &ROL64 ($A[1][0],$rhotates[1][0],$A[3][1]); #&ROL64 ($C[3], $rhotates[0][3],$A[1][0]); # moved below &ROL64 ($C[1], $rhotates[0][1],$A[2][0]); &ROL64 ($C[4], $rhotates[0][4],$A[3][0]); &ROL64 ($C[2], $rhotates[0][2],$A[4][0]); $code.=<<___; || ANDN A$A[0][2],A$A[0][1],A$C[4] ; Chi+Iota || ANDN B$A[0][2],B$A[0][1],B$C[4] || ANDN A$A[0][3],A$A[0][2],A$C[1] || ANDN B$A[0][3],B$A[0][2],B$C[1] || ANDN A$A[0][4],A$A[0][3],A$C[2] || ANDN B$A[0][4],B$A[0][3],B$C[2] ___ &ROL64 ($C[3], $rhotates[0][3],$A[1][0]); $code.=<<___; || ANDN A$A[0][0],A$A[0][4],A$C[3] || ANDN B$A[0][0],B$A[0][4],B$C[3] || XOR A$C[4],A$A[0][0],A$A[0][0] || XOR B$C[4],B$A[0][0],B$A[0][0] || ANDN A$A[0][1],A$A[0][0],A$C[4] || ANDN B$A[0][1],B$A[0][0],B$C[4] XOR A$C[1],A$A[0][1],A$A[0][1] || XOR B$C[1],B$A[0][1],B$A[0][1] || XOR A$C[2],A$A[0][2],A$A[0][2] || XOR B$C[2],B$A[0][2],B$A[0][2] || XOR A$C[3],A$A[0][3],A$A[0][3] || XOR B$C[3],B$A[0][3],B$A[0][3] XOR A$C[4],A$A[0][4],A$A[0][4] || XOR B$C[4],B$A[0][4],B$A[0][4] || XOR A$C[0],A$A[0][0],A$A[0][0] ; A[0][0] ^= iotas[i++]; || XOR B$C[0],B$A[0][0],B$A[0][0] || EXTU $iotas,24,24,A0 ; A0 is A$C[0], as we done? ANDN A$A[1][2],A$A[1][1],A$C[4] || ANDN B$A[1][2],B$A[1][1],B$C[4] || ANDN A$A[1][3],A$A[1][2],A$C[1] || ANDN B$A[1][3],B$A[1][2],B$C[1] || ANDN A$A[1][4],A$A[1][3],A$C[2] || ANDN B$A[1][4],B$A[1][3],B$C[2] ANDN A$A[1][0],A$A[1][4],A$C[3] || ANDN B$A[1][0],B$A[1][4],B$C[3] || XOR A$C[4],A$A[1][0],A$A[1][0] || XOR B$C[4],B$A[1][0],B$A[1][0] || ANDN A$A[1][1],A$A[1][0],A$C[4] || ANDN B$A[1][1],B$A[1][0],B$C[4] XOR A$C[1],A$A[1][1],A$A[1][1] || XOR B$C[1],B$A[1][1],B$A[1][1] || XOR A$C[2],A$A[1][2],A$A[1][2] || XOR B$C[2],B$A[1][2],B$A[1][2] || XOR A$C[3],A$A[1][3],A$A[1][3] || XOR B$C[3],B$A[1][3],B$A[1][3] XOR A$C[4],A$A[1][4],A$A[1][4] || XOR B$C[4],B$A[1][4],B$A[1][4] || ANDN A$A[2][2],A$A[2][1],A$C[4] || ANDN B$A[2][2],B$A[2][1],B$C[4] || ANDN A$A[2][3],A$A[2][2],A$C[1] || ANDN B$A[2][3],B$A[2][2],B$C[1] ANDN A$A[2][4],A$A[2][3],A$C[2] || ANDN B$A[2][4],B$A[2][3],B$C[2] || ANDN A$A[2][0],A$A[2][4],A$C[3] || ANDN B$A[2][0],B$A[2][4],B$C[3] || XOR A$C[4],A$A[2][0],A$A[2][0] || XOR B$C[4],B$A[2][0],B$A[2][0] ANDN A$A[2][1],A$A[2][0],A$C[4] || ANDN B$A[2][1],B$A[2][0],B$C[4] || XOR A$C[1],A$A[2][1],A$A[2][1] || XOR B$C[1],B$A[2][1],B$A[2][1] || XOR A$C[2],A$A[2][2],A$A[2][2] || XOR B$C[2],B$A[2][2],B$A[2][2] XOR A$C[3],A$A[2][3],A$A[2][3] || XOR B$C[3],B$A[2][3],B$A[2][3] || XOR A$C[4],A$A[2][4],A$A[2][4] || XOR B$C[4],B$A[2][4],B$A[2][4] ANDN A$A[3][2],A$A[3][1],A$C[4] || ANDN B$A[3][2],B$A[3][1],B$C[4] || ANDN A$A[3][3],A$A[3][2],A$C[1] || ANDN B$A[3][3],B$A[3][2],B$C[1] || ANDN A$A[3][4],A$A[3][3],A$C[2] || ANDN B$A[3][4],B$A[3][3],B$C[2] ANDN A$A[3][0],A$A[3][4],A$C[3] || ANDN B$A[3][0],B$A[3][4],B$C[3] || XOR A$C[4],A$A[3][0],A$A[3][0] || XOR B$C[4],B$A[3][0],B$A[3][0] || ANDN A$A[3][1],A$A[3][0],A$C[4] || ANDN B$A[3][1],B$A[3][0],B$C[4] XOR A$C[1],A$A[3][1],A$A[3][1] || XOR B$C[1],B$A[3][1],B$A[3][1] || XOR A$C[2],A$A[3][2],A$A[3][2] || XOR B$C[2],B$A[3][2],B$A[3][2] || XOR A$C[3],A$A[3][3],A$A[3][3] ||[A0] BNOP loop? XOR B$C[3],B$A[3][3],B$A[3][3] || XOR A$C[4],A$A[3][4],A$A[3][4] || XOR B$C[4],B$A[3][4],B$A[3][4] ||[!A0] LDDW *FP[-7],A3:A2 ||[!A0] LDDW *SP[4], RA:B2 ANDN A$A[4][2],A$A[4][1],A$C[4] || ANDN B$A[4][2],B$A[4][1],B$C[4] || ANDN A$A[4][3],A$A[4][2],A$C[1] || ANDN B$A[4][3],B$A[4][2],B$C[1] || ANDN A$A[4][4],A$A[4][3],A$C[2] || ANDN B$A[4][4],B$A[4][3],B$C[2] ANDN A$A[4][0],A$A[4][4],A$C[3] || ANDN B$A[4][0],B$A[4][4],B$C[3] || XOR A$C[4],A$A[4][0],A$A[4][0] || XOR B$C[4],B$A[4][0],B$A[4][0] || ANDN A$A[4][1],A$A[4][0],A$C[4] || ANDN B$A[4][1],B$A[4][0],B$C[4] XOR A$C[1],A$A[4][1],A$A[4][1] || XOR B$C[1],B$A[4][1],B$A[4][1] || XOR A$C[2],A$A[4][2],A$A[4][2] || XOR B$C[2],B$A[4][2],B$A[4][2] || XOR A$C[3],A$A[4][3],A$A[4][3] || XOR B$C[3],B$A[4][3],B$A[4][3] XOR A$C[4],A$A[4][4],A$A[4][4] || XOR B$C[4],B$A[4][4],B$A[4][4] ;;===== branch to loop? is taken here BNOP RA,5 .endasmfunc .newblock .global _KeccakF1600 .align 32 _KeccakF1600: .asmfunc stack_usage(80) STW FP,*SP--(80) ; save frame pointer || MV SP,FP STDW B13:B12,*SP[9] || STDW A13:A12,*FP[-4] STDW B11:B10,*SP[8] || STDW A11:A10,*FP[-5] STW RA, *SP[15] || STW A14,*FP[-6] || MV A4,A2 || ADD 4,A4,B2 LDW *A2++[2],A$A[0][0] ; load A[5][5] || LDW *B2++[2],B$A[0][0] LDW *A2++[2],A$A[0][1] || LDW *B2++[2],B$A[0][1] LDW *A2++[2],A$A[0][2] || LDW *B2++[2],B$A[0][2] LDW *A2++[2],A$A[0][3] || LDW *B2++[2],B$A[0][3] LDW *A2++[2],A$A[0][4] || LDW *B2++[2],B$A[0][4] LDW *A2++[2],A$A[1][0] || LDW *B2++[2],B$A[1][0] LDW *A2++[2],A$A[1][1] || LDW *B2++[2],B$A[1][1] LDW *A2++[2],A$A[1][2] || LDW *B2++[2],B$A[1][2] LDW *A2++[2],A$A[1][3] || LDW *B2++[2],B$A[1][3] LDW *A2++[2],A$A[1][4] || LDW *B2++[2],B$A[1][4] LDW *A2++[2],A$A[2][0] || LDW *B2++[2],B$A[2][0] LDW *A2++[2],A$A[2][1] || LDW *B2++[2],B$A[2][1] LDW *A2++[2],A$A[2][2] || LDW *B2++[2],B$A[2][2] LDW *A2++[2],A$A[2][3] || LDW *B2++[2],B$A[2][3] LDW *A2++[2],A$A[2][4] || LDW *B2++[2],B$A[2][4] LDW *A2++[2],A$A[3][0] || LDW *B2++[2],B$A[3][0] LDW *A2++[2],A$A[3][1] || LDW *B2++[2],B$A[3][1] LDW *A2++[2],A$A[3][2] || LDW *B2++[2],B$A[3][2] LDW *A2++[2],A$A[3][3] || LDW *B2++[2],B$A[3][3] LDW *A2++[2],A$A[3][4] || LDW *B2++[2],B$A[3][4] || BNOP _KeccakF1600_int ADDKPC ret?,RA || LDW *A2++[2],A$A[4][0] || LDW *B2++[2],B$A[4][0] LDW *A2++[2],A$A[4][1] || LDW *B2++[2],B$A[4][1] LDW *A2++[2],A$A[4][2] || LDW *B2++[2],B$A[4][2] LDW *A2++[2],A$A[4][3] || LDW *B2++[2],B$A[4][3] LDW *A2,A$A[4][4] || LDW *B2,B$A[4][4] || ADDK -192,A2 ; rewind || ADDK -192,B2 .align 16 ret?: STW A$A[0][0],*A2++[2] ; store A[5][5] || STW B$A[0][0],*B2++[2] STW A$A[0][1],*A2++[2] || STW B$A[0][1],*B2++[2] STW A$A[0][2],*A2++[2] || STW B$A[0][2],*B2++[2] STW A$A[0][3],*A2++[2] || STW B$A[0][3],*B2++[2] STW A$A[0][4],*A2++[2] || STW B$A[0][4],*B2++[2] STW A$A[1][0],*A2++[2] || STW B$A[1][0],*B2++[2] STW A$A[1][1],*A2++[2] || STW B$A[1][1],*B2++[2] STW A$A[1][2],*A2++[2] || STW B$A[1][2],*B2++[2] STW A$A[1][3],*A2++[2] || STW B$A[1][3],*B2++[2] STW A$A[1][4],*A2++[2] || STW B$A[1][4],*B2++[2] STW A$A[2][0],*A2++[2] || STW B$A[2][0],*B2++[2] STW A$A[2][1],*A2++[2] || STW B$A[2][1],*B2++[2] STW A$A[2][2],*A2++[2] || STW B$A[2][2],*B2++[2] STW A$A[2][3],*A2++[2] || STW B$A[2][3],*B2++[2] STW A$A[2][4],*A2++[2] || STW B$A[2][4],*B2++[2] STW A$A[3][0],*A2++[2] || STW B$A[3][0],*B2++[2] STW A$A[3][1],*A2++[2] || STW B$A[3][1],*B2++[2] STW A$A[3][2],*A2++[2] || STW B$A[3][2],*B2++[2] STW A$A[3][3],*A2++[2] || STW B$A[3][3],*B2++[2] STW A$A[3][4],*A2++[2] || STW B$A[3][4],*B2++[2] LDW *SP[15],RA || LDW *FP[-6],A14 STW A$A[4][0],*A2++[2] || STW B$A[4][0],*B2++[2] STW A$A[4][1],*A2++[2] || STW B$A[4][1],*B2++[2] STW A$A[4][2],*A2++[2] || STW B$A[4][2],*B2++[2] STW A$A[4][3],*A2++[2] || STW B$A[4][3],*B2++[2] STW A$A[4][4],*A2 || STW B$A[4][4],*B2 || ADDK -192,A2 ; rewind MV A2,A4 ; return original A4 || LDDW *SP[8], B11:B10 || LDDW *FP[-5],A11:A10 LDDW *SP[9], B13:B12 || LDDW *FP[-4],A13:A12 || BNOP RA LDW *++SP(80),FP ; restore frame pointer NOP 4 ; wait till FP is committed .endasmfunc .newblock .asg B2,BSZ .asg A2,INP .asg A3,LEN .global _SHA3_absorb .align 32 _SHA3_absorb: .asmfunc stack_usage(80) STW FP,*SP--(80) ; save frame pointer || MV SP,FP STDW B13:B12,*SP[9] || STDW A13:A12,*FP[-4] STDW B11:B10,*SP[8] || STDW A11:A10,*FP[-5] STW RA, *SP[15] || STW A14,*FP[-6] STW A4,*SP[1] ; save A[][] || MV B4,INP ; reassign arguments || MV A6,LEN || MV B6,BSZ || ADD 4,A4,B4 LDW *A4++[2],A$A[0][0] ; load A[5][5] || LDW *B4++[2],B$A[0][0] LDW *A4++[2],A$A[0][1] || LDW *B4++[2],B$A[0][1] LDW *A4++[2],A$A[0][2] || LDW *B4++[2],B$A[0][2] LDW *A4++[2],A$A[0][3] || LDW *B4++[2],B$A[0][3] LDW *A4++[2],A$A[0][4] || LDW *B4++[2],B$A[0][4] LDW *A4++[2],A$A[1][0] || LDW *B4++[2],B$A[1][0] LDW *A4++[2],A$A[1][1] || LDW *B4++[2],B$A[1][1] LDW *A4++[2],A$A[1][2] || LDW *B4++[2],B$A[1][2] LDW *A4++[2],A$A[1][3] || LDW *B4++[2],B$A[1][3] LDW *A4++[2],A$A[1][4] || LDW *B4++[2],B$A[1][4] LDW *A4++[2],A$A[2][0] || LDW *B4++[2],B$A[2][0] LDW *A4++[2],A$A[2][1] || LDW *B4++[2],B$A[2][1] LDW *A4++[2],A$A[2][2] || LDW *B4++[2],B$A[2][2] LDW *A4++[2],A$A[2][3] || LDW *B4++[2],B$A[2][3] LDW *A4++[2],A$A[2][4] || LDW *B4++[2],B$A[2][4] LDW *A4++[2],A$A[3][0] || LDW *B4++[2],B$A[3][0] LDW *A4++[2],A$A[3][1] || LDW *B4++[2],B$A[3][1] LDW *A4++[2],A$A[3][2] || LDW *B4++[2],B$A[3][2] LDW *A4++[2],A$A[3][3] || LDW *B4++[2],B$A[3][3] LDW *A4++[2],A$A[3][4] || LDW *B4++[2],B$A[3][4] LDW *A4++[2],A$A[4][0] || LDW *B4++[2],B$A[4][0] LDW *A4++[2],A$A[4][1] || LDW *B4++[2],B$A[4][1] LDW *A4++[2],A$A[4][2] || LDW *B4++[2],B$A[4][2] LDW *A4++[2],A$A[4][3] || LDW *B4++[2],B$A[4][3] LDW *A4,A$A[4][4] || LDW *B4,B$A[4][4] || ADDKPC loop?,RA STDW RA:BSZ,*SP[4] loop?: CMPLTU LEN,BSZ,A0 ; len < bsz? || SHRU BSZ,3,BSZ [A0] BNOP ret? ||[A0] ZERO BSZ ||[A0] LDW *SP[1],A2 ; pull A[][] [BSZ] LDNDW *INP++,A1:A0 ||[BSZ] SUB LEN,8,LEN ||[BSZ] SUB BSZ,1,BSZ NOP 4 ___ for ($y = 0; $y < 5; $y++) { for ($x = 0; $x < ($y<4 ? 5 : 4); $x++) { $code.=<<___; .if .BIG_ENDIAN SWAP2 A0,A1 || SWAP2 A1,A0 SWAP4 A0,A0 SWAP4 A1,A1 ||[!BSZ]BNOP _KeccakF1600_cheat ||[!BSZ]STDW LEN:INP,*SP[3] || DEAL A0,A0 .else [!BSZ]BNOP _KeccakF1600_cheat ||[!BSZ]STDW LEN:INP,*SP[3] || DEAL A0,A0 .endif [BSZ] LDNDW *INP++,A1:A0 || DEAL A1,A1 [BSZ] SUB LEN,8,LEN ||[BSZ] SUB BSZ,1,BSZ PACK2 A1,A0,A0 || PACKH2 A1,A0,A1 XOR A0,A$A[$y][$x],A$A[$y][$x] XOR A1,B$A[$y][$x],B$A[$y][$x] ___ } } $code.=<<___; .if .BIG_ENDIAN SWAP2 A0,A1 || SWAP2 A1,A0 SWAP4 A0,A0 SWAP4 A1,A1 .endif BNOP _KeccakF1600_cheat || STDW LEN:INP,*SP[3] || DEAL A0,A0 DEAL A1,A1 NOP PACK2 A1,A0,A0 || PACKH2 A1,A0,A1 XOR A0,A$A[4][4],A$A[4][4] XOR A1,B$A[4][4],B$A[4][4] .align 16 ret?: MV LEN,A4 ; return value || ADD 4,A2,B2 STW A$A[0][0],*A2++[2] ; store A[5][5] || STW B$A[0][0],*B2++[2] STW A$A[0][1],*A2++[2] || STW B$A[0][1],*B2++[2] STW A$A[0][2],*A2++[2] || STW B$A[0][2],*B2++[2] STW A$A[0][3],*A2++[2] || STW B$A[0][3],*B2++[2] STW A$A[0][4],*A2++[2] || STW B$A[0][4],*B2++[2] STW A$A[1][0],*A2++[2] || STW B$A[1][0],*B2++[2] STW A$A[1][1],*A2++[2] || STW B$A[1][1],*B2++[2] STW A$A[1][2],*A2++[2] || STW B$A[1][2],*B2++[2] STW A$A[1][3],*A2++[2] || STW B$A[1][3],*B2++[2] STW A$A[1][4],*A2++[2] || STW B$A[1][4],*B2++[2] STW A$A[2][0],*A2++[2] || STW B$A[2][0],*B2++[2] STW A$A[2][1],*A2++[2] || STW B$A[2][1],*B2++[2] STW A$A[2][2],*A2++[2] || STW B$A[2][2],*B2++[2] STW A$A[2][3],*A2++[2] || STW B$A[2][3],*B2++[2] STW A$A[2][4],*A2++[2] || STW B$A[2][4],*B2++[2] LDW *SP[15],RA || LDW *FP[-6],A14 STW A$A[3][0],*A2++[2] || STW B$A[3][0],*B2++[2] STW A$A[3][1],*A2++[2] || STW B$A[3][1],*B2++[2] STW A$A[3][2],*A2++[2] || STW B$A[3][2],*B2++[2] STW A$A[3][3],*A2++[2] || STW B$A[3][3],*B2++[2] STW A$A[3][4],*A2++[2] || STW B$A[3][4],*B2++[2] LDDW *SP[8], B11:B10 || LDDW *FP[-5],A11:A10 LDDW *SP[9], B13:B12 || LDDW *FP[-4],A13:A12 BNOP RA || LDW *++SP(80),FP ; restore frame pointer STW A$A[4][0],*A2++[2] || STW B$A[4][0],*B2++[2] STW A$A[4][1],*A2++[2] || STW B$A[4][1],*B2++[2] STW A$A[4][2],*A2++[2] || STW B$A[4][2],*B2++[2] STW A$A[4][3],*A2++[2] || STW B$A[4][3],*B2++[2] STW A$A[4][4],*A2++[2] || STW B$A[4][4],*B2++[2] .endasmfunc .newblock .global _SHA3_squeeze .asg A12,OUT .asg A13,LEN .asg A14,BSZ .align 32 _SHA3_squeeze: .asmfunc stack_usage(24) STW FP,*SP--(24) ; save frame pointer || MV SP,FP STW RA, *SP[5] || STW A14,*FP[-2] STDW A13:A12,*FP[-2] || MV B4,OUT ; reassign arguments MV A6,LEN || MV B6,BSZ loop?: LDW *SP[5],RA ; reload RA || SHRU BSZ,3,A1 || MV A4,A8 || ADD 4,A4,B8 block?: CMPLTU LEN,8,A0 ; len < 8? [A0] BNOP tail? LDW *A8++[2],A9 || LDW *B8++[2],B9 || SUB LEN,8,LEN ; len -= 8 MV LEN,A0 || SUB A1,1,A1 ; bsz-- || NOP 4 .if .BIG_ENDIAN SWAP4 A9,A9 || SWAP4 B9,B9 SWAP2 A9,A9 || SWAP2 B9,B9 .endif [!A0] BNOP ret? ||[!A0] ZERO A1 PACK2 B9,A9,B7 ||[A1] BNOP block? PACKH2 B9,A9,B9 || SHFL B7,B7 SHFL B9,B9 STNW B7,*OUT++ STNW B9,*OUT++ NOP BNOP _KeccakF1600,4 ADDKPC loop?,RA .align 16 tail?: .if .BIG_ENDIAN SWAP4 A9,A9 || SWAP4 B9,B9 SWAP2 A9,A9 || SWAP2 B9,B9 .endif PACK2 B9,A9,B7 PACKH2 B9,A9,B9 || SHFL B7,B7 SHFL B9,B9 STB B7,*OUT++ || SHRU B7,8,B7 || ADD LEN,7,A0 [A0] STB B7,*OUT++ ||[A0] SHRU B7,8,B7 ||[A0] SUB A0,1,A0 [A0] STB B7,*OUT++ ||[A0] SHRU B7,8,B7 ||[A0] SUB A0,1,A0 [A0] STB B7,*OUT++ ||[A0] SUB A0,1,A0 [A0] STB B9,*OUT++ ||[A0] SHRU B9,8,B9 ||[A0] SUB A0,1,A0 [A0] STB B9,*OUT++ ||[A0] SHRU B9,8,B9 ||[A0] SUB A0,1,A0 [A0] STB B9,*OUT++ ret?: LDDW *FP[-2],A13:A12 BNOP RA || LDW *FP[-2],A14 LDW *++SP(24),FP ; restore frame pointer NOP 4 ; wait till FP is committed .endasmfunc .if __TI_EABI__ .sect ".text:sha_asm.const" .else .sect ".const:sha_asm" .endif .align 256 .uword 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 iotas: .uword 0x00000001, 0x00000000 .uword 0x00000000, 0x00000089 .uword 0x00000000, 0x8000008b .uword 0x00000000, 0x80008080 .uword 0x00000001, 0x0000008b .uword 0x00000001, 0x00008000 .uword 0x00000001, 0x80008088 .uword 0x00000001, 0x80000082 .uword 0x00000000, 0x0000000b .uword 0x00000000, 0x0000000a .uword 0x00000001, 0x00008082 .uword 0x00000000, 0x00008003 .uword 0x00000001, 0x0000808b .uword 0x00000001, 0x8000000b .uword 0x00000001, 0x8000008a .uword 0x00000001, 0x80000081 .uword 0x00000000, 0x80000081 .uword 0x00000000, 0x80000008 .uword 0x00000000, 0x00000083 .uword 0x00000000, 0x80008003 .uword 0x00000001, 0x80008088 .uword 0x00000000, 0x80000088 .uword 0x00000001, 0x00008000 .uword 0x00000000, 0x80008082 .cstring "Keccak-1600 absorb and squeeze for C64x, CRYPTOGAMS by <appro\@openssl.org>" .align 4 ___ $output=pop and open STDOUT,">$output"; print $code; close STDOUT or die "error closing STDOUT: $!";
jens-maus/amissl
openssl/crypto/sha/asm/keccak1600-c64x.pl
Perl
bsd-3-clause
22,743
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/ympzZnp0Uq/asia. Olson data version 2012c # # Do not edit this file directly. # package DateTime::TimeZone::Asia::Tbilisi; { $DateTime::TimeZone::Asia::Tbilisi::VERSION = '1.46'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::Asia::Tbilisi::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, 59295531644, DateTime::TimeZone::NEG_INFINITY, 59295542400, 10756, 0, 'LMT' ], [ 59295531644, 60694520444, 59295542400, 60694531200, 10756, 0, 'TBMT' ], [ 60694520444, 61730542800, 60694531244, 61730553600, 10800, 0, 'TBIT' ], [ 61730542800, 62490600000, 61730557200, 62490614400, 14400, 0, 'TBIT' ], [ 62490600000, 62506407600, 62490618000, 62506425600, 18000, 1, 'TBIST' ], [ 62506407600, 62522136000, 62506422000, 62522150400, 14400, 0, 'TBIT' ], [ 62522136000, 62537943600, 62522154000, 62537961600, 18000, 1, 'TBIST' ], [ 62537943600, 62553672000, 62537958000, 62553686400, 14400, 0, 'TBIT' ], [ 62553672000, 62569479600, 62553690000, 62569497600, 18000, 1, 'TBIST' ], [ 62569479600, 62585294400, 62569494000, 62585308800, 14400, 0, 'TBIT' ], [ 62585294400, 62601026400, 62585312400, 62601044400, 18000, 1, 'TBIST' ], [ 62601026400, 62616751200, 62601040800, 62616765600, 14400, 0, 'TBIT' ], [ 62616751200, 62632476000, 62616769200, 62632494000, 18000, 1, 'TBIST' ], [ 62632476000, 62648200800, 62632490400, 62648215200, 14400, 0, 'TBIT' ], [ 62648200800, 62663925600, 62648218800, 62663943600, 18000, 1, 'TBIST' ], [ 62663925600, 62679650400, 62663940000, 62679664800, 14400, 0, 'TBIT' ], [ 62679650400, 62695375200, 62679668400, 62695393200, 18000, 1, 'TBIST' ], [ 62695375200, 62711100000, 62695389600, 62711114400, 14400, 0, 'TBIT' ], [ 62711100000, 62726824800, 62711118000, 62726842800, 18000, 1, 'TBIST' ], [ 62726824800, 62742549600, 62726839200, 62742564000, 14400, 0, 'TBIT' ], [ 62742549600, 62758274400, 62742567600, 62758292400, 18000, 1, 'TBIST' ], [ 62758274400, 62773999200, 62758288800, 62774013600, 14400, 0, 'TBIT' ], [ 62773999200, 62790328800, 62774017200, 62790346800, 18000, 1, 'TBIST' ], [ 62790328800, 62806053600, 62790343200, 62806068000, 14400, 0, 'TBIT' ], [ 62806053600, 62806824000, 62806068000, 62806838400, 14400, 1, 'TBIST' ], [ 62806824000, 62821782000, 62806838400, 62821796400, 14400, 1, 'GEST' ], [ 62821782000, 62829896400, 62821792800, 62829907200, 10800, 0, 'GET' ], [ 62829896400, 62837499600, 62829907200, 62837510400, 10800, 0, 'GET' ], [ 62837499600, 62853220800, 62837514000, 62853235200, 14400, 1, 'GEST' ], [ 62853220800, 62868949200, 62853231600, 62868960000, 10800, 0, 'GET' ], [ 62868949200, 62884670400, 62868963600, 62884684800, 14400, 1, 'GEST' ], [ 62884670400, 62900398800, 62884681200, 62900409600, 10800, 0, 'GET' ], [ 62900398800, 62916120000, 62900413200, 62916134400, 14400, 1, 'GEST' ], [ 62916120000, 62931844800, 62916134400, 62931859200, 14400, 0, 'GET' ], [ 62931844800, 62947566000, 62931862800, 62947584000, 18000, 1, 'GEST' ], [ 62947566000, 62963899200, 62947580400, 62963913600, 14400, 0, 'GET' ], [ 62963899200, 62982039600, 62963917200, 62982057600, 18000, 1, 'GEST' ], [ 62982039600, 62995345200, 62982057600, 62995363200, 18000, 1, 'GEST' ], [ 62995345200, 63013489200, 62995363200, 63013507200, 18000, 1, 'GEST' ], [ 63013489200, 63026798400, 63013503600, 63026812800, 14400, 0, 'GET' ], [ 63026798400, 63044938800, 63026816400, 63044956800, 18000, 1, 'GEST' ], [ 63044938800, 63058248000, 63044953200, 63058262400, 14400, 0, 'GET' ], [ 63058248000, 63076993200, 63058266000, 63077011200, 18000, 1, 'GEST' ], [ 63076993200, 63089697600, 63077007600, 63089712000, 14400, 0, 'GET' ], [ 63089697600, 63108442800, 63089715600, 63108460800, 18000, 1, 'GEST' ], [ 63108442800, 63121147200, 63108457200, 63121161600, 14400, 0, 'GET' ], [ 63121147200, 63139892400, 63121165200, 63139910400, 18000, 1, 'GEST' ], [ 63139892400, 63153201600, 63139906800, 63153216000, 14400, 0, 'GET' ], [ 63153201600, 63171342000, 63153219600, 63171360000, 18000, 1, 'GEST' ], [ 63171342000, 63184651200, 63171356400, 63184665600, 14400, 0, 'GET' ], [ 63184651200, 63202791600, 63184669200, 63202809600, 18000, 1, 'GEST' ], [ 63202791600, 63216100800, 63202806000, 63216115200, 14400, 0, 'GET' ], [ 63216100800, 63223959600, 63216118800, 63223977600, 18000, 1, 'GEST' ], [ 63223959600, 63234860400, 63223974000, 63234874800, 14400, 1, 'GEST' ], [ 63234860400, 63247561200, 63234871200, 63247572000, 10800, 0, 'GET' ], [ 63247561200, DateTime::TimeZone::INFINITY, 63247575600, DateTime::TimeZone::INFINITY, 14400, 0, 'GET' ], ]; sub olson_version { '2012c' } sub has_dst_changes { 27 } sub _max_year { 2022 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/DateTime/TimeZone/Asia/Tbilisi.pm
Perl
bsd-3-clause
5,429
#! /usr/bin/perl # $Id: ldifsort.pl,v 1.9 2005/04/03 20:20:24 subbarao Exp $ =head1 NAME ldifsort.pl - Sorts an LDIF file by the specified key attribute. The sorted version is written to standard output. =head1 DESCRIPTION Sorts an LDIF file by the specified key attribute. =head1 SYNOPSIS ldifsort.pl B<-k keyattr> [B<-andc>] file.ldif =over 4 =item B<-k> Specifies the key attribute for making sort comparisons. If 'dn' is specified, sorting is done by the full DN string, which can be composed of different attributes for different entries. =item B<-a> Specifies that attributes within a given entry should also be sorted. This has the side effect of removing all comments and line continuations in the LDIF file. =item B<-n> Specifies numeric comparisons on the key attribute. Otherwise string comparisons are done. =item B<-d> Specifies that the key attribute is a DN. Comparisons are done on a DN-normalized version of attribute values. This is the default behavior if 'dn' is passed as the argument to B<-k>. =item B<-c> Specifies case-insensitive comparisons on the key attribute. This is the default behavior if 'dn' is passed as the argument to B<-k>. =back =head1 AUTHOR Kartik Subbarao E<lt>subbarao@computer.orgE<gt> =cut use Net::LDAP::Util qw(canonical_dn); use MIME::Base64; use Getopt::Std; use strict; my %args; getopts("k:andc", \%args); my $keyattr = $args{k}; my $sortattrs = $args{a}; my $ciscmp = $args{c}; my $ldiffile = $ARGV[0]; die "usage: $0 -k keyattr [-n] [-d] [-c] ldiffile\n" unless $keyattr && $ldiffile; $/ = ""; open(LDIFH, $ldiffile) || die "$ldiffile: $!\n"; my $pos = 0; my @valuepos; while (<LDIFH>) { my $value; 1 while s/^($keyattr:.*)?\n /$1/im; # Handle line continuations if (/^$keyattr(::?) (.*)$/im) { $value = $2; $value = decode_base64($value) if $1 eq '::'; } $value = lc($value) if $ciscmp; push @valuepos, [ $value, $pos ]; $pos = tell; } sub cmpattr { $a->[0] cmp $b->[0] } sub cmpattrnum { $a->[0] <=> $b->[0] } my %canonicaldns; sub cmpdn { my $cadn = ($canonicaldns{$a->[0]} ||= lc(canonical_dn($a->[0]))); my $cbdn = ($canonicaldns{$b->[0]} ||= lc(canonical_dn($b->[0]))); # sort by DN hierarchy my @cadns = split(/(^|[^\\])(\\\\)*,/, $cadn); my @cbdns = split(/(^|[^\\])(\\\\)*,/, $cbdn); while (@cadns || @cbdns) { # read from the top of the tree my $cmpa = pop(@cadns); my $cmpb = pop(@cbdns); # if differs return cmp if not, continue with checking if ($cmpa cmp $cmpb) { return $cmpa cmp $cmpb; } } # both entries match return 0; } my $cmpfunc; if ($args{d} || lc($keyattr) eq 'dn') { $cmpfunc = \&cmpdn } elsif ($args{n}) { $cmpfunc = \&cmpattrnum } else { $cmpfunc = \&cmpattr; } my @sorted; @sorted = sort $cmpfunc @valuepos; foreach my $valuepos (@sorted) { seek(LDIFH, $valuepos->[1], 0); my $entry = <LDIFH>; if ($sortattrs) { $entry =~ s/\n //mg; # collapse line continuations my @lines = grep(!/^#/, split(/\n/, $entry)); my $dn = shift(@lines); print "$dn\n", join("\n", sort @lines), "\n\n"; } else { print $entry; print "\n" if $entry !~ /\n\n$/; } }
sustr4/perun-services
slave/process-ldap/lib/ldifsort.pl
Perl
bsd-2-clause
3,118
#!/usr/bin/perl -w # configure script for smbase use strict 'subs'; require sm_config; $SMBASE = "."; get_sm_config_version(); $thisPackage = "smbase"; sub usage { standardUsage(); print(<<"EOF"); package options: -prof enable profiling -devel add options useful while developing smbase -debugheap turn on heap usage debugging -traceheap print messages on each malloc and free EOF # this option is obscure, so I won't print it in the usage string # -icc turn on options for Intel's compiler } # defaults (also see sm_config.pm) $DEBUG_HEAP = 0; $TRACE_HEAP = 0; # global variables holding information about the current command-line # option being processed $option = ""; $value = ""; # process command-line arguments foreach $optionAndValue (@ARGV) { # ignore leading '-' characters, and split at first '=' (if any) ($option, $value) = ($optionAndValue =~ m/^-*([^-][^=]*)=?(.*)$/); # option = value my $arg = $option; if (handleStandardOption()) { # handled by sm_config.pm } elsif ($arg eq "prof") { push @CCFLAGS, "-pg"; } elsif ($arg eq "devel") { push @CCFLAGS, "-Werror"; } elsif ($arg eq "debugheap") { $DEBUG_HEAP = 1; } elsif ($arg eq "traceheap") { $TRACE_HEAP = 1; } # 9/19/04: I spent some time getting smbase to build under # the Intel C++ 8.1 compiler; these are the options I used. elsif ($arg eq "icc") { # compiler executables $CC = "icc"; $CXX = "icpc"; # diagnostic suppression: # 444: Wants virtual destructors # 1418: external definition with no prior declaration # 810: Conversion might lose sig.digs (can't suppress with cast!) # 271: trailing comma is nonstandard # 981: operands are evaluated in unspecified order # 279: controlling expression is constant # 383: value copied to temporary, reference to temporary used # 327: NULL reference is not allowed # 1419: external declaration in primary source file push @CCFLAGS, "-wd444,1418,810,271,981,279,383,327,1419"; } else { print STDERR ("unknown option: $arg\n"); exit(2); } } finishedOptionProcessing(); # -------------- external tools tests --------------------- test_CXX_compiler(); # ------------------ config.summary ----------------- $summary = getStandardConfigSummary(); if ($DEBUG_HEAP) { $summary .= "echo \" DEBUG_HEAP: $DEBUG_HEAP\"\n"; } if ($TRACE_HEAP) { $summary .= "echo \" TRACE_HEAP: $TRACE_HEAP\"\n"; } writeConfigSummary($summary); # ------------------- config.status ------------------ writeConfigStatus("DEBUG_HEAP" => "$DEBUG_HEAP", "TRACE_HEAP" => "$TRACE_HEAP"); # ----------------- final actions ----------------- # run the output file generator run("./config.status"); print("\nYou can now run make, usually called 'make' or 'gmake'.\n"); exit(0); # silence warnings pretendUsed($thisPackage); pretendUsed($CC); pretendUsed($CXX); # the code below is never executed as part of smbase/configure.pl; # it is here so it can be easily found to copy into the client # configuration scripts # -------------- BEGIN common block --------------- # do an initial argument scan to find if smbase is somewhere else for (my $i=0; $i < @ARGV; $i++) { my ($d) = ($ARGV[$i] =~ m/-*smbase=(.*)/); if (defined($d)) { $SMBASE = $d; } } # try to load the sm_config module eval { push @INC, ($SMBASE); require sm_config; }; if ($@) { die("$@" . # ends with newline, usually "\n" . "I looked for smbase in \"$SMBASE\".\n" . "\n" . "You can explicitly specify the location of smbase with the -smbase=<dir>\n" . "command-line argument.\n"); } # check version number $smcv = get_sm_config_version(); if ($smcv < $req_smcv) { die("This package requires version $req_smcv of sm_config, but found\n" . "only version $smcv.\n"); } # -------------- END common block --------------- # -------------- BEGIN common block 2 ------------- # global variables holding information about the current command-line # option being processed $option = ""; $value = ""; # process command-line arguments foreach $optionAndValue (@ARGV) { # ignore leading '-' characters, and split at first '=' (if any) ($option, $value) = ($optionAndValue =~ m/^-*([^-][^=]*)=?(.*)$/); # option = value my $arg = $option; if (handleStandardOption()) { # handled by sm_config.pm } # -------------- END common block 2 ------------- } # EOF
BackupTheBerlios/codemorpher-svn
trunk/elsa/smbase/configure.pl
Perl
bsd-3-clause
4,617
=head1 NAME Image::ExifTool::MIEUnits - MIE units documentation =head1 DESCRIPTION The MIE format allows units of measurement to be specified in brackets at the end of a MIE tag name (ie. "Volume(m3)"). This document describes the standard MIE units abbreviations. =head1 SYNTAX The units string may contain any ASCII characters in the range 0x21 ('!') to 0x7d ('}'), excepting the bracket characters (0x28 and 0x29). An empty string is allowed, and indicates a dimensionless value. L<Standard units|/STANDARD UNITS> should be used where possible. In the standard units, an underline ('_') is used to indicate a subscript, and multiple words may be separated with a hyphen ('-'). Exponents should be positive, and require no separator (ie. "m2" for square meters). L<Prefixes|/PREFIXES> may be added to the standard units (ie. "cm") except when the resulting name conflicts with another standard unit. Multiplication is indicated by '.', and division by '/'. Reciprocal units (ie. the multiplicative inverse) are obtained through division rather than the use of negative exponents (ie. "/in", not "in-1"). In MIE units, multiplication has precedence over division, so everything to the right of a '/' is in the denominator. (See L</EXAMPLES> for a few examples.) Below is a table summarizing the special characters used in MIE units strings. . multiplication / division (used for negative exponents) - word separator _ subscript {} annotation [] used to avoid name conflicts if necessary 0-9 exponentiation =head1 STANDARD UNITS dimensionless [G] Newtonian constant of gravitation (unclassified) [g] standard acceleration of free fall (acceleration) [h] Planck constant (action) [k] Boltzmann constant (unclassified) {cfu} colony forming units (number) {rbc} red blood cell count (number) {tbl} tablets (number) {tot} particles total count (number) % percent (fraction) 10^N the number ten for arbitrary powers (number) A Ampere (electric current) a year (time) a_g mean Gregorian year (time) a_j mean Julian year (time) a_t tropical year (time) acr acre, U.S. (area) acr_br acre, British (area) Ao Angstrom (length) APL-U APL unit (biologic activity of anticardiolipin IgA) ar are (area) arb-U arbitrary unit (arbitrary) arcmin minute of arc (plane angle) arcsec second of arc (plane angle) atm standard atmosphere (pressure) att technical atmosphere (pressure) AU astronomic unit (length) b barn (action area) B bel (level) B-kW bel kilowatt (power level) B-mV bel millivolt (electric potential level) B-SPL bel sound pressure (pressure level) B-uV bel microvolt (electric potential level) B-V bel volt (electric potential level) B-W bel watt (power level) bar bar (pressure) bbl barrel (fluid volume) Bd baud (signal transmission rate) bdsk-U Bodansky unit (biologic activity of phosphatase) beth-U Bethesda unit (biologic activity of factor VIII inhibitor) bf board foot (volume) Bi Biot (electric current) bit bit (amount of information) Bq Becquerel (radioactivity) Btu British thermal unit (energy) Btu_39 British thermal unit at 39 degF (energy) Btu_59 British thermal unit at 59 degF (energy) Btu_60 British thermal unit at 60 degF (energy) Btu_IT international table British thermal unit (energy) Btu_m mean British thermal unit (energy) Btu_th thermochemical British thermal unit (energy) bu bushel, U.S. (dry volume) bu_br bushel, British (volume) By byte (amount of information) C Coulomb (electric charge) c velocity of light (velocity) cal calorie (energy) Cal nutrition label Calories (energy) cal_15 calorie at 15 degC (energy) cal_20 calorie at 20 degC (energy) cal_IT international table calorie (energy) cal_m mean calorie (energy) cal_th thermochemical calorie (energy) car_Au carat of gold alloys (mass fraction) car_m metric carat (mass) cd candela (luminous intensity) Cel degree Celsius (temperature) Ch Charriere (gauge of catheters) ch Gunter's chain, U.S. (length) ch_br Gunter's chain, British (length) Ci Curie (radioactivity) cicero cicero (length) circ circle (plane angle) cml circular mil, international (area) cr cord, international (volume) crd_us cord, U.S. (fluid volume) cup_us cup (volume) d day (time) deg degree (plane angle) deg{mag} degree from magnetic north (plane angle) degF degree Fahrenheit (temperature) didot didot (length) diop diopter (refraction of a lens) dpt dry pint, U.S. (dry volume) dqt dry quart, U.S. (dry volume) dr dram (mass) dr_ap dram, apothecary (mass) drp drop (volume) dye-U Dye unit (biologic activity of amylase) dyn dyne (force) e elementary charge (electric charge) eps_0 permittivity of vacuum (electric permittivity) eq equivalents (amount of substance) erg erg (energy) eV electronvolt (energy) F Farad (electric capacitance) fdr fluid dram, U.S. (fluid volume) fdr_br fluid dram, British (volume) foz fluid ounce, U.S. (fluid volume) foz_br fluid ounce, British (volume) ft foot, international (length) ft_br foot, British (length) ft_us foot, U.S. (length) fth fathom, international (length) fth_br fathom, British (length) fth_us fathom, U.S. (length) fur furlong, U.S. (length) G Gauss (magnetic flux density) g gram (mass) g.m/{H-B} gram meter per heartbeat (prop. to ventricular stroke work) g% gram percent (mass fraction) Gal Gal (acceleration) gal gallon, U.S. (fluid volume) gal_br gallon, British (volume) gal_wi historical winchester gallon (dry volume) Gb Gilbert (magnetic tension) gf gram-force (force) gil gill, U.S. (fluid volume) gil_br gill, British (volume) gon gon (plane angle) GPL-U GPL unit (biologic activity of anticardiolipin IgG) gr grain (mass) Gy Gray (energy dose) H Henry (inductance) h hour (time) hd hand, international (height of horses) hnsf-U Hounsfield unit (x-ray attenuation) HP horsepower (power) hp_C homeopathic potency of centesimal series (homeopathic potency) hp_X homeopathic potency of decimal series (homeopathic potency) HPF high power field (view area in microscope) Hz Herz (frequency) in inch, international (length) in_br inch, British (length) in_us inch, U.S. (length) in-H2O inch of water column (pressure) in-Hg inch of mercury column (pressure) iU international unit (arbitrary) J Joule (energy) K Kelvin (temperature) ka-U King-Armstrong unit (biologic activity of phosphatase) kat katal (catalytic activity) kg{wet-tis} kilogram of wet tissue (mass) kn knot, international (velocity) kn_br knot, British (velocity) knk-U Kunkel unit (arbitrary biologic activity) Ky Kayser (lineic number) l liter (volume) L liter (volume) lb pound (mass) lb_ap pound, apothecary (mass) lb_tr pound, troy (mass) lbf pound force (force) lcwt long hunderdweight (mass) ligne ligne (length) lk link for Gunter's chain, U.S. (length) lk_br link for Gunter's chain, British (length) lm lumen (luminous flux) Lmb Lambert (brightness) lne line (length) LPF low power field (view area in microscope) lton long ton (mass) lx lux (illuminance) ly light-year (length) m meter (length) m_e electron mass (mass) m_p proton mass (mass) m-H2O meter of water column (pressure) m-Hg meter of mercury column (pressure) mclg-U Mac Lagan unit (arbitrary biologic activity) mesh mesh, international (lineic number) MET metabolic equivalent (metabolic cost of physical activity) mg{creat} milligram of creatinine (mass) mho mho (electric conductance) mi mile, international (statute mile) (length) mi_br mile, British (length) mi_us mile, U.S. (length) mil mil, international (length) mil_us mil, U.S. (length) min minute (time) min_br minim, British (volume) min_us minim, U.S. (fluid volume) mo month (time) mo_g mean Gregorian month (time) mo_j mean Julian month (time) mo_s synodal month (time) mol mole (amount of substance) MPL-U MPL unit (biologic activity of anticardiolipin IgM) mu_0 permeability of vacuum (magnetic permeability) Mx Maxwell (flux of magnetic induction) N Newton (force) nmi nautical mile, international (length) nmi_br nautical mile, British (length) Np neper (level) Oe Oersted (magnetic field intensity) Ohm Ohm (electric resistance) osm osmole of dissolved particles (amount of substance) oz ounce (mass) oz_ap ounce, apothecary (mass) oz_tr ounce, troy (mass) P Poise (dynamic viscosity) Pa Pascal (pressure) pc parsec (length) pc_br pace (length) pca pica (length) pca_pr Printer's pica (length) pH pH (acidity) ph phot (illuminance) pi the number pi (number) pied pied (length) pk peck, U.S. (dry volume) pk_br peck, British (volume) pnt point (length) pnt_pr Printer's point (length) pouce pouce (length) ppb parts per billion (fraction) ppm parts per million (fraction) ppth parts per thousand (fraction) pptr parts per trillion (fraction) PRU peripheral vascular resistance unit (fluid resistance) psi pound per square inch (pressure) pt pint, U.S. (fluid volume) pt_br pint, British (volume) pwt_tr pennyweight (mass) qt quart, U.S. (fluid volume) qt_br quart, British (volume) R Roentgen (ion dose) rad radian (plane angle) RAD radiation absorbed dose (energy dose) rch Ramden's chain, U.S. (length) rd rod, U.S. (length) rd_br rod, British (length) REM radiation equivalent man (dose equivalent) rlk_us link for Ramden's chain (length) s second (time) S Siemens (electric conductance) sb stilb (lum. intensity density) sc_ap scruple, apothecary (mass) sct section (area) scwt short hundredweight (mass) smgy-U Somogyi unit (biologic activity of amylase) sph spere (solid angle) sr streadian (solid angle) st stere (volume) St Stokes (kinematic viscosity) ston short ton (mass) stone stone (mass) Sv Sievert (dose equivalent) Sv-U Svedberg unit (sedimentation coefficient) T Tesla (magnetic flux density) t tonne (mass) tb-U tuberculin unit (biologic activity of tuberculin) tbs tablespoon, U.S. (volume) todd-U Todd unit (biologic activity antistreptolysin O) tsp teaspoon, U.S. (volume) twp township (area) u unified atomic mass unit (mass) U Unit (catalytic activity) USP-U U.S. Pharmacopeia unit (arbitrary) V Volt (electric potential) W Watt (power) Wb Weber (magnetic flux) wk week (time) yd yard, international (length) yd_br yard, British (length) yd_us yard, U.S. (length) =head1 PREFIXES Standard SI prefixes: y yocto (10^-24) z zepto (10^-21) a atto (10^-18) f femto (10^-15) p pico (10^-12) n nano (10^-9) u micro (10^-6) m milli (10^-3) c centi (10^-2) d deci (10^-1) da deka (10) h hecto (10^2) k kilo (10^3) G giga (10^9) M mega (10^6) T tera (10^12) P peta (10^15) E exa (10^18) Z zetta (10^21) Y yotta (10^24) Binary power prefixes: Ki kibi (2^10) Mi mebi (2^20) Gi gibi (2^30) Ti tebi (2^40) =head1 EXAMPLES A few examples of combined units strings: /cm3 per cubic centimeter in2 square inches kg.m/s2 Newtons (N) m3/kg.s2 units of [G] 10^100 googols =head1 HISTORY 2006-12-14 - PH Created =head1 AUTHOR Copyright 2003-2013, Phil Harvey (phil at owl.phy.queensu.ca) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 REFERENCES =over 4 =item L<http://aurora.regenstrief.org/UCUM/> =back =head1 SEE ALSO L<Image::ExifTool::MIE(3pm)|Image::ExifTool::MIE>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
wilg/mini_exiftool_vendored
vendor/Image-ExifTool-9.27/lib/Image/ExifTool/MIEUnits.pod
Perl
mit
14,005
package ExtUtils::Mkbootstrap; # There's just too much Dynaloader incest here to turn on strict vars. use strict 'refs'; our $VERSION = '6.63_02'; require Exporter; our @ISA = ('Exporter'); our @EXPORT = ('&Mkbootstrap'); use Config; our $Verbose = 0; sub Mkbootstrap { my($baseext, @bsloadlibs)=@_; @bsloadlibs = grep($_, @bsloadlibs); # strip empty libs print STDOUT " bsloadlibs=@bsloadlibs\n" if $Verbose; # We need DynaLoader here because we and/or the *_BS file may # call dl_findfile(). We don't say `use' here because when # first building perl extensions the DynaLoader will not have # been built when MakeMaker gets first used. require DynaLoader; rename "$baseext.bs", "$baseext.bso" if -s "$baseext.bs"; if (-f "${baseext}_BS"){ $_ = "${baseext}_BS"; package DynaLoader; # execute code as if in DynaLoader local($osname, $dlsrc) = (); # avoid warnings ($osname, $dlsrc) = @Config::Config{qw(osname dlsrc)}; $bscode = ""; unshift @INC, "."; require $_; shift @INC; } if ($Config{'dlsrc'} =~ /^dl_dld/){ package DynaLoader; push(@dl_resolve_using, dl_findfile('-lc')); } my(@all) = (@bsloadlibs, @DynaLoader::dl_resolve_using); my($method) = ''; if (@all){ open my $bs, ">", "$baseext.bs" or die "Unable to open $baseext.bs: $!"; print STDOUT "Writing $baseext.bs\n"; print STDOUT " containing: @all" if $Verbose; print $bs "# $baseext DynaLoader bootstrap file for $^O architecture.\n"; print $bs "# Do not edit this file, changes will be lost.\n"; print $bs "# This file was automatically generated by the\n"; print $bs "# Mkbootstrap routine in ExtUtils::Mkbootstrap (v$VERSION).\n"; print $bs "\@DynaLoader::dl_resolve_using = "; # If @all contains names in the form -lxxx or -Lxxx then it's asking for # runtime library location so we automatically add a call to dl_findfile() if (" @all" =~ m/ -[lLR]/){ print $bs " dl_findfile(qw(\n @all\n ));\n"; }else{ print $bs " qw(@all);\n"; } # write extra code if *_BS says so print $bs $DynaLoader::bscode if $DynaLoader::bscode; print $bs "\n1;\n"; close $bs; } } 1; __END__ =head1 NAME ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader =head1 SYNOPSIS C<Mkbootstrap> =head1 DESCRIPTION Mkbootstrap typically gets called from an extension Makefile. There is no C<*.bs> file supplied with the extension. Instead, there may be a C<*_BS> file which has code for the special cases, like posix for berkeley db on the NeXT. This file will get parsed, and produce a maybe empty C<@DynaLoader::dl_resolve_using> array for the current architecture. That will be extended by $BSLOADLIBS, which was computed by ExtUtils::Liblist::ext(). If this array still is empty, we do nothing, else we write a .bs file with an C<@DynaLoader::dl_resolve_using> array. The C<*_BS> file can put some code into the generated C<*.bs> file by placing it in C<$bscode>. This is a handy 'escape' mechanism that may prove useful in complex situations. If @DynaLoader::dl_resolve_using contains C<-L*> or C<-l*> entries then Mkbootstrap will automatically add a dl_findfile() call to the generated C<*.bs> file. =cut
leighpauls/k2cro4
third_party/perl/perl/lib/ExtUtils/Mkbootstrap.pm
Perl
bsd-3-clause
3,205
package Net::DNS::RR::RT; # # $Id: RT.pm 632 2007-03-12 13:24:21Z olaf $ # use strict; BEGIN { eval { require bytes; } } use vars qw(@ISA $VERSION); @ISA = qw(Net::DNS::RR); $VERSION = (qw$LastChangedRevision: 632 $)[1]; # Highest preference sorted first. __PACKAGE__->set_rrsort_func("preference", sub { my ($a,$b)=($Net::DNS::a,$Net::DNS::b); $a->{'preference'} <=> $b->{'preference'} } ); __PACKAGE__->set_rrsort_func("default_sort", __PACKAGE__->get_rrsort_func("preference") ); sub new { my ($class, $self, $data, $offset) = @_; if ($self->{"rdlength"} > 0) { ($self->{"preference"}) = unpack("\@$offset n", $$data); $offset += Net::DNS::INT16SZ(); ($self->{"intermediate"}) = Net::DNS::Packet::dn_expand($data, $offset); } return bless $self, $class; } sub new_from_string { my ($class, $self, $string) = @_; if ($string && ($string =~ /^(\d+)\s+(\S+)$/)) { $self->{"preference"} = $1; $self->{"intermediate"} = $2; $self->{"intermediate"} =~ s/\.+$//; } return bless $self, $class; } sub rdatastr { my $self = shift; return $self->{"preference"} ? "$self->{preference} $self->{intermediate}." : ''; } sub rr_rdata { my ($self, $packet, $offset) = @_; my $rdata = ""; if (exists $self->{"preference"}) { $rdata .= pack("n", $self->{"preference"}); $rdata .= $packet->dn_comp($self->{"intermediate"}, $offset + length $rdata); } return $rdata; } sub _canonicalRdata { my ($self, $packet, $offset) = @_; my $rdata = ""; if (exists $self->{"preference"}) { $rdata .= pack("n", $self->{"preference"}); $rdata .= $self->_name2wire(lc($self->{"intermediate"})); } return $rdata; } 1; __END__ =head1 NAME Net::DNS::RR::RT - DNS RT resource record =head1 SYNOPSIS C<use Net::DNS::RR>; =head1 DESCRIPTION Class for DNS Route Through (RT) resource records. =head1 METHODS =head2 preference print "preference = ", $rr->preference, "\n"; Returns the preference for this route. =head2 intermediate print "intermediate = ", $rr->intermediate, "\n"; Returns the domain name of the intermediate host. =head1 COPYRIGHT Copyright (c) 1997-2002 Michael Fuhr. Portions Copyright (c) 2002-2004 Chris Reinhardt. Portions Copyright (c) 2005 Olaf Kolkman NLnet Labs. All rights reserved. This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L<perl(1)>, L<Net::DNS>, L<Net::DNS::Resolver>, L<Net::DNS::Packet>, L<Net::DNS::Header>, L<Net::DNS::Question>, L<Net::DNS::RR>, RFC 1183 Section 3.3 =cut
leighpauls/k2cro4
third_party/cygwin/lib/perl5/vendor_perl/5.10/i686-cygwin/Net/DNS/RR/RT.pm
Perl
bsd-3-clause
2,622
package DDG::Goodie::Lowercase; # ABSTRACT: Convert a string into lowercase. use strict; use DDG::Goodie; zci answer_type => "lowercase"; zci is_cached => 1; triggers start => 'lowercase', 'lower case', 'lc', 'strtolower', 'tolower'; handle remainder => sub { my $input = shift; return unless $input; my $lower = lc $input; return if ($lower eq $input); return $lower, structured_answer => { data => { title => $lower, subtitle => "Lowercase: $input" }, templates => { group => 'text', } }; }; 1;
shubhamrajput/zeroclickinfo-goodies
lib/DDG/Goodie/Lowercase.pm
Perl
apache-2.0
600
package Fixtures::Integration::Cdn; # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Do not edit! Generated code. # See https://github.com/Comcast/traffic_control/wiki/The%20Kabletown%20example use Moose; extends 'DBIx::Class::EasyFixture'; use namespace::autoclean; my %definition_for = ( 'cd1' => { new => 'Cdn', using => { id => 1, name => 'CDN1', dnssec_enabled => '0', domain_name => 'cdn1.kabletown.net', last_updated => '2015-12-10 15:43:45', }, }, 'cdn2' => { new => 'Cdn', using => { id => 2, name => 'CDN2', dnssec_enabled => '0', domain_name => 'cdn2.kabletown.net', last_updated => '2015-12-10 15:43:45', }, }, ); sub name { return "Cdn"; } sub get_definition { my ( $self, $name ) = @_; return $definition_for{$name}; } sub all_fixture_names { # sort by db name to guarantee insertion order return (sort { $definition_for{$a}{using}{name} cmp $definition_for{$b}{using}{name} } keys %definition_for); } __PACKAGE__->meta->make_immutable; 1;
mdb/incubator-trafficcontrol
traffic_ops/app/lib/Fixtures/Integration/Cdn.pm
Perl
apache-2.0
1,758
print ".text\n\t.type _start,@", "function\n_start:\n\n"; @ldhint = ( "", ".nt1", ".nta" ); @ldspec = ( "", ".s", ".a", ".sa", ".c.clr", ".c.nc" ); @sthint = ( "", ".nta" ); $i = 0; # Integer Load foreach $s ( "1", "2", "4", "8" ) { foreach $e (@ldspec, ".bias", ".acq", ".c.clr.acq") { foreach $l (@ldhint) { print "\tld${s}${e}${l} r4 = [r5]\n"; print "\tld${s}${e}${l} r4 = [r5], r6\n"; print "\tld${s}${e}${l} r4 = [r5], ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; } } # Integer Fill for $l (@ldhint) { print "\tld8.fill${l} r4 = [r5]\n"; print "\tld8.fill${l} r4 = [r5], r6\n"; print "\tld8.fill${l} r4 = [r5], ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; # Integer Store foreach $s ("1", "2", "4", "8", "1.rel", "2.rel", "4.rel", "8.rel", "8.spill") { for $l (@sthint) { print "\tst${s}${l} [r4] = r5\n"; print "\tst${s}${l} [r4] = r5, ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; } # Floating Point Load foreach $s ( "fs", "fd", "f8", "fe" ) { foreach $e (@ldspec) { foreach $l (@ldhint) { print "\tld${s}${e}${l} f4 = [r5]\n"; print "\tld${s}${e}${l} f4 = [r5], r6\n"; print "\tld${s}${e}${l} f4 = [r5], ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; } } # Floating Point Fill for $l (@ldhint) { print "\tldf.fill${l} f4 = [r5]\n"; print "\tldf.fill${l} f4 = [r5], r6\n"; print "\tldf.fill${l} f4 = [r5], ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; # Floating Point Store foreach $s ( "fs", "fd", "f8", "fe", "f.spill" ) { for $l (@sthint) { print "\tst${s}${l} [r4] = f5\n"; print "\tst${s}${l} [r4] = f5, ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; } # Floating Point Load Pair foreach $s ( "fps", "fpd", "fp8" ) { foreach $e (@ldspec) { foreach $l (@ldhint) { print "\tld${s}${e}${l} f4, f5 = [r5]\n"; print "\tld${s}${e}${l} f4, f5 = [r5], ", ($s eq "fps" ? 8 : 16), "\n"; } print "\n"; } } # Line Prefetch @lfhint = ( "", ".nt1", ".nt2", ".nta" ); foreach $e ( "", ".excl" ) { foreach $f ( "", ".fault" ) { foreach $h (@lfhint) { print "\tlfetch${f}${e}${h} [r4]\n"; print "\tlfetch${f}${e}${h} [r4], r5\n"; print "\tlfetch${f}${e}${h} [r4], ", $i - 256, "\n"; $i = ($i + 13) % 512; } print "\n"; } } # Compare and Exchange foreach $s ( "1", "2", "4", "8" ) { foreach $e ( ".acq", ".rel" ) { foreach $h (@ldhint) { print "\tcmpxchg${s}${e}${h} r4 = [r5], r6, ar.ccv\n"; } print "\n"; } } # Exchange foreach $s ( "1", "2", "4", "8" ) { foreach $h (@ldhint) { print "\txchg${s}${h} r4 = [r5], r6\n"; } print "\n"; } # Fetch and Add $i = 0; @inc3 = ( -16, -8, -4, -1, 1, 4, 8, 16 ); foreach $s ( "4.acq", "8.acq", "4.rel", "8.rel" ) { foreach $h (@ldhint) { print "\tfetchadd${s}${h} r4 = [r5], ", $inc3[$i], "\n"; $i = ($i + 1) % 8; } print "\n"; } # Get/Set FR foreach $e ( ".sig", ".exp", ".s", ".d" ) { print "\tsetf${e} f4 = r5\n"; } print "\n"; foreach $e ( ".sig", ".exp", ".s", ".d" ) { print "\tgetf${e} r4 = f5\n"; } print "\n"; # Speculation and Advanced Load Checkso print <<END chk.s.m r4, _start chk.s f4, _start chk.a.nc r4, _start chk.a.clr r4, _start chk.a.nc f4, _start chk.a.clr f4, _start invala fwb mf mf.a srlz.d srlz.i sync.i nop.m 0 nop.i 0 { .mii; alloc r4 = ar.pfs, 2, 10, 16, 16 } { .mii; flushrs } { .mii; loadrs } invala.e r4 invala.e f4 fc r4 ptc.e r4 break.m 0 break.m 0x1ffff nop.m 0 break.m 0x1ffff probe.r r4 = r5, r6 probe.w r4 = r5, r6 probe.r r4 = r5, 0 probe.w r4 = r5, 1 probe.r.fault r3, 2 probe.w.fault r3, 3 probe.rw.fault r3, 0 itc.d r8 itc.i r9 sum 0x1234 rum 0x5aaaaa ssm 0xffffff rsm 0x400000 ptc.l r4, r5 ptc.g r4, r5 ptc.ga r4, r5 ptr.d r4, r5 ptr.i r4, r5 thash r4 = r5 ttag r4 = r5 tpa r4 = r5 tak r4 = r5 END ;
shaotuanchen/sunflower_exp
tools/source/binutils-2.16.1/gas/testsuite/gas/ia64/opc-m.pl
Perl
bsd-3-clause
3,976
#!/usr/bin/perl use strict; use utf8; my ($path, $ext, $output) = @ARGV; opendir(SUBDIR, "$path") or die $!; my $num_files = 0; open(LOG, ">>irl-log.txt"); my @newcontent = (); while (my $txt = readdir(SUBDIR)) { if ($txt =~ /\.$ext$/i) { open(INN, "$path$txt"); # binmode INN, ":utf8"; print LOG "$txt\n"; my @content = <INN>; close(INN); if ($#content <= 0) { print "Empty file? $path$txt\n"; next; } $num_files++; my $written = 0; my $lead = ''; my @cachen = (); foreach my $temp (@content) { chomp($temp); $temp =~ s/\x0A//g; $temp =~ s/\x0D//g; $temp =~ s/> <X> <#> /> <#> /; $temp =~ s/ <#> /\n<#> /g; my @temparr = split/\n/, $temp; foreach my $temp2 (@temparr) { push(@cachen, $temp2) } } foreach my $line (@cachen) #(@content) { if (defined($line) && $line ne '') { my $country = 'ICE-IRL:'; if ($path =~ /written/ || $path =~ /spoken/) { if ($line =~ /^<W([A-Z0-9\$-]+)>$/ || $line =~ /^<S([A-Z0-9\$-]+)>$/) { $lead = ''; $line =~ s/^<//; $line =~ s/>$//; $line =~ s/\$/:/; $lead = "\n" . $country . $line . "\t"; } elsif ($line =~ /^<W([A-Z0-9\$-]+)> / || $line =~ /^<S([A-Z0-9\$-]+)> /) { $lead = ''; my $letter = ''; if ($line =~ /^<W/) { $letter = 'W'; } else { $letter = 'S'; } $line =~ s/^<W([A-Z0-9\$-]+)> (.*)/<W$1\t$2/; $line =~ s/^<S([A-Z0-9\$-]+)> (.*)/<S$1\t$2/; $lead = "\n" . $country . $letter . $1 . "\t"; $line =~ s/^<//; $line =~ s/\$/:/; $lead =~ s/\$/:/; my $sunit = "\n" . $country . $line; push(@newcontent, $sunit); } elsif ($line =~ /^<#> /) { $line =~ s/^<#> //; my $sunit = $lead . $line; push(@newcontent, $sunit); } elsif ($line =~ /^<S([^ ]+) ([^>]+?)>$/ || $line =~ /^<W([^ ]+) ([^>]+?)>$/ || $line eq '<I>' || $line eq '</I>' || $line eq ' <p> ') { # print LOG "1: $line\n"; } elsif ($line =~ / <#> /) { $line =~ s/^<p> //; $line =~ s/^<h> //; $line =~ s/^<quote> //; $line =~ s/^<ul> //; $line =~ s/^<bold> //; $line =~ s/^<it> //; $line =~ s/^<#> //; $line =~ s/^<quote> //; $line =~ s/^<ul> //; $line =~ s/^<bold> //; $line =~ s/^<it> //; $line =~ s/^<#> //; $line =~ s/^<p><#> //; $line =~ s/^><ul> <bold> <#> //; # $line =~ s/<#>/#.#/g; # push(@newcontent, $lead); # my $sunit = $lead . $line; # push(@newcontent, $sunit); print LOG "2: $line\n"; } else { $line = ' ' . $line . ' '; push(@newcontent, $line); # print LOG "3: $line\n"; } } if ($path =~ /unknown/) { if ($line =~ /^<S([A-Z0-9\$-]+)>/) { $lead = ''; $line =~ s/^<([^>]+)> <unclear> (.+) <\/unclear>$/$1\t/; $line =~ s/> <X> <#> /> <#> /; $line =~ s/> <(\{|\[)> /> <#> /; $line =~ s/> <([A-Z]{1,1})> (\w)/> <#> $1/; $line =~ s/^<([^>]+)> <\&> (.+) <\/\&> <#> /$1\t/; $line =~ s/^<([^>]+)> <X> <\&> (.+) <\/\&> <#> /$1\t/; $line =~ s/^<([^>]+)> <\&> (.+) <\/\&>/$1\t#,,#/; $line =~ s/^<([^>]+)> <\&(.+)<\/\&([^>]+?)> (.+)/$1\t$3/; $line =~ s/^<([^>]+)> (\w)/$1\t$2/; $line =~ s/> <X> <#> /\t/; $line =~ s/^<([^>]+)> <#> /$1\t/; $line =~ s/\$/:/; # $line =~ s/<#>/#.#/g; $line =~ s/^<//; $line = "\n" . $country . $line; #print "$line\n"; push(@newcontent, $line); } elsif ($line =~ /^<\&> (.+) <\/\&>$/) { } elsif ($line =~ /^<#> /) { $line =~ s/^<#> / #.# /g; push(@newcontent, $line); } else { } } } } } } close(SUBDIR); print "Number of files read: $num_files\n"; open(OUT, ">$output"); binmode OUT, ":utf8"; foreach my $sentence (@newcontent) { if ($sentence =~ /\n/ && $sentence !~ /\t/) { print LOG "1: $sentence\n"; } print OUT "$sentence"; } close(OUT); close(LOG); print "Check log file, irl-log.txt\n"; exit;
jarleEbe/elasticsearch-on-corpora
iceuntagged/Extracted/irl_simple_extract.pl
Perl
mit
4,121
########################################################################### # # This file is auto-generated by the Perl DateTime Suite time locale # generator (0.04). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate_from_cldr. # # This file as generated from the CLDR XML locale data. See the # LICENSE.cldr file included in this distribution for license details. # # This file was generated from the source file tn.xml. # The source file version number was 1.20, generated on # 2007/07/14 23:02:17. # # Do not edit this file directly. # ########################################################################### package DateTime::Locale::tn; use strict; BEGIN { if ( $] >= 5.006 ) { require utf8; utf8->import; } } use DateTime::Locale::root; @DateTime::Locale::tn::ISA = qw(DateTime::Locale::root); my @day_names = ( "Mosopulogo", "Labobedi", "Laboraro", "Labone", "Labotlhano", "Matlhatso", "Tshipi", ); my @day_abbreviations = ( "Mos", "Bed", "Rar", "Ne", "Tla", "Mat", "Tsh", ); my @day_narrows = ( "2", "3", "4", "5", "6", "7", "1", ); my @month_names = ( "Ferikgong", "Tlhakole", "Mopitlo", "Moranang", "Motsheganang", "Seetebosigo", "Phukwi", "Phatwe", "Lwetse", "Diphalane", "Ngwanatsele", "Sedimonthole", ); my @month_abbreviations = ( "Fer", "Tlh", "Mop", "Mor", "Mot", "See", "Phu", "Pha", "Lwe", "Dip", "Ngw", "Sed", ); my @month_narrows = ( "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", ); my @quarter_names = ( "Q1", "Q2", "Q3", "Q4", ); my @quarter_abbreviations = ( "Q1", "Q2", "Q3", "Q4", ); my @am_pms = ( "AM", "PM", ); my @era_names = ( "BC", "AD", ); my @era_abbreviations = ( "BC", "AD", ); my $date_before_time = "1"; my $date_parts_order = "ymd"; sub day_names { \@day_names } sub day_abbreviations { \@day_abbreviations } sub day_narrows { \@day_narrows } sub month_names { \@month_names } sub month_abbreviations { \@month_abbreviations } sub month_narrows { \@month_narrows } sub quarter_names { \@quarter_names } sub quarter_abbreviations { \@quarter_abbreviations } sub am_pms { \@am_pms } sub era_names { \@era_names } sub era_abbreviations { \@era_abbreviations } sub full_date_format { "\%A\,\ \%\{ce_year\}\ \%B\ \%d" } sub long_date_format { "\%\{ce_year\}\ \%B\ \%\{day\}" } sub medium_date_format { "\%\{ce_year\}\ \%b\ \%\{day\}" } sub short_date_format { "\%y\/\%m\/\%d" } sub full_time_format { "\%H\:\%M\:\%S\ v" } sub long_time_format { "\%H\:\%M\:\%S\ \%\{time_zone_long_name\}" } sub medium_time_format { "\%H\:\%M\:\%S" } sub short_time_format { "\%H\:\%M" } sub date_before_time { $date_before_time } sub date_parts_order { $date_parts_order } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/Locale/tn.pm
Perl
mit
3,042
# Time-stamp: "2002-11-16 01:57:08 MST" require 5; package MIDI::Score; use strict; use vars qw($Debug $VERSION); use Carp; $VERSION = 0.79; =head1 NAME MIDI::Score - MIDI scores =head1 SYNOPSIS # it's a long story; see below =head1 DESCRIPTION This module provides functions to do with with MIDI scores. It is used as the basis for all the functions in MIDI::Simple. (Incidentally, MIDI::Opus's draw() method also uses some of the functions in here.) Whereas the events in a MIDI event structure are items whose timing is expressed in delta-times, the timing of items in a score is expressed as an absolute number of ticks from the track's start time. Moreover, pairs of 'note_on' and 'note_off' events in an event structure are abstracted into a single 'note' item in a score structure. 'note' takes the following form: ('note_on', I<start_time>, I<duration>, I<channel>, I<note>, I<velocity>) The problem that score structures are meant to solve is that 1) people definitely don't think in delta-times -- they think in absolute times or in structures based on that (like 'time from start of measure'); 2) people think in notes, not note_on and note_off events. So, given this event structure: ['text_event', 0, 'www.ely.anglican.org/parishes/camgsm/chimes.html'], ['text_event', 0, 'Lord through this hour/ be Thou our guide'], ['text_event', 0, 'so, by Thy power/ no foot shall slide'], ['patch_change', 0, 1, 8], ['note_on', 0, 1, 25, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 29, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 27, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 20, 96], ['note_off', 192, 0, 1, 0], ['note_on', 0, 1, 25, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 27, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 29, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 25, 96], ['note_off', 192, 0, 1, 0], ['note_on', 0, 1, 29, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 25, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 27, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 20, 96], ['note_off', 192, 0, 1, 0], ['note_on', 0, 1, 20, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 27, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 29, 96], ['note_off', 96, 0, 1, 0], ['note_on', 0, 1, 25, 96], ['note_off', 192, 0, 1, 0], here is the corresponding score sctructure: ['text_event', 0, 'www.ely.anglican.org/parishes/camgsm/chimes.html'], ['text_event', 0, 'Lord through this hour/ be Thou our guide'], ['text_event', 0, 'so, by Thy power/ no foot shall slide'], ['patch_change', 0, 1, 8], ['note', 0, 96, 1, 25, 96], ['note', 96, 96, 1, 29, 96], ['note', 192, 96, 1, 27, 96], ['note', 288, 192, 1, 20, 96], ['note', 480, 96, 1, 25, 96], ['note', 576, 96, 1, 27, 96], ['note', 672, 96, 1, 29, 96], ['note', 768, 192, 1, 25, 96], ['note', 960, 96, 1, 29, 96], ['note', 1056, 96, 1, 25, 96], ['note', 1152, 96, 1, 27, 96], ['note', 1248, 192, 1, 20, 96], ['note', 1440, 96, 1, 20, 96], ['note', 1536, 96, 1, 27, 96], ['note', 1632, 96, 1, 29, 96], ['note', 1728, 192, 1, 25, 96] Note also that scores aren't crucially ordered. So this: ['note', 768, 192, 1, 25, 96], ['note', 960, 96, 1, 29, 96], ['note', 1056, 96, 1, 25, 96], means the same thing as: ['note', 960, 96, 1, 29, 96], ['note', 768, 192, 1, 25, 96], ['note', 1056, 96, 1, 25, 96], The only exception to this is in the case of things like: ['patch_change', 200, 2, 15], ['note', 200, 96, 2, 25, 96], where two (or more) score items happen I<at the same time> and where one affects the meaning of the other. =head1 WHAT CAN BE IN A SCORE Besides the new score structure item C<note> (covered above), the possible contents of a score structure can be summarized thus: Whatever can appear in an event structure can appear in a score structure, save that its second parameter denotes not a delta-time in ticks, but instead denotes the absolute number of ticks from the start of the track. To avoid the long periphrase "items in a score structure", I will occasionally refer to items in a score structure as "notes", whether or not they are actually C<note> commands. This leaves "event" to unambiguously denote items in an event structure. These, below, are all the items that can appear in a score. This is basically just a repetition of the table in L<MIDI::Event>, with starttime substituting for dtime -- so refer to L<MIDI::Event> for an explanation of what the data types (like "velocity" or "pitch_wheel"). As far as order, the first items are generally the most important: =over =item ('note', I<starttime>, I<duration>, I<channel>, I<note>, I<velocity>) =item ('key_after_touch', I<starttime>, I<channel>, I<note>, I<velocity>) =item ('control_change', I<starttime>, I<channel>, I<controller(0-127)>, I<value(0-127)>) =item ('patch_change', I<starttime>, I<channel>, I<patch>) =item ('channel_after_touch', I<starttime>, I<channel>, I<velocity>) =item ('pitch_wheel_change', I<starttime>, I<channel>, I<pitch_wheel>) =item ('set_sequence_number', I<starttime>, I<sequence>) =item ('text_event', I<starttime>, I<text>) =item ('copyright_text_event', I<starttime>, I<text>) =item ('track_name', I<starttime>, I<text>) =item ('instrument_name', I<starttime>, I<text>) =item ('lyric', I<starttime>, I<text>) =item ('marker', I<starttime>, I<text>) =item ('cue_point', I<starttime>, I<text>) =item ('text_event_08', I<starttime>, I<text>) =item ('text_event_09', I<starttime>, I<text>) =item ('text_event_0a', I<starttime>, I<text>) =item ('text_event_0b', I<starttime>, I<text>) =item ('text_event_0c', I<starttime>, I<text>) =item ('text_event_0d', I<starttime>, I<text>) =item ('text_event_0e', I<starttime>, I<text>) =item ('text_event_0f', I<starttime>, I<text>) =item ('end_track', I<starttime>) =item ('set_tempo', I<starttime>, I<tempo>) =item ('smpte_offset', I<starttime>, I<hr>, I<mn>, I<se>, I<fr>, I<ff>) =item ('time_signature', I<starttime>, I<nn>, I<dd>, I<cc>, I<bb>) =item ('key_signature', I<starttime>, I<sf>, I<mi>) =item ('sequencer_specific', I<starttime>, I<raw>) =item ('raw_meta_event', I<starttime>, I<command>(0-255), I<raw>) =item ('sysex_f0', I<starttime>, I<raw>) =item ('sysex_f7', I<starttime>, I<raw>) =item ('song_position', I<starttime>) =item ('song_select', I<starttime>, I<song_number>) =item ('tune_request', I<starttime>) =item ('raw_data', I<starttime>, I<raw>) =back =head1 FUNCTIONS This module provides these functions: =over =item $score2_r = MIDI::Score::copy_structure($score_r) This takes a I<reference> to a score structure, and returns a I<reference> to a copy of it. Example usage: @new_score = @{ MIDI::Score::copy_structure( \@old_score ) }; =cut sub copy_structure { return &MIDI::Event::copy_structure(@_); # hey, a LoL is an LoL } ########################################################################## =item $events_r = MIDI::Score::score_r_to_events_r( $score_r ) =item ($events_r, $ticks) = MIDI::Score::score_r_to_events_r( $score_r ) This takes a I<reference> to a score structure, and converts it to an event structure, which it returns a I<reference> to. In list context, also returns a second value, a count of the number of ticks that structure takes to play (i.e., the end-time of the temporally last item). =cut sub score_r_to_events_r { # list context: Returns the events_r AND the total tick time # scalar context: Returns events_r my $score_r = $_[0]; my $time = 0; my @events = (); croak "MIDI::Score::score_r_to_events_r's first arg must be a listref" unless ref($score_r); # First, turn instances of 'note' into 'note_on' and 'note_off': foreach my $note_r (@$score_r) { next unless ref $note_r; if($note_r->[0] eq 'note') { my @note_on = @$note_r; #print "In: ", map("<$_>", @note_on), "\n"; $note_on[0] = 'note_on'; my $duration = splice(@note_on, 2, 1); my @note_off = @note_on; # /now/ copy it $note_off[0] = 'note_off'; $note_off[1] += $duration; $note_off[4] = 0; # set volume to 0 push(@events, \@note_on, \@note_off); #print "on: ", map("<$_>", @note_on), "\n"; #print "off: ", map("<$_>", @note_off), "\n"; } else { push(@events, [@$note_r]); } } # warn scalar(@events), " events in $score_r"; $score_r = sort_score_r(\@events); # warn scalar(@$score_r), " events in $score_r"; # Now we turn it into an event structure by fiddling the timing $time = 0; foreach my $event (@$score_r) { next unless ref($event) && @$event; my $delta = $event->[1] - $time; # Figure out the delta $time = $event->[1]; # Move it forward $event->[1] = $delta; # Swap it in } return($score_r, $time) if wantarray; return $score_r; } ########################################################################### =item $score2_r = MIDI::Score::sort_score_r( $score_r) This takes a I<reference> to a score structure, and returns a I<reference> to a sorted (by time) copy of it. Example usage: @sorted_score = @{ MIDI::Score::sort_score_r( \@old_score ) }; =cut sub sort_score_r { # take a reference to a score LoL, and sort it by note start time, # and return a reference to that sorted LoL. Notes from the same # time must be left in the order they're found!!!! That's why we can't # just use sort { $a->[1] <=> $b->[1] } (@$score_r) my $score_r = $_[0]; my %timing = (); foreach my $note_r (@$score_r) { push( @{$timing{ $note_r->[1] }}, $note_r ) if ref($note_r); } # warn scalar(@$score_r), " events in $score_r"; #print "sequencing for times: ", map("<$_> ", # sort {$a <=> $b} keys(%timing) # ), "\n"; return [ map(@{ $timing{$_} }, sort {$a <=> $b} keys(%timing) ) ]; } ########################################################################### =item $score_r = MIDI::Score::events_r_to_score_r( $events_r ) =item ($score_r, $ticks) = MIDI::Score::events_r_to_score_r( $events_r ) This takes a I<reference> to an event structure, converts it to a score structure, which it returns a I<reference> to. If called in list context, also returns a count of the number of ticks that structure takes to play (i.e., the end-time of the temporally last item). =cut sub events_r_to_score_r { # Returns the score_r AND the total tick time my $events_r = $_[0]; croak "first argument to MIDI::Score::events_to_score is not a listref!" unless $events_r; my $options_r = ref($_[1]) ? $_[1] : {}; my $time = 0; if( $options_r->{'no_note_abstraction'} ) { my $score_r = MIDI::Event::copy_structure($events_r); foreach my $event_r (@$score_r) { # print join(' ', @$event_r), "\n"; $event_r->[1] = ($time += $event_r->[1]) if ref($event_r); } return($score_r, $time) if wantarray; return $score_r; } else { my %note = (); my @score = map { if(!ref($_)) { (); } else { $_ = [@$_]; # copy. $_->[1] = ($time += $_->[1]) if ref($_); if($_->[0] eq 'note_off' or($_->[0] eq 'note_on' && $_->[4] == 0) ) { # End of a note # print "Note off : @$_\n"; delete( $note{pack 'CC', @{$_}[2,3]} )->[2] += $time if exists $note{ pack 'CC', @{$_}[2,3] }; (); # Erase this event. } elsif ($_->[0] eq 'note_on') { # Start of a note $_ = [@$_]; $note{ pack 'CC', @{$_}[2,3] } = $_; splice(@$_, 2, 0, -$time); $_->[0] = 'note'; # ('note', Starttime, Duration, Channel, Note, Veloc) $_; } else { $_; } } } @$events_r ; #print "notes remaining on stack: ", scalar(values %note), "\n" # if values %note; foreach my $one (values %note) { $one->[2] += $time; } return(\@score, $time) if wantarray; return \@score; } } ########################################################################### =item $ticks = MIDI::Score::score_r_time( $score_r ) This takes a I<reference> to a score structure, and returns a count of the number of ticks that structure takes to play (i.e., the end-time of the temporally last item). =cut sub score_r_time { # returns the duration of the score you pass a reference to my $score_r = $_[0]; croak "arg 1 of MIDI::Score::score_r_time isn't a ref" unless ref $score_r; my $track_time = 0; foreach my $event_r (@$score_r) { next unless @$event_r; my $event_end_time = ($event_r->[0] eq 'note') ? ($event_r->[1] + $event_r->[2]) : $event_r->[1] ; #print "event_end_time: $event_end_time\n"; $track_time = $event_end_time if $event_end_time > $track_time; } return $track_time; } ########################################################################### =item MIDI::Score::dump_score( $score_r ) This dumps (via C<print>) a text representation of the contents of the event structure you pass a reference to. =cut sub dump_score { my $score_r = $_[0]; print "\@notes = ( # ", scalar(@$score_r), " notes...\n"; foreach my $note_r (@$score_r) { print " [", &MIDI::_dump_quote(@$note_r), "],\n" if @$note_r; } print ");\n"; return; } ########################################################################### =back =head1 COPYRIGHT Copyright (c) 1998-2002 Sean M. Burke. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHOR Sean M. Burke C<sburke@cpan.org> =cut 1; __END__
carlgao/lenga
images/lenny64-peon/usr/share/perl5/MIDI/Score.pm
Perl
mit
13,540
package omnitool::omniclass::saver; =cut Here is the main event: where we create or update the data records managed by OmniTool. Please see extensive notes in omniclass.pm =cut $omnitool::omniclass::saver::VERSION = '6.0'; # new way of doing something we've done in the past # time to grow up use strict; # kick off the routine to find our data! sub save { # need myself and my args my $self = shift; my (%args) = @_; my ($restore_params, $args_ref, $data_code, $field, $field_type, $table_column, $we_shall, $lock_user,$lock_remaining_minutes, $params_key, $log_message, $log_file, $p); # create or update? use easy-to-remember scalar if ($args{data_code} !~ /\d\_\d/) { $we_shall = 'create'; $args{data_code} = ''; # no bogus data-codes } else { $we_shall = 'update'; } # most of the time, our field values will be in the %$params hash, but let's allow them to use # an alternative hashref, placed into $args{params} # since we prefer you use $self-{luggage}{params}, we'll wedge it in a bit if ($args{params} && ref($args{params}) eq 'HASH') { # save the standard %$params for use afer we're done in save() $self->{luggage}{stash_params} = $self->{luggage}{params}; $restore_params = 1; # only do this within this execute, if we are saving many items # and put their desired values $self->{luggage}{params} = $args{params}; # perhaps they want to use some of the $self->{luggage}{params}, allow for a merge if ($args{merge_params}) { foreach $p (keys %{ $self->{luggage}{stash_params} }) { $args{params}{$p} = $self->{luggage}{stash_params}{$p} if !$args{params}{$p}; } } } # if updating, check to see if this data is locked if ($we_shall eq 'update') { ($lock_user,$lock_remaining_minutes) = $self->check_data_lock($args{data_code}); if ($lock_user) { # locked, can't proceed return; } # if creating, make sure we have a valid parent set } elsif ($we_shall eq 'create' && $args{parent} !~ /top|\d\_\d\:\d/) { return; } # good place to reun the pre-save hook $args_ref = \%args; # will need below too if (!$self->{skip_hooks} && !$args{skip_hooks} && $self->can('pre_save')) { $args{we_shall} = $we_shall; # useful to know what we are doing $self->pre_save($args_ref); # we might choose to cancel the create/update in the pre_save hook; if you want to do that, fill '$$args{cancel_save}' if ($args{cancel_save}) { # how about a useful message? return; } } # at this point, we need to massage the %$params a bit to make sure everything is in their right place; # simple fields (short text, long-text, single-selects) will already be in place, but dates, files # multi-selects, and others may be a bit spread out. If calling from a script or CLI, they may # be already prepped, but let's go through them anyway. We just want to make sure there is a value # in the %$params which relates to each column in this datatype's table; bearing in mind that (a) # the field may not be required and (b) we may have a prefix on the key name in %$params, i.e. # when creating multiple records (of different or the same type). Also, "%$params" means $$luggage{params}. # Gosh, this comment has been going on a while. I am likely not impressing you with either my clarity # nor my brevity. Should have used 'neither/nor' there. Will fix that later. # we are going to rely on the omniclass::field_grabber() package, which is part of # this monster object # go thru each field and handle based on its field_type foreach $field (@{ $self->{datatype_info}{fields_key} }) { # some sanity here $table_column = $self->{datatype_info}{fields}{$field}{table_column}; $field_type = $self->{datatype_info}{fields}{$field}{field_type}; # call the module, which will update $self->{luggage}{params} in place if ($self->can($field_type)) { $self->$field_type($table_column,$args_ref,$field); } } # now, to do the actual create or update, we are going to use separate methods below, for the sake # of segmenting this code a bit. if ($we_shall eq 'create') { # do you need a comment here? $data_code = $self->do_create($args_ref); } else { # or here? $data_code = $self->do_update($args_ref); } # note that for use in post_save $self->{last_saved_data_code} = $data_code; # if there were some file uploads, tie them to this record foreach $field (@{ $self->{datatype_info}{fields_key} }) { # only file updates next if $self->{datatype_info}{fields}{$field}{field_type} ne 'file_upload'; # figure the params keys $table_column = $self->{datatype_info}{fields}{$field}{table_column}; $params_key = $self->figure_the_key($table_column,$args_ref); # skip if blank next if !$self->{luggage}{params}{$params_key}; # go for the tie-in $self->{file_manager}->tie_to_record($self->{luggage}{params}{$params_key},$self->{dt},$data_code,$field); } # good place to run the post-save hook if (!$self->{skip_hooks} && !$args{skip_hooks} && $self->can('post_save')) { $self->post_save($args_ref); } # if they used their own params, put the 'real' psgi params back in place for the rest of execute if ($self->{luggage}{stash_params} && $restore_params) { $self->{luggage}{params} = $self->{luggage}{stash_params}; } # let's log out all changes $log_message = $self->{luggage}{username}.' '.$we_shall.'d '.$data_code; $log_file = 'saves_'.$self->{database_name}.'_'.$self->{table_name}; $self->{belt}->logger($log_message, $log_file); } # subroutine to handle the actual creating / insert commands sub do_create { # need myself and my args my $self = shift; my ($args) = @_; my ($is_draft, $altcode, $data_code, $field, $name_key, $params_key, $q_mark_list, $record_cols, $table_column, @values); # first the parent and name push(@values,$$args{parent}); # remember, may have a base-name to the %$params, so rely on a module below to save lines $name_key = $self->figure_the_key('name',$args); if (!$self->{luggage}{params}{$name_key}) { # some forms do not provide a name field push(@values,'Not Named'); } else { push(@values,$self->{luggage}{params}{$name_key}); } # will need this for status message $$args{new_name} = $values[1]; # start off our column list $record_cols = 'parent,name'; foreach $field (@{ $self->{datatype_info}{fields_key} }) { # skip virtual fields next if $self->{datatype_info}{fields}{$field}{virtual_field} eq 'Yes'; # table column $table_column = $self->{datatype_info}{fields}{$field}{table_column}; # sanity # add to the list of columns $record_cols .= ','.$table_column; # which %$params key shall we use? $params_key = $self->figure_the_key($table_column,$args); # add to our values push(@values,$self->{luggage}{params}{$params_key}); } # need a comma-list of the q-marks $q_mark_list = $self->{belt}->q_mark_list(scalar @values); # FYI, this is the spot where $self->{server_id} is used to imprint this record # as having been created on this particular database server # construct and execute the insert statement for the main record $self->{db}->do_sql( 'insert into '.$self->{database_name}.'.'.$self->{table_name}. ' (server_id,'.$record_cols.') values ('. $self->{server_id}.','.$q_mark_list.')', \@values ); # determine the new 'data_code' primary key $data_code = $self->{db}->{last_insert_id}.'_'.$self->{server_id}; # fail out if there was a problem with the insert, rather than make a mess if (!$self->{db}->{last_insert_id}) { $self->{belt}->mr_zebra(qq{Data create failed.},1); } # constructing the metainfo record is a bit more dynamic, and probably confusing # and we can skip it if the datatype does not want metainfo if ($self->{datatype_info}{skip_metainfo} ne 'Yes') { # the 'altcode' is the human-friendly unique identifier, and we have a standard # altcode-maker method below; it is recommended that for important datatypes, # you override this in the datatype's specific class/perl_module $altcode = $self->altcode_maker($args); # no spaces in that altcode! $altcode =~ s/\s//g; # on create only, they can flag something as 'draft' data, and later set it to not draft # via the 'not_draft()' method below if ($$args{is_draft}) { $is_draft = 'Yes'; } else { $is_draft = 'No'; } $self->{db}->do_sql('insert into '.$self->{database_name}.'.'.$self->{metainfo_table}. ' (server_id,altcode,data_code,the_type,table_name,originator,'. 'create_time,updater,update_time,parent,is_draft) '. 'values (?,?,?,?,?,?,unix_timestamp(),?,unix_timestamp(),?,?)', [ $self->{server_id}, $altcode, $data_code, $self->{dt}, $self->{table_name}, $self->{luggage}{username}, $self->{luggage}{username}, $$args{parent}, $is_draft ] ); # update the proud new parent's children column $self->children_update($$args{parent}) if $$args{parent} ne 'top'; } # if they want an extended update history, this is a good time to start it if ($self->{datatype_info}{extended_change_history} eq 'Yes') { $self->update_history('New Record "'.$$args{new_name}.'" was created.',$$args{data_code}); } # send back the data_code return $data_code; } # quick method to mark a piece of data as 'not draft' # just need the target primary key / data code for lifting the 'draft' mark sub not_draft { my $self = shift; my ($data_code) = @_; $self->{db}->do_sql( 'update '.$self->{database_name}.'.'.$self->{metainfo_table}. qq{ set is_draft='No' where the_type=? and data_code=?}, [$self->{dt}, $data_code] ); # pretty easy } # subroutine to handle the actual updating / update commands sub do_update { # need myself and my args my $self = shift; my ($args) = @_; my ($altcode, $before_altcode, $before_update_record, $code, $dc, $field, $params_key, $rec_key, $server_id, $table_column, $update_detail, $update_detail_name_chg, $update_detail_text, $update_sql, @update_details, @values); # let's try to use our primary key for the lookup; we have a nice subroutine in our utility belt for that ($code,$server_id) = split /_/, $$args{data_code}; # sanity for the comparisons for extended_change_history $dc = $$args{data_code}; # if they want detailed updates, our first order of business is to grab a copy of the record # prior to its modification if ($self->{datatype_info}{extended_change_history} eq 'Yes') { ($before_update_record,$rec_key) = $self->{db}->sql_hash( qq{select concat(code,'_',server_id),name,}.$self->{datatype_info}{all_db_columns}.' from '. $self->{database_name}.'.'.$self->{table_name}. ' where code=? and server_id=?', ( 'bind_values' => [$code,$server_id] ) ); } # note that we do not change the parent here; the method for that is change_parent(); # build a nice update statement $update_sql = 'update '.$self->{database_name}.'.'.$self->{table_name}.' set '; # go thru each field foreach $field (@{ $self->{datatype_info}{fields_key} }) { $table_column = $self->{datatype_info}{fields}{$field}{table_column}; # sanity # skip if it's a virtual (generated) field next if $self->{datatype_info}{fields}{$field}{virtual_field} eq 'Yes'; # which %$params key shall we use? $params_key = $self->figure_the_key($table_column,$args); # if they sent 'skip_blank_fields', we will only update those fields which have some value next if $$args{skip_blanks} && !(length($self->{luggage}{params}{$params_key})); # testing with length() allows them to send a 0 # if it's a hidden_field, it may be blank for a normal form update, allowing # for the parent to set these via post_save next if $self->{datatype_info}{fields}{$field}{field_type} eq 'hidden_field' && !(length($self->{luggage}{params}{$params_key})); # add to the update SQL $update_sql .= $table_column.'=?, '; # add to our values push(@values,$self->{luggage}{params}{$params_key}); # if logging the update details, keep track of changes if ($self->{datatype_info}{extended_change_history} eq 'Yes' && $$before_update_record{$dc}{$table_column} ne $self->{luggage}{params}{$params_key}) { # we will limit the values to the first 200 chars for space/sanity # we will join this together later push(@update_details, $self->{datatype_info}{fields}{$field}{name}.' was modified:'. "\nOld Value: ".substr($$before_update_record{$dc}{$table_column},0,200). "\nNew Value: ".substr($self->{luggage}{params}{$params_key},0,200) ); } } # name/title column too # which %$params key shall we use? $params_key = $self->figure_the_key('name',$args); # for the name, if they didn't send a name, we will automatically use the pre-existing name if (length($self->{luggage}{params}{$params_key})) { $update_sql .= 'name=?'; # add to our values push(@values,$self->{luggage}{params}{$params_key}); # will need this for status message $$args{new_name} = $self->{luggage}{params}{$params_key}; } else { # get the name from the DB ($$args{new_name}) = $self->{db}->quick_select( 'select name from '.$self->{database_name}.'.'.$self->{table_name}. ' where code=? and server_id=?', [$code,$server_id] ); # also can't use the last space/comma in $update_sql now $update_sql =~ s/\,\ $//; } # if logging the update details, keep track of changes if ($self->{datatype_info}{extended_change_history} eq 'Yes' && $$before_update_record{$dc}{'name'} ne $self->{luggage}{params}{$params_key}) { # we will limit the values to the first 200 chars for space/sanity # this one goes on the front unshift(@update_details, 'Name/Title was modified:'. "\nOld Value: ".substr($$before_update_record{$dc}{'name'},0,200). "\nNew Value: ".substr($self->{luggage}{params}{$params_key},0,200) ); $update_detail_name_chg .= "\nOld Value: ".substr($$before_update_record{$dc}{'name'},0,200); $update_detail_name_chg .= "\nNew Value: ".substr($self->{luggage}{params}{$params_key},0,200); } # finish the SQL statement $update_sql .= ' where code=? and server_id=?'; push(@values,$code,$server_id); # commit the update to the main record table if (scalar(@values) > 2) { # only proceed if at least one field is getting updated, since we allow for skipping-blanks $self->{db}->do_sql($update_sql,\@values); } # for the metainfo, mainly it's the updater & update_time; and they may want to to update the altcode if ($self->{datatype_info}{metainfo_table} ne 'No Metainfo') { # see if there are changes to the altcode ($before_altcode) = $self->{db}->quick_select( 'select altcode from '.$self->{database_name}.'.'.$self->{metainfo_table}. ' where the_type=? and data_code=?', [$self->{dt}, $$args{data_code}] ); # check the altcode & access list; which %$params key shall we use? $params_key = $self->figure_the_key('altcode',$args); $altcode = $self->{luggage}{params}{$params_key}; # check to see if they are changed if ($self->{datatype_info}{extended_change_history} eq 'Yes') { if ($altcode ne $before_altcode && $altcode) { # blank is OK too push(@update_details, 'Altcode was modified:'. "\nOld Value: ".$before_altcode. "\nNew Value: ".$altcode ); } } # if neither was sent, originals are defaults $altcode ||= $before_altcode; # commit the update to the metainfo table $self->{db}->do_sql( 'update '.$self->{database_name}.'.'.$self->{metainfo_table}. ' set altcode=?, updater=?, update_time=unix_timestamp()'. ' where the_type=? and data_code=?', [$altcode,$self->{luggage}{username}, $self->{dt}, $$args{data_code}] ); } if ($self->{datatype_info}{extended_change_history} eq 'Yes') { # put the details together if (!$update_details[0]) { # no changes? $update_detail_text = 'No fields were actually changed'; } else { # put them together $update_detail_text = join("\n------\n",@update_details); } # save that history $self->update_history($update_detail_text,$$args{data_code}); } # OK, do they want to auto-(re)load the updated record if ($$args{auto_load}) { # yessir! $self->load( 'data_codes' => [$$args{data_code}], 'skip_hooks' => $$args{skip_hooks}, ); } return $$args{data_code}; } # generic altcode-generator; you definitely want to override this with your custom classes sub altcode_maker { # need myself and my args my $self = shift; my ($args) = @_; my ($month_year, $table_name, $proposed_altcode); # get month abbreviation from utility belt $month_year = $self->{belt}->time_to_date(time(),'to_month_abbrev'); # clean table table ($table_name = $self->{table_name}) =~ s/_//g; # mash together the month, username, table name, and auto_increment column, and send that mess out $proposed_altcode = $month_year.$self->{luggage}{username}.'_'.$table_name.$self->{db}->{last_insert_id}; # if that's more than 50 chars, try a version without the username if (length($proposed_altcode) > 50) { $proposed_altcode = $month_year.'_'.$table_name.$self->{db}->{last_insert_id}; # still over 50 chars? really stripped down version if (length($proposed_altcode) > 50) { $proposed_altcode = $month_year.'_'.$self->{dt}.'_'.$self->{db}->{last_insert_id}; } } # that is not the right way to handle that logic, but I still like it. # send it out return $proposed_altcode; } # if you have overriden altcode_maker() in your own class, you probably don't want to use # the 'last_insert_id', but rather count(*)+1 of the records created this month # this subroutine allows you to pass a base-pattern (i.e. MonYYYY) to find the count(*)+1 value # the base_pattern is always the start of the proposed altcode sub altcode_next_number { my $self = shift; my ($base_pattern) = @_; return if !$base_pattern; # proceed with our search my ($altcode_next_number) = $self->{db}->quick_select( 'select count(*)+1 from '.$self->{database_name}.'.'.$self->{metainfo_table}. qq{ where the_type=? and altcode like ?}, [$self->{dt}, $base_pattern.'%'] ); # make sure it is at least three digits long while (length($altcode_next_number) < 3) { $altcode_next_number = '0'.$altcode_next_number; } # send it out return $altcode_next_number; } # quick subroutine to minimize repeated if/else for figuring %$param keys; for use in this module only sub figure_the_key { my $self = shift; my ($key,$args) = @_; if (length($$args{params_key})) { return $$args{params_key}.'_'.$key; } else { return $key; } } # convenience method for updating a few fields of a record # something i should have written two years ago ;) sub simple_save { my $self = shift; my (%args) = @_; my (@sent_keys, $data_code); # did they send a data code? if ($args{data_code}) { # yes $data_code = $args{data_code}; # don't pass that value into the save() params delete($args{data_code}); # no -- is there a loaded record? } elsif ($self->{data_code}) { $data_code = $self->{data_code}; } # if there is no data_code, we cannot proceed if (!$data_code) { return; } # now that we cleared $args{data_code}, make sure there are some items left in %args @sent_keys = keys %args; if (!$sent_keys[0]) { return; } # okay, send the command to save() to update the fields $self->save( 'data_code' => $data_code, 'skip_blanks' => 1, 'params' => \%args, ); } # utility method to change the update_time in a record's metainfo entry # use this when you are updating a very important child record sub touch_update_time { my $self = shift; # needed arg is a data_code for a record my ($data_code) = @_; # if no $data_code argument, we'll look at $self->{data_code} $data_code ||= $self->{data_code}; # do nothing without a data_code return if !$data_code; # do nothing if no metainfo table (rare) return if $self->{datatype_info}{metainfo_table} eq 'No Metainfo'; # otherwise, simple sql statement $self->{db}->do_sql( 'update '.$self->{database_name}.'.'.$self->{metainfo_table}. ' set update_time=unix_timestamp(), updater=? where the_type=? and data_code=?', [ $self->{luggage}{username}, $self->{dt}, $data_code] ); } 1;
ericschernoff/omnitool
omnitool/omniclass/saver.pm
Perl
mit
20,068
package FuncDecl; use Var; use Utility; my $logger = Log::Log4perl->get_logger('semfix'); sub new { my $class = shift; my $self = { _func_name => undef, _input => [], # @hoang an array of Var _param => [], # @hoang an array of Var _output => [], # @hoang an array of Var _impl => undef, _constraint => undef, }; bless $self, $class; return $self; } sub add_input { my $self = shift; my $var = shift; push (@{$self->{_input}}, $var); return; } sub add_param { my $self = shift; my $var = shift; push (@{$self->{_param}}, $var); return; } sub add_output { my $self = shift; my $var = shift; push (@{$self->{_output}}, $var); return; } sub parse_impl { my $self = shift; my $line = shift; #TODO $self->{_impl} = $line; return; } sub get_impl { my $self = shift; my $impl = $self->{_impl}; $impl =~ s/\\n/\n/g; $impl =~ s/\\t/\ \ \ \ /g; return $impl; } sub get_angelic { my $p_outputs = shift; my @outputs = @{$p_outputs}; # $logger->debug("outputs: " . Dumper(@outputs)); # my $outputs_size = scalar @outputs; # $logger->debug("outputs_size: $outputs_size"); my @filtered = (); foreach my $output (@outputs) { # $logger->debug("output: " . Dumper($output)); my $var_name = $output->{_name}; if ($var_name =~ /!angelic$/) { push (@filtered, $output); } } return \@filtered; } sub get_all_var { my $self = shift; my @tmpout = (); my $func_name = $self->{_func_name}; foreach ( ( @{ $self->{_input} }, @{ $self->{_output} } ) ) { my $var_name = $_->{_name}; push( @tmpout, "$func_name\_$var_name" ); } return \@tmpout; } sub get_all_input { my $self = shift; my @tmpout = (); my $func_name = $self->{_func_name}; foreach ( @{ $self->{_input} } ) { my $var_name = $_->{_name}; DEBUG_PRINT("VARNAME: $var_name"); push( @tmpout, "$func_name\_$var_name" ); } return \@tmpout; } sub get_all_input_type { my $self = shift; my @tmpout = (); foreach ( @{ $self->{_input} } ) { my $var_type = $_->{_type}; push( @tmpout, $var_type); } return \@tmpout; } sub get_all_output_type { my $self = shift; my @tmpout = (); foreach ( @{ $self->{_output} } ) { my $var_type = $_->{_type}; push( @tmpout, $var_type); } return \@tmpout; } sub get_all_output { my $self = shift; my @tmpout = (); my $func_name = $self->{_func_name}; foreach ( @{ $self->{_output} } ) { my $var_name = $_->{_name}; DEBUG_PRINT("VARNAME: $var_name"); push( @tmpout, "$func_name\_$var_name" ); } return \@tmpout; } sub get_all_var_type { my $self = shift; my @tmpout = (); foreach ( ( @{ $self->{_input} }, @{ $self->{_output} } ) ) { my $var_type = $_->{_type}; push( @tmpout, $var_type ); } return \@tmpout; } sub get_decls { # ($ins_index, $io_index) my $self = shift; my $ins_index = shift; my $io_index = shift; $logger->debug("FuncDecl.get_decls called"); my @decl = (); my $func_name = $self->{_func_name}; foreach ( ( @{ $self->{_input} }, @{ $self->{_output} } ) ) { my $var = $_; my $var_name = $var->{_name}; my $var_type = $var->{_type}; my $var_decl; my $new_var_name = "$func_name\_$var_name\_ins$ins_index\_io$io_index"; $var_decl = Utility::getDeclare($new_var_name, $var_type); push( @decl, $var_decl ); if ( $var_type eq "AIC" || $var_type eq "AII") #@hoang add length declaration { my $len_name = "$func_name\_$var_name\_len\_ins$ins_index\_io$io_index"; my $len_type = "INT"; my $len_decl = Utility::getDeclare($len_name, $len_type); push (@decl, $len_decl); } } return join( "", @decl ); } sub get_loc_var_decl { my $self = shift; my $suffix = shift; # optional parameter if ( not defined($suffix) ) { $suffix = ""; } else { $suffix = "_" . $suffix; } my @decl = (); my $func_name = $self->{_func_name}; foreach ( ( @{ $self->{_input} }, @{ $self->{_output} } ) ) { my $var_name = $_->{_name}; $var_name = "$func_name\_$var_name"; my $loc_var = "l_" . $var_name . $suffix; my $loc_type = Utility::getDeclare($loc_var, "Int"); push( @decl, $loc_type ); } return join( "", @decl ); } sub get_all_loc_var { my $self = shift; my @tmp = (); my $func_name = $self->{_func_name}; foreach ( ( @{ $self->{_input} }, @{ $self->{_output} } ) ) { my $var_name = $_->{_name}; $var_name = "$func_name\_$var_name"; my $loc_var = "l_" . $var_name; push( @tmp, $loc_var ); } return \@tmp; } sub get_param { my $self = shift; my @tmp; my $func_name = $self->{_func_name}; foreach ( @{ $self->{_param} } ) { my $var_name = $_->{_name}; $var_name = "$func_name\_$var_name"; push( @tmp, $var_name ); } return \@tmp; } sub get_param_type { my $self = shift; my @tmpout = (); foreach ( @{ $self->{_param} }) { my $var_type = $_->{_type}; push (@tmpout, $var_type); } return \@tmpout } sub get_constraint { # @hoang get_constraint($ins_index, $io_index) my $self = shift; my $ins_index = shift; my $io_index = shift; my $tmp = $self->{_constraint}; my $func_name = $self->{_func_name}; my @param = @{ $self->{_param} }; foreach (@param) { my $tmp_param_name = $_->{_name}; $tmp =~ s/$tmp_param_name/p_$func_name\_$tmp_param_name/g; } $tmp =~ s/(x\d+\_len)/$func_name\_$1\_ins$ins_index\_io$io_index/g; $tmp =~ s/(x\d+)([^\_])/$func_name\_$1\_ins$ins_index\_io$io_index$2/g; return "(assert $tmp)\n"; } sub get_acyc_constraint { my $self = shift; my $suffix = shift; if ( not defined($suffix) ) { $suffix = ""; } else { $suffix = "_" . $suffix; } my @constr = (); my $func_name = $self->{_func_name}; my @output = @{ $self->{_output} }; my $out_var = $output[0]->{_name}; foreach ( @{ $self->{_input} } ) { my $in_name = $_->{_name}; push( @constr, "(assert (< l_$func_name\_$in_name$suffix l_$func_name\_$out_var$suffix))\n" ); } return join( "", @constr ); } sub print_myself { my $self = shift; my $funcname = $self->{_func_name}; print "fun $funcname:1\n"; foreach ( @{ $self->{_input} } ) { my $input_name = $_->{_name}; my $input_type = $_->{_type}; print "in $input_name:($input_type)\n"; } foreach ( @{ $self->{_output} } ) { my $output_name = $_->{_name}; my $output_type = $_->{_type}; print "out $output_name:($output_type)\n"; } if ( defined $self->{_impl} ) { print "impl "; print $self->{_impl} . "\n"; } if ( defined $self->{_constraint} ) { print $self->{_constraint} . "\n"; } foreach ( @{ $self->{_param} } ) { my $param_name = $_->{_name}; print "param $param_name\n"; } } sub DEBUG_PRINT { if (0) { print STDERR "@_\n"; } } 1;
mechtaev/angelix
src/semfix/lib/FuncDecl.pm
Perl
mit
8,731
# Copyright (c) 2010 ToI Inc. All rights reserved. # # 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. # # $Id$ package Tablize; use warnings; use strict; sub _hdlr_tablize { my ($ctx, $args, $cond) = @_; my $per_row = $args->{'tablize_per_row'} or return $ctx->error(MT->translate('tablize_per_row is required')); my $tag = $args->{'tablize_tag'} or return $ctx->error(MT->translate('tablize_tag is required')); local $ctx->{__stash}{'tablize_per_row'} = $per_row; local $ctx->{__stash}{'tablize_index'} = -1; my $tokens = $ctx->stash('tokens'); my @sentinels = grep({ lc($_->[0]) eq lc('TablizeSentinel') } @$tokens); my @is_last_in_rows = grep({ lc($_->[0]) eq lc('TablizeIsLastInRow') } @$tokens); my $container_args = { %$args }; delete $container_args->{'@'}; my $container = bless [ 'TablizeContainer', $container_args, $tokens, [], undef, undef, $tokens->[0][5], $tokens->[0][6], ], 'MT::Template::Node'; my $tablize_target = bless [ $tag, $container_args, bless([ $container ], 'MT::Template::Tokens'), [], undef, undef, $tokens->[0][5], $tokens->[0][6], ], 'MT::Template::Node'; $ctx->stash('tokens', bless([ $tablize_target ], 'MT::Template::Tokens')); my $result = $ctx->slurp($args, $cond); my $index = $ctx->stash('tablize_index'); if (@sentinels) { my $builder = $ctx->stash('builder'); while ($index % $per_row != $per_row - 1) { $index++; for my $t (@sentinels) { my $tmp = $builder->build($ctx, bless([ $t ], 'MT::Template::Tokens'), $cond); return $ctx->error($builder->errstr) unless defined $tmp; $result .= $tmp; } if ($index % $per_row == $per_row - 1) { for my $t (@is_last_in_rows) { my $tmp = $builder->build($ctx, bless([ $t ], 'MT::Template::Tokens'), $cond); return $ctx->error($builder->errstr) unless defined $tmp; $result .= $tmp; } } } } $result; } sub _hdlr_tablize_container { my ($ctx, $args, $cond) = @_; my $stash = $ctx->{__stash}; my $index = ++$stash->{'tablize_index'}; my $per_row = $stash->{'tablize_per_row'}; $ctx->slurp($args, { %$cond, TablizeIsFirstInRow => $index % $per_row == 0, TablizeIsLastInRow => $index % $per_row == $per_row - 1, TablizeSentinel => 0, }); } 1;
usualoma/movable-type-plugin-tablize
lib/Tablize.pm
Perl
mit
3,297
use strict; use warnings; my $image_ajax_form = CXGN::ImageAjaxForm->new(); package CXGN::ImageAjaxForm; use CatalystX::GlobalContext '$c'; use base "CXGN::Page::Form::AjaxFormPage"; use JSON; use SGN::Image; use Try::Tiny; sub define_object { my $self = shift; my %json_hash = $self->get_json_hash(); # call set_object_id, set_object and set_primary_key here # with the appropriate parameters. # my %args = $self->get_args(); if ( !exists( $args{object_id} ) ) { $json_hash{error} = "No object_id provided"; } $self->set_object_name('image'); $self->set_object_id( $args{object_id} ); $self->set_object( SGN::Image->new( $self->get_dbh(), $self->get_object_id(), $c ) ); $self->set_primary_key("object_id"); $self->set_owners( $self->get_object()->get_sp_person_id() ); $self->set_json_hash(%json_hash); } sub generate_form { my $self = shift; my $form_id = 'image_form'; my %args = $self->get_args(); $self->init_form($form_id); my $form = $self->get_form(); my $image = $self->get_object(); my $object_id = $self->get_object_id(); my $submitter = CXGN::People::Person->new( $self->get_dbh(), $image->get_sp_person_id() ); my $sp_person_id = $submitter->get_sp_person_id(); my $submitter_name = ($submitter->get_first_name() || '') . " " . ($submitter->get_last_name() || ''); my $submitter_link = qq |<a href="/solpeople/personal-info.pl?sp_person_id=$sp_person_id">$submitter_name </a> |; my $name = ""; my $description = ""; if ( $self->get_action() =~ /view|edit/i ) { $name = $image->get_name(); $description = $image->get_description(); } if ( $self->get_action() =~ /edit/i ) { $name ||= $args{name}; $description ||= $args{description}; } if ( $self->get_action() =~ /store/i ) { $name = $args{name}; $description = $args{description}; } $form->add_field( display_name => "Image Name:", field_name => "name", contents => $name, length => 15, object => $image, getter => "get_name", setter => "set_name" ); $form->add_field( display_name => "Image Description: ", field_name => "description", contents => $description, length => 40, object => $image, getter => "get_description", setter => "set_description" ); $form->add_hidden( display_name => "Image ID", field_name => "object_id", contents => $object_id ); $form->add_hidden( display_name => "Action", field_name => "action", contents => "store" ); $form->add_label( display_name => "Uploaded by: ", field_name => "submitter", contents => $submitter_link, ); $self->set_form($form); } sub delete { my ( $self ) = @_; $self->check_modify_privileges or $self->print_json; my %json = $self->get_json_hash; try { $self->get_object->delete; $json{success} = 1; } catch { $json{error} = "Deletion failed ($_)"; }; #$self->set_json_hash( %json ); #$self->print_json; } sub store { my $self=shift; my $image = $self->get_object(); my $image_id = $self->get_object_id(); my %args = $self->get_args(); my %json_hash = $self->get_json_hash(); my $error; try{ $self->SUPER::store(); #this sets $json_hash{validate} if the form validation failed. $image_id = $image->get_image_id; } catch { $error = " An error occurred. Cannot store to the database\n An email message has been sent to the SGN development team"; CXGN::Contact::send_email('image_ajax_form.pl died', $error . "\n" . $_ , 'sgn-bugs@sgn.cornell.edu'); }; #the validate field is false is validation passed for all fields, true if did not pass and the form is re-printed %json_hash= $self->get_json_hash(); my $validate= $json_hash{validate}; $json_hash{error} = $error if $error; my $refering_page="/image/index.pl?image_id=$image_id"; $self->send_form_email({subject=>"[New image details stored] image $image_id", mailing_list=>'sgn-db-curation@sgn.cornell.edu', refering_page=>"www.solgenomics.net".$refering_page}) if (!$validate && !$json_hash{error}); $json_hash{refering_page}=$refering_page if !$validate && !$error; $self->set_json_hash(%json_hash); $self->print_json(); }
solgenomics/sgn
cgi-bin/image/ajax/image_ajax_form.pl
Perl
mit
4,657
:- module(output_manager, [abstract_action_to_action/2] ). %====================================================================== :- use_module(library(lists)). :- use_module('$REGULUS/PrologLib/utilities'). %====================================================================== % OUTPUT MANAGEMENT: ABSTRACT ACTION TO CONCRETE ACTION abstract_action_to_action(say(AbsResponse), tts(String)) :- perform_output_generation(AbsResponse, String), !. perform_output_generation(AbsAction, OutputString) :- generation_grammar(AbsAction, OutputWords, []), join_with_spaces(OutputWords, OutputAtom), atom_chars(OutputAtom, OutputString), !. perform_output_generation(_AbsAction, _OutputString) :- format('~N~nError in output manager.~n', []), fail. generation_grammar(no) --> ['no']. generation_grammar(unable_to_interpret) --> ['sorry that doesn\'t make sense']. generation_grammar(ambiguous) --> ['sorry, that\'s ambiguous']. generation_grammar(reverted) --> ['ok, undone']. generation_grammar(dev(Device, Location, _OnOff, Intensity)) --> generation_grammar(device(Device)), ['in'], generation_grammar(location(Location)), ['is'], generation_grammar(intensity(Intensity)). generation_grammar(device(light)) --> ['the light']. generation_grammar(device(fan)) --> ['the fan']. generation_grammar(location(kitchen)) --> ['the kitchen']. generation_grammar(location(living_room)) --> ['the living room']. generation_grammar(intensity(0)) --> ['off']. generation_grammar(intensity(100)) --> ['on']. generation_grammar(intensity(Other)) --> { number(Other), 0 < Other, Other < 100 }, ['dimmed'].
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/regulus/Examples/Toy1/Prolog/output_manager_corrections.pl
Perl
mit
1,619
=head1 NAME CXGN::Page::Form::Field; =head1 DESCRIPTION Implements a static (non-editable) field on a static form. For more information, see L<CXGN::Page::Form>. =head1 AUTHOR(S) Lukas Mueller (lam87@cornell.edu) =cut use strict; use CXGN::Page::Form::ElementI; package CXGN::Page::Form::Field; use base qw/ CXGN::Page::Form::ElementI /; =head2 new Usage: Desc: Ret: Args: a hashref with the following keys: display_name (name of the field for display purposes) field_name (name of the form element) contents (the current value of the field) length (the length of the input field in characters) object (the object this field maps to) getter (the getter function for this field in the object) setter (the setter function for this field in the object) Side Effects: Example: =cut sub new { my $class = shift; my $self = $class->SUPER::new(@_); return $self; } =head2 render Usage: Desc: Ret: Args: Side Effects: Example: =cut sub render { my $self = shift; my $contents = $self->get_contents(); my $formatting = $self->get_formatting(); if ($formatting) { $formatting =~ s/\*/$contents/; $contents = $formatting ; } return $contents."\n"; #return $self->get_contents()."\n"; } return 1;
solgenomics/sgn
lib/CXGN/Page/Form/Field.pm
Perl
mit
1,376
package Plucene::Utils; =head1 NAME Plucene::Utils - Utility class for Plucene =head1 SYNOPSIS use Plucene::Utils; do_locked($sub, $lock); =head1 DESCRIPTION Utilities to help with Plucene. =head1 METHODS =cut use strict; use warnings; use Carp; use Fcntl qw(O_EXCL O_CREAT O_WRONLY); use base 'Exporter'; our @EXPORT = qw( do_locked ); =head2 do_locked do_locked($sub, $lock); =cut sub do_locked (&$) { my ($sub, $lock) = @_; local *FH; for (1 .. 5) { sysopen FH, $lock, O_EXCL | O_CREAT | O_WRONLY and goto got_lock; sleep 1; warn "I had to sleep to get a lock on $lock"; } carp "Couldn't get lock $lock: $!"; got_lock: $sub->(); close *FH; unlink $lock; } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Plucene/Utils.pm
Perl
mit
702
:- expects_dialect(lps). % This ilustrates a bug: % the askMoney action is not firing because the timeless predicate parent's second solution is not being considered maxTime(5). events party/1. actions askMoney/2. fluents hasMoney/1. initially hasMoney(mum). observe party(bob) to 2. parent(bob, dad). parent(bob, mum). if party(bob) then parent(bob,X), hasMoney(X), askMoney(bob, X).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_lps/examples/party_minimal.pl
Perl
mit
393
:- module(dictoo_lib, [ oo/1, oo_bind/2, is_oo/1, is_oo/2, % '$was_dictoo'/2, is_oo_invokable/2, oo_call/4, oo_call_dot_hook/4, oo_jpl_call/3, oo_derefed/2, oo_derefed/3, oo_deref/3, oo_put_attr/3, oo_put_attrs/2, oo_get_attr/3, oo_get_attrs/2, oo_inner_class_begin/1, oo_inner_class_end/1, oo_class_field/1, oo_class_begin/1, oo_class_end/1, oo_set/3, oo_put_dict/4, oo_get_dict/3 ]). /** <module> dictoo_lib - Dict-like OO Syntax Pack Author: Douglas R. Miles E-mail: logicmoo@gmail.com WWW: http://www.logicmoo.org Copyright (C): 2017 This program is free software; you can redistribute it and/or modify it. */ :- set_module(class(library)). :- set_prolog_flag(generate_debug_info, false). :- reexport(library(gvar_lib)). :- use_module(library(dicts)). :- use_module(library(logicmoo/attvar_serializer)). :- multifile(dot_cfg:using_dot_type/2). :- dynamic(dot_cfg:using_dot_type/2). :- nodebug(dictoo(core)). :- nodebug(dictoo(decl)). :- nodebug(dictoo(syntax)). :- nodebug(dictoo(goal_expand)). %:- autoload(library(jpl),[jpl_set/3,jpl_get/3,jpl_call/4]). :- autoload(library(backcomp),[string_to_atom/2]). % :- use_module(atts). :- meta_predicate(fail_on_missing(*)). % fail_on_missing(G):-current_predicate(G),!,call(G). fail_on_missing(G):- notrace(catch(G,error(existence_error(_,_),_),fail)). oo_get_attr(MVar,Attr,Value):- % notrace ((strip_module(MVar,M,Var),oo_call(M,Var,Attr,Value))). oo_put_attr(MVar,Attr,Value):- notrace((strip_module(MVar,M,Var),oo_put_dict(M,Attr,Var,Value))). oo_get_attrs(V,Att3s):- var(V),!,get_attrs(V,Att3s),!. oo_get_attrs('$VAR'(Name),_):- atom(Name),!,fail. oo_get_attrs('$VAR'(Att3s),Att3):-!,Att3s=Att3. oo_get_attrs('aVar'(Att3s),Att3):-!,Att3s=Att3. oo_get_attrs('aVar'(_,Att3s),Att3):-!,Att3s=Att3. % oo_get_attrs(V,Value):- trace_or_throw(oo_get_attrs(V,Value)). put_atts_list([KV|Attrs],Var):-!, get_kv(KV,K,V),oo_set(Var,K,V),put_atts_list(Attrs,Var). put_atts_list([],_):-!. %:- if(exists_source(library(atts))). %:- user:use_module(library(atts)). oo_put_attrs(V,Attrs):- must_be(nonvar,Attrs),is_list(Attrs),!,put_atts_list(Attrs,V). %:- endif. oo_put_attrs(V,Att3s):- var(V),!,put_attrs(V,Att3s),!. oo_put_attrs(VAR,Att3s):- VAR='$VAR'(Name), atom(Name),!,setarg(1,VAR, att(vn, Name, Att3s)). oo_put_attrs(VAR,Att3s):- VAR='$VAR'(_Att3),!,setarg(1,VAR, Att3s). oo_put_attrs(VAR,Att3s):- VAR='aVar'(_Att3),!,setarg(1,VAR, Att3s). oo_put_attrs(VAR,Att3s):- VAR='aVar'(_,_),!,setarg(2,VAR, Att3s). oo_put_attrs(V,Att3s):- trace_or_throw(oo_put_attrs(V,Att3s)). % '$was_dictoo'(_,_). %% is_oo(+Self) is det. %% is_oo(+Module,+Self) is det. % % Tests to see if Self % Has Member Functions % is_oo(S):- ((strip_module(S,M,O),is_oo(M,O))). %is_oo(_,_):- !. % assume we''ll take care of dicts as well is_oo(M,O):- (var(O)->attvar(O); (is_dvar(O)->true; (((((((O='$was_dictoo'(MM,_),ignore(M=MM)); is_dict(O); O=jclass(_); O=jpl(_); O= class(_); O='&'(_) ; O='&'(_,_) ; functor(O,'.',2); is_logtalk_object(O); (oo_deref(M,O,DREF)->O\==DREF); fail_on_missing(jpl_is_ref(O)); fail_on_missing(cli_is_object(O)); fail_on_missing(cli_is_struct(O)))))))))),!. :- if((false,exists_source(library(multivar)))). :- use_module(library(multivar)). oo(O):- call(ignore,xvarx(O)),put_attr(O,oo,binding(O,_Value)). :- else. oo(O):- do_but_warn(put_attr(O,oo,binding(O,_Value))). :- endif. do_but_warn(G):- call(G),dmsg(do_but_warn(G)). oo_bind(O,Value):- oo(O),put_attr(O,oo,binding(O,Value)). oo:attr_unify_hook(B,Value):- B = binding(_Var,Prev)->Prev.equals(Value);true. oo_get_extender(_,_):-fail. oo_put_extender(_,_):-fail. new_oo(_M,Self,NewSelf):- oo(Self)->NewSelf=Self. logtalk_ready :- current_predicate(logtalk:current_logtalk_flag/2). is_logtalk_object(O):- logtalk_ready, call(call,logtalk:current_object(O)). nb_setattr(Att,Key,Value):-nb_setattr(Att,Att,Key,Value). nb_setattr(att(Key,_OldValue,_),Atts,Key,Value):-!,nb_setarg(2,Atts,Value). nb_setattr(att(_,_,[]),Att,Key,Value):-!,nb_setarg(3,Att,att(Key,Value,[])). nb_setattr(att(_,_,Att),_,Key,Value):-nb_setattr(Att,Att,Key,Value). b_setattr(Att,Key,Value):-b_setattr(Att,Att,Key,Value). b_setattr(att(Key,_OldValue,_),Atts,Key,Value):-!,setarg(2,Atts,Value). b_setattr(att(_,_,[]),Att,Key,Value):-!,setarg(3,Att,att(Key,Value,[])). b_setattr(att(_,_,Att),_,Key,Value):-b_setattr(Att,Att,Key,Value). oo_set(UDT,Key,Value):- attvar(UDT),!,get_attrs(UDT,Atts),nb_setattr(Atts,Atts,Key,Value). oo_set(UDT,Key,Value):- var(UDT),!,do_but_warn(put_attr(UDT,Key,Value)),!. oo_set(UDT,Key,Value):- oo_derefed(UDT,DREF),!,oo_set(DREF,Key,Value). oo_set(UDT,Key,Value):- is_dict(UDT),!,nb_set_dict(Key,UDT,Value). %oo_set(UDT,Key,Value):- is_rbtree(UDT),!,nb_rb_insert(UDT, Key, Value),!. oo_set(UDT,Key,Value):- is_rbtree(UDT),!,rb_insert(UDT,Key,Value,NewUDT),nb_copy(2,NewUDT,UDT). oo_set(UDT,Key,Value):- is_assoc(UDT),!, put_assoc(Key,UDT,Value,NewUDT),nb_copy(NewUDT,UDT). oo_set(UDT,Key,Value):- UDT=..[U,D|T], oo_nb_set_varholder(U,D,T,UDT,Key,Value). oo_set(UDT,Key,Value):- is_list(UDT),!,((member(KV,UDT),get_kv(KV,K,_),Key==K,nb_set_kv(KV,K,Value))->true;(nb_copy([Key-Value|UDT],UDT))). oo_set(UDT,Key,Value):- fail_on_missing(jpl_is_ref(UDT)),fail_on_missing(jpl_set(UDT,Key,Value)). %oo_set(UDT,Key,Value):- trace_or_throw(oo_set(UDT,Key,Value)). oo_nb_set_varholder('$VAR',Name,[],UDT,Key,Value):- atom(Name),!,nb_setarg(1,UDT,att(vn, Name, att(Key,Value, []))). oo_nb_set_varholder('$VAR',Att3,[],UDT,Key,Value):- nb_setarg(1,UDT,att(Key,Value,Att3)). oo_nb_set_varholder('aVar',Att3,[],UDT,Key,Value):- nb_setarg(1,UDT,att(Key,Value,Att3)). oo_nb_set_varholder('aVar',_D,[Att3],UDT,Key,Value):- nb_setarg(2,UDT,att(Key,Value,Att3)). oo_nb_set_varholder('att',_D,_T,UDT,Key,Value):- !,nb_setattr(UDT,Key,Value). oo_b_set_varholder('$VAR',Name,[],UDT,Key,Value):- atom(Name),!,setarg(1,UDT,att(vn, Name, att(Key,Value, []))). oo_b_set_varholder('$VAR',Att3,[],UDT,Key,Value):- setarg(1,UDT,att(Key,Value,Att3)). oo_b_set_varholder('aVar',Att3,[],UDT,Key,Value):- setarg(1,UDT,att(Key,Value,Att3)). oo_b_set_varholder('aVar',_D,[Att3],UDT,Key,Value):- setarg(2,UDT,att(Key,Value,Att3)). oo_b_set_varholder('att',_D,_T,UDT,Key,Value):- !,b_setattr(UDT,Key,Value). b_copy(NewMap,Map):-functor(NewMap,F,A),functor(Map,F,A),b_copy(A,NewMap,Map). b_copy(A,NewMap,Map):- arg(A,NewMap,E),setarg(A,NewMap,E), (A==1-> true ; Am1 is A-1, (b_copy(Am1,NewMap,Map))). nb_copy(NewMap,Map):-functor(NewMap,F,A),functor(Map,F,A),nb_copy(A,NewMap,Map). nb_copy(2,NewUDT,UDT):- !, arg(1,NewUDT,Arg1),nb_setarg(1,UDT,Arg1),arg(2,NewUDT,Arg2),nb_setarg(2,UDT,Arg2). nb_copy(A,NewMap,Map):- arg(A,NewMap,E),nb_setarg(A,NewMap,E), (A==1-> true ; Am1 is A-1, (b_copy(Am1,NewMap,Map))). %get_kv(KV,K,V):-compound(KV),(KV=..[_,K,V]->true;KV=..[K,V]). %% get_kv( ?KV, ?X, ?Y) is semidet. % % Get Kv. % get_kv(X=Y,X,Y):- !. get_kv(X-Y,X,Y):- !. get_kv(KV,X,Y):- functor(KV,_,1),KV=..[X,Y],!. get_kv(KV,X,Y):- arg(1,KV,X),arg(2,KV,Y),!. % @TODO WRONG?! set_kv(KV,K,V):- b_put_kv(KV,K,V). nb_set_kv(KV,K,V):- nb_put_kv(KV,K,V). b_put_kv(KV,_,V):- functor(KV,_,A),setarg(A,KV,V). nb_put_kv(KV,_,V):- functor(KV,_,A),nb_setarg(A,KV,V). % oo_get_attr(V,A,Value):- trace_or_throw(oo_get_attr(V,A,Value)). oo_put_dict5(M,Key,UDT,Value, NewUDT):- is_dict(UDT),!,M:put_dict(Key,UDT,Value, NewUDT). oo_put_dict5(M,Key,UDT,Value, NewUDT):- oo_copy_term(UDT,NewUDT),oo_put_dict(M,Key,NewUDT,Value). oo_copy_term(UDT,NewUDT):- copy_term(UDT,NewUDT). oo_put_dict( M,Key,UDT,Value):- var(UDT),!,(attvar(UDT)-> M:put_attr(UDT,Key,Value);do_but_warn(put_attr(UDT,Key,Value))). oo_put_dict( M,Key,UDT,Value):- \+ compound(UDT),!,oo_derefed(M,UDT,DREF),!,oo_put_dict(M,DREF,Key,Value). oo_put_dict(_M,Key,UDT,Value):- compound_name_arity(UDT,att,3),nb_setattr(UDT,Key,Value). oo_put_dict( M,Key,UDT,Value):- is_dict(UDT),!,M:m_put_dict(Key,UDT,Value). oo_put_dict(_M,Key,UDT,Value):- is_rbtree(UDT),!,rb_insert(UDT,Key,Value,NewUDT),arg(1,NewUDT,Arg1),setarg(1,UDT,Arg1),arg(2,NewUDT,Arg2),setarg(2,UDT,Arg2). oo_put_dict(_M,Key,UDT,Value):- is_assoc(UDT),!,put_assoc(Key,UDT,Value,NewUDT),b_copy(NewUDT,UDT). oo_put_dict(_M,Key,UDT,Value):- is_list(UDT),!,((member(KV,UDT),get_kv(KV,K,_),Key==K,set_kv(KV,K,Value))->true;(b_copy([Key-Value|UDT],UDT))). % todo index these by sending in the UDT on two args oo_put_dict(_M,Key,UDT,Value):- UDT=..[U,D|T], oo_b_set_varholder(U,D,T,UDT,Key,Value). oo_put_dict( M,Key,REF,Value):- oo_derefed(M,REF,DREF),!,oo_put_dict(M,DREF,Key,Value). oo_put_dict( M,Key,UDT,Value):- M:oo_set(UDT,Key,Value),!. oo_put_dict( M,Key,UDT,Value):- trace_or_throw(oo_put_dict(M,Key,UDT,Value)). oo_get(UDT,Key,Value):- oo_get_dict(Key,UDT,Value). oo_get_dict(Key,UDT,Value):- strip_module(UDT,M,Self), oo_get_dict(M,Key,Self, Value). oo_get_dict(M,Key,Self, Value):- oo_call(M,Self,Key,Value). m_put_dict(Key,Map,Value):- ((get_dict(Key,Map,_),b_set_dict(Key,Map,Value))->true; (oo_put_extender(Map,Ext),oo_put_attr(Ext,Key,Value))). oo_jpl_call(A,B,C):- (integer(B);B==length; B= (_-_)),!,fail_on_missing(jpl_get(A,B,C)). oo_jpl_call(A,B,C):- (compound(B)->compound_name_arguments(B,H,L);(H=B,L=[])),fail_on_missing(jpl_call(A,H,L,C)),!. oo_jpl_call(A,B,C):- catch(fail_on_missing(jpl_get(A,B,C)),E,(debug(dictoo(_),'~N~w,~n',[E:jpl_get(A,B,C)]),fail)). to_atomic_name(DMemb,Memb):- compound(DMemb),!,compound_name_arity(DMemb,Memb,0). to_atomic_name(Memb,Memb):- var(Memb),!. to_atomic_name(SMemb,Memb):- string_to_atom(SMemb,Memb). member_func_unify(X,Y):- to_atomic_name(X,X1),to_atomic_name(Y,Y1),X1=Y1. %% is_oo_invokable(+Self,-DeRef) is det. % % DeRef''s an OO Whatnot and ckecks if invokable % is_oo_invokable(Was,Was):- is_oo(Was),!. % is_oo_invokable(Was,Was):- M:nb_current('$oo_stack',[Was|_]) is_oo_invokable(Was,Ref):- strip_module(Was,M,Self),oo_deref(M,Self,Ref),!,((Self\==Ref,M:Self\==Ref,Self\==M:Ref);is_oo(M,Ref)). :- module_transparent(oo_call/4). :- module_transparent(oo_call_dot_hook/4). :- thread_initialization(nb_setval('$oo_stack',[])). oo_call_dot_hook(M,Self, Func, Value):- is_dict(Self), M:dot_dict(Self, Func, Value),!. oo_call_dot_hook(M,A,B,C):- (M:nb_current('$oo_stack',Was)->true;Was=[]),b_setval('$oo_stack',['.'(A,B,C)|Was]),oo_call(M,A,B,C). oo_call(M,DVAR, Memb,Value):- dvar_name(M,DVAR,_,NameSpace), dot_cfg:dictoo_decl(= ,_SM,_CM,From,DVAR,DMemb,Value,Call),member_func_unify(DMemb,Memb),!, sanity(ground(NameSpace)), show_call(dictoo(core), From:Call). %oo_call(M,DVAR,Memb,Value):- Memb==value, dvar_name(M,DVAR,_,GVar), atom(GVar), var(Value),M:nb_current_value(GVar,Value),!. %oo_call(M,DVAR,Memb,Value):- Memb==value, dvar_name(M,DVAR,_,GVar), atom(GVar),!,must( M:nb_link_value(GVar,Value)),!, on_bind(Value,gvar_put(M, GVar, Value)),!. oo_call(_M,Self,Memb,Value):- notrace((atom(Memb),attvar(Self))),get_attr(Self, Memb, Value),!. oo_call(M,Self,Memb,Value):- var(Self),atom(Memb),!, % trace, on_bind(Self,oo_call(M,Self,Memb,Value)). oo_call(M,Self,Memb,Value):- var(Self),!, % trace, on_bind(Self,oo_call(M,Self,Memb,Value)). oo_call(_M,'$VAR'(Name),N,V):- atom(Name),!,N=vn,V=Name. oo_call(_M,'$VAR'(Att3),A,Value):- !, put_attrs(NewVar,Att3),get_attr(NewVar,A,Value). oo_call(_M,'aVar'(Att3),A,Value):- !, put_attrs(NewVar,Att3),get_attr(NewVar,A,Value). oo_call(_M,'aVar'(_,Att3),A,Value):- !, put_attrs(NewVar,Att3),get_attr(NewVar,A,Value). oo_call(M,Map,Key,Value):-is_dict(Map),!,(get_dict(Key,Map,Value)->true;(oo_get_extender(Map,Ext),oo_call(M,Ext,Key,Value))). oo_call(M,Map,Key,Value):-is_rbtree(Map),!,(rb_in(Key,Value,Map)->true;(oo_get_extender(Map,Ext),oo_call(M,Ext,Key,Value))). oo_call(M,Map,Key,Value):-is_assoc(Map),!,(get_assoc(Key,Value,Map)->true;(oo_get_extender(Map,Ext),oo_call(M,Ext,Key,Value))). oo_call(M,Map,Key,Value):-is_list(Map),!,((member(KV,Map),get_kv(KV,K,V),Key==K,V=Value)->true;(oo_get_extender(Map,Ext),oo_call(M,Ext,Key,Value))). oo_call(_M,Self,Memb,Value):- strip_module(Memb,M,Prop),Memb\==Prop,catch(oo_call(M,Self,Prop,Value),_E,fail). oo_call(M,'$was_dictoo'(CM,Self),Memb,Value):- var(Self),new_oo(M,Self,NewSelf),!,M:oo_call(CM,NewSelf,Memb,Value). oo_call(M,DVAR,add(Memb,V),'$was_dictoo'(M,DVAR)):- dvar_name(M,DVAR,_,GVar), notrace((atom(GVar),M:nb_current_value(GVar,Self))), is_dict(Self),!, M:m_put_dict(Memb,Self,V,NewSelf), M:nb_set_value(GVar,NewSelf). oo_call(M,DVAR,Memb,Value):- dvar_name(M,DVAR,_,GVar), atom(GVar), gvar_call(M, GVar, Memb, Value),!. oo_call(M,DVAR,Memb,Value):- dvar_name(M,DVAR,_,GVar), is_gvar(M,GVar,_Name),gvar_call(M,GVar,Memb,Value),!. oo_call(M,'&'(Self,_),Memb,Value):- gvar_call(M,Self,Memb,Value),!. oo_call(M,'&'(_,Self),Memb,Value):- oo_call(M,Self,Memb,Value),!. oo_call(M,Self,set(Memb,Value),'&'(Self)):- is_dict(Self),!,M:nb_set_dict(Memb,Self,Value). oo_call(M,Self,Memb,Value):- notrace(is_dict(Self)),!, M:dot_dict(Self, Memb, Value). oo_call(M,'&'(Self),Memb,Value):- !,oo_call(M,Self,Memb,Value). oo_call(M,jpl(Self),Memb,Value):- !, M:oo_jpl_call(Self, Memb, Value). oo_call(M,jclass(Self),Memb,Value):- !, M:oo_jpl_call(Self, Memb, Value). oo_call(M,class(Self),Memb,Value):- M:fail_on_missing(cli_call(Self, Memb, Value)),!. oo_call(M,DVAR,Memb,Value):- dvar_name(M,DVAR,_,GVar), atom(GVar), (M:nb_current_value(GVar,Self)),oo_call(M,Self,Memb,Value), M:nb_set_value(GVar,Self). oo_call(M,Self,Memb,Value):- fail_on_missing(jpl_is_ref(Self)),!,M:oo_jpl_call(Self, Memb, Value). oo_call(M,Self,Memb,Value):- notrace(fail_on_missing(cli_is_object(Self))),!,fail_on_missing(M:cli_call(Self, Memb, Value)). oo_call(M,Self,Memb,Value):- notrace(fail_on_missing(cli_is_struct(Self))),!,fail_on_missing(M:cli_call(Self, Memb, Value)). oo_call(M,Class,Inner,Value):- show_success(is_oo_class(inner(Class,Inner))),!,oo_call(M,inner(Class,Inner),Value,_). oo_call(M,'&'(_,DeRef),Memb,Value):- oo_call(M,DeRef,Memb,Value). %oo_call(M,Self,deref,Value):- var(Self),nonvar(Value),!,oo_call(M,Value,deref,Self). %oo_call(M,Self,deref,Self):-!. % oo_call(M,Self,Memb,Value):- nonvar(Value),trace_or_throw(oo_call(M,Self,Memb,Value)). oo_call(M,Self,Memb,Value):- oo_derefed(M,Self,NewSelf),!,oo_call(M,NewSelf,Memb,Value). % oo_call(M,Self,Memb,Value):- gvar_interp(M,Self,Self,Memb,Value). oo_call(M,DVAR,Memb,Value):- dvar_name(M,DVAR,_,NameSpace), nonvar(NameSpace), dot_cfg:dictoo_decl(= ,_SM,_CM,From,DVAR,Unk,Value,Call),!, throw(M:dot_cfg=dictoo_decl(= ,From,NameSpace,Memb-->Unk,Value,Call)),fail. oo_call(_,M:Self,Memb,Value):- !,oo_call(M,Self,Memb,Value). oo_call(_,_Self,_Memb,_Value):- !,fail. oo_call(_,Self,Memb,Value):- Value =.. ['.', Self,Memb],!. oo_call(M,Self,Memb,Value):- throw(oo_call(M,Self,Memb,Value)). oo_call(M,Self,Memb,Value):- var(Value),!,on_bind(Value, oo_put_dict(M,Memb,Self, Value)). oo_call(M,Self,Memb,Value):- var(Memb),!,on_bind(Memb, oo_put_dict(M,Memb,Self, Value)). oo_call(_,Self,Memb,Value):- var(Value),!,Value='&'(Self,Memb). oo_call(M,Self,Memb,Value):- throw(oo_call(M,Self,Memb,Value)). /* oo_call(M,Self,Memb,Value):- nb_link_value(Self,construct(Self,Memb,Value)),!,oo_call(M,Self,Memb,Value). oo_call(M,Self,Memb,Value):- to_member_path(Memb,[F|Path]),append(Path,[Value],PathWValue), Call =.. [F,Self|PathWValue], oo_call(M,Call). to_member_path(C,[F|ARGS]):-compound(C),!,compound_name_args(C,F,ARGS). to_member_path(C,[C]). */ bb_key(Module:Key, Atom) :- atom(Module), !, atomic(Key), atomic_list_concat([Module, Key], :, Atom). bb_key(Key, Atom) :- atomic(Key), prolog_load_context(module, Module), atomic_list_concat([Module, Key], :, Atom). oo_derefed(MObj,RObj):- strip_module(MObj,M,Obj),oo_derefed(M,Obj,RObj). oo_derefed( M,Obj,RObj):- oo_deref(M,Obj,RObj),!,RObj\==Obj. oo_derefed(_M,Obj,RObj):- atom(Obj),!,oo_new(_,RObj),nb_setval(Obj,RObj). oo_deref(M,Obj,RObj):- var(Obj),!,M:once(get_attr(Obj,oo,binding(_,RObj));Obj=RObj),!. oo_deref(_,Value,Value):- \+ compound(Value),!. % oo_deref(M,'$'(GVar),'&'(GVar,Value)):- atom(GVar),M:nb_current_value(GVar,Value),!. %oo_deref(M,'$'(GVar),'&'(GVar,Value)):- atom(GVar),(M:nb_current_value(GVar,Value)->true;(Value=[],M:nb_setvar(GVar,Value))). oo_deref(M,DVAR,Value):- dvar_name(M,DVAR,_,GVar), atom(GVar),notrace((M:nb_current_value(GVar,ValueM))),!,oo_deref(M,ValueM,Value). oo_deref(M,inline_cl_eval(Call),Result):-is_list(Call),!,M:fail_on_missing(cl_eval(Call,Result)). oo_deref(M,inline_cl_eval(Call),Result):-!,nonvar(Call),oo_deref(M,Call,CallE),!,M:call(CallE,Result). %oo_deref(M,Value,Value):- M:fail_on_missing(jpl_is_ref(Value)),!. % %oo_deref(M,[A|B],Result):-!, maplist(oo_deref(M),[A|B],Result). % %oo_deref(M,Call,Result):- call(Call,Result),!. %oo_deref(_,Value,Value):- is_logtalk_object(Value). %oo_deref(M,Head,HeadE):- Head=..B,maplist(oo_deref(M),B,A),HeadE=..A,!. oo_deref(_,Value,Value). oo_get_dict(M,Key,Dict, Value, NewDict, NewDict) :- is_dict(Dict),!, M:get_dict(Key,Dict, Value, NewDict, NewDict). oo_get_dict(M,Key,Dict, Value, NewDict, NewDict) :- oo_get_dict(M,Key,Dict, Value), oo_put_dict5(M,Key,Dict, NewDict, NewDict). %! eval_oo_function(M,+Func, +Tag, +UDT,-Value) % % Test for predefined functions on Objects or evaluate a user-defined % function. eval_oo_function(_M,Func, Tag, UDT,Value) :- is_dict(UDT),!, '$dicts':eval_dict_function(Func, Tag, UDT,Value). eval_oo_function(M,get(Key), _, UDT,Value) :- !, oo_get_dict(M,Key,UDT,Value). eval_oo_function(M,put(Key,Value), _, UDT,NewUDT) :- !, ( atomic(Key) -> oo_put_dict5(M,Key,UDT,Value, NewUDT) ; put_oo_path(M,Key,UDT,Value, NewUDT) ). eval_oo_function(M,put(New), _Tag, UDT,NewUDT) :- !, % put_dict(New, Dict, NewDict). oo_put_dict(M,New, UDT,NewUDT). eval_oo_function(M,Func, Tag, UDT,Value) :- M:call(Tag:Func, UDT,Value). %! put_oo_path(M,+KeyPath, +UDT,+Value, -NewUDT) % % Add/replace a value according to a path definition. Path % segments are separated using '/'. put_oo_path(M,Key,UDT,Value, NewUDT) :- atom(Key), !, oo_put_dict5(M,Key,UDT,Value, NewUDT). put_oo_path(M,Path, UDT,Value, NewUDT) :- get_oo_path(M,Path, UDT,_Old, NewUDT,Value). get_oo_path(_M,Path, _, _, _, _) :- var(Path), !, '$instantiation_error'(Path). get_oo_path(M,Path/Key,UDT,Old, NewUDT,New) :- !, get_oo_path(M,Path, UDT,OldD, NewUDT,NewD), ( oo_get_dict(M,Key,OldD, Old, NewD, New), is_oo(M,Old) -> true ; Old = _{}, oo_put_dict5(M,Key,OldD, New, NewD) ). get_oo_path(M,Key,UDT,Old, NewUDT,New) :- oo_get_dict(M,Key,UDT,Old, NewUDT,New), is_oo(M,Old), !. get_oo_path(M,Key,UDT,_{}, NewUDT,New) :- oo_put_dict5(M,Key,UDT,New, NewUDT). :- dynamic(is_oo_class/1). :- dynamic(is_oo_class_field/2). :- multifile(dot_cfg:dictoo_decl/8). :- dynamic(dot_cfg:dictoo_decl/8). :- discontiguous(dot_cfg:dictoo_decl/8). % is_oo_hooked(M,Self,_Func,_Value):- M:is_oo(M,Self),!. is_oo_hooked(M,Self,_Func,_Value):- M:is_oo_invokable(Self,_),!. % $current_file.value = X :- prolog_load_context(file,X). % dot_cfg:dictoo_decl(= ,mpred_gvars,current_file,value,A,prolog_load_context(file, A)). is_oo_hooked(M, IVar, Memb, Value):- compound(IVar), IVar = ($(Var)), dot_cfg:dictoo_decl(= ,_SM,_CM,M,Var, Memb, Value,_Body). % is_oo_hooked(M, IVar, value, Ref):- atom(IVar),IVar=Var,dot_cfg:dictoo_decl(= ,SM,CM,M,IVar,value,_Value,_Body),!,must(Ref=IVar). %is_oo_hooked(M,Var,_,Ref):- dot_cfg:dictoo_decl(= ,SM,CM,M,Var,value,_Value,_Body),Ref=Var. oo_class_begin(Name):-asserta(is_oo_class(Name)). oo_class_end(Name):- is_oo_class(Name),!,retract(is_oo_class(Name)),assertz(is_oo_class(Name)). oo_inner_class(Name,Inner):-asserta(is_oo_class(inner(Name,Inner))). oo_inner_class_begin(Inner):- is_oo_class(Name),!,oo_class_begin(inner(Name,Inner)). oo_inner_class_end(Inner):- is_oo_class(inner(Name,Inner)),!,oo_class_end(inner(Name,Inner)). oo_class_field(Inner):- is_oo_class(Name),!,asserta(is_oo_class_field(Name,Inner)). :- multifile(gvs:dot_overload_hook/4). :- dynamic(gvs:dot_overload_hook/4). :- module_transparent(gvs:dot_overload_hook/4). gvs:dot_overload_hook(M,NewName, Memb, Value):- dot_cfg:using_dot_type(_,M) -> show_call(dictoo(overload),oo_call_dot_hook(M,NewName, Memb, Value)). :- multifile(gvs:is_dot_hook/4). :- dynamic(gvs:is_dot_hook/4). :- module_transparent(gvs:is_dot_hook/4). gvs:is_dot_hook(M,Self,Func,Value):- dot_cfg:using_dot_type(_,M) -> is_oo_hooked(M,Self,Func,Value),!. :- gvar_file_predicates_are_exported, gvar_file_predicates_are_transparent.
TeamSPoon/logicmoo_workspace
packs_sys/dictoo/prolog/dictoo_lib.pl
Perl
mit
21,002
#!/usr/bin/perl -w # use Data::Dumper; # use constant TRUE => 1; use constant FALSE => 0; # use constant SUCCESS => 1; use constant FAIL => 0; # sub read_file { my ($inf_file, $praw_data) = @_; # printf "%d: Reading file: %s\n", __LINE__, $inf_file; # if ( ! -r $inf_file ) { printf "%d: ERROR: file $inf_file is NOT readable\n\n", __LINE__; return FAIL; } # unless (open(INFD, $inf_file)) { printf "%d: ERROR: unable to open $inf_file.\n\n", __LINE__; return FAIL; } @{$praw_data} = <INFD>; close(INFD); # # remove any CR-NL sequences from Windose. # chomp(@{$praw_data}); s/\r//g for @{$praw_data}; # printf "%d: Lines read: %d\n", __LINE__, scalar(@{$praw_data}); # return SUCCESS; } # sub accept_token { my ($ptokens, $pidx, $lnno) = @_; # $$pidx += 1; } # sub is_end_tag { my ($start_tag, $token) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); # $proot = $proot->[-1]->{SIBLINGS}; } else { element_xml($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if (is_end_tag($tag_name, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); } else { printf "%d: MISSING END TAG : <%s,%s>\n", __LINE__, $tag_name, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } elsif ($token =~ m/^<\/[^>]+>$/) { if (is_end_tag($first_start_tag, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { printf "%d: UNEXPECTED END TAG : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } else { printf "%d: UNEXPECTED TOKEN : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } } # sub start_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { accept_token($ptokens, $pidx, __LINE__); element_xml($ptokens, $pidx, $maxtoken, $proot); } else { printf "%d: NOT XML 1.0 DOC: <%s>\n", __LINE__, $token; } # return($proot); } # sub parse_xml { my ($xml_rec) = @_; # printf "%d: Parse XML (1): %s\n", __LINE__, $xml_rec; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; start_xml(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } # sub element_xml2 { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; my $first_start_tag_seen = 0; my $first_start_tag_proot = undef; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; $first_start_tag_seen += 1; $first_start_tag_proot = $proot; # $$proot->{$token} = undef; $proot = \$$proot->{$token}; accept_token($ptokens, $pidx, __LINE__); } else { $$proot->{$token} = undef; element_xml2($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; $$proot->{$tag_name} = $tag_value; accept_token($ptokens, $pidx, __LINE__); # $token = $ptokens->[$$pidx]; if (is_end_tag($tag_name, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); } else { printf "%d: MISSING END TAG : <%s,%s>\n", __LINE__, $tag_name, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } elsif ($token =~ m/^<\/[^>]+>$/) { if (is_end_tag($first_start_tag, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { printf "%d: UNEXPECTED END TAG : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } else { printf "%d: UNEXPECTED TOKEN : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } } } # sub start_xml2 { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { accept_token($ptokens, $pidx, __LINE__); element_xml2($ptokens, $pidx, $maxtoken, $proot); } else { printf "%d: NOT XML 1.0 DOC: <%s>\n", __LINE__, $token; } # return($proot); } # sub parse_xml2 { my ($xml_rec) = @_; # printf "%d: Parse XML (2): %s\n", __LINE__, $xml_rec; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); # my $proot = undef; start_xml2(\@tokens, \$idx, scalar(@tokens), \$proot); # return($proot); } # sub to_xml2 { my ($ptree, $pxml, $last_element) = @_; # my $ref_type = ref($ptree); # my $last_element_end_tag = $last_element; $last_element_end_tag =~ s?^<?</?; # if ($ref_type eq "ARRAY") { my $imax = scalar(@{$ptree}); # for (my $i=0; $i<$imax; ++$i) { $$pxml .= "$last_element" if ($i > 0); to_xml2($ptree->[$i], $pxml, $last_element); $$pxml .= "$last_element_end_tag" if ($i < ($imax-1)); } } elsif ($ref_type eq "HASH") { foreach my $element ( sort keys %{$ptree} ) { my $element_end_tag = $element; $element_end_tag =~ s?^<?</?; # $$pxml .= "$element"; to_xml2($ptree->{$element}, $pxml, $element); $$pxml .= "$element_end_tag"; } } else { $$pxml .= "$ptree" if (defined($ptree)); } } # sub msg_to_xml2 { my ($ptree) = @_; # my $xml = '<?xml version="1.0" encoding="UTF-8"?>'; my $last_element = ""; to_xml2($ptree, \$xml, $last_element); # return $xml; } # foreach my $inf_file (@ARGV) { my @raw_data = (); # read_file($inf_file, \@raw_data); # foreach my $xml_rec (@raw_data) { my $proot = parse_xml($xml_rec); printf "\n%d: DUMPER root msg (1) = %s\n", __LINE__, Dumper($proot); # my $proot2 = parse_xml2($xml_rec); printf "\n%d: DUMPER root Original msg (2) = %s\n", __LINE__, Dumper($proot2); # my $msg2 = msg_to_xml2($proot2); printf "%d: Original = %s\n", __LINE__, $xml_rec; printf "%d: Deparsed = %s\n", __LINE__, $msg2; } } # exit(0); __DATA__ # ###################################################################### # # process an INF file and store the data in XML files. # ###################################################################### # use strict; # use Carp; use Getopt::Std; use File::Find; use File::Path qw(mkpath); use File::Basename; use File::Path 'rmtree'; # ###################################################################### # # logical constants # use constant TRUE => 1; use constant FALSE => 0; # use constant SUCCESS => 1; use constant FAIL => 0; # # required section names # use constant INDEX => '[Index]'; use constant INFORMATION => '[Information]'; # # verbose levels # use constant NOVERBOSE => 0; use constant MINVERBOSE => 1; use constant MIDVERBOSE => 2; use constant MAXVERBOSE => 3; # # section types # use constant SECTION_UNKNOWN => 0; use constant SECTION_NAME_VALUE => 1; use constant SECTION_LIST => 2; # # filename to id constants # use constant MAX_RECORDS_BEFORE_WRITE => 100; # ###################################################################### # # globals # my $cmd = $0; my $log_fh = *STDOUT; # # cmd line options # my $logfile = ''; my $verbose = NOVERBOSE; my $rmv_xml_dir = FALSE; my $use_same_path = FALSE; # my $xml_base_path = "/tmp"; my $xml_rel_path = "XML"; my $xml_path = $xml_base_path . '/' . $xml_rel_path; # my %verbose_levels = ( off => NOVERBOSE(), min => MINVERBOSE(), mid => MIDVERBOSE(), max => MAXVERBOSE() ); # ###################################################################### # # miscellaneous functions # sub usage { my ($arg0) = @_; print $log_fh <<EOF; usage: $arg0 [-?] [-h] \\ [-w | -W |-v level] \\ [-l logfile] \\ [-B base path] \\ [-R relative path] \\ [-P path] \\ [-S] \\ [-r] \\ INF-file ... where: -? or -h - print this usage. -w - enable warning (level=min=1) -W - enable warning and trace (level=mid=2) -v - verbose level: 0=off,1=min,2=mid,3=max -l logfile - log file path -B path - base xml path, defaults to '${xml_base_path}' -R path - relative xml path, defaults to '${xml_rel_path}' -P path - xml path, defaults to '${xml_path}' -S - use same path as original file, but prefix XML_ to the file name. -r - remove old XML directory (off by default). EOF } # ###################################################################### # # load name-value or list section # sub load_name_value { my ($praw_data, $section, $pirec, $max_rec, $pinf_db) = @_; # $pinf_db->{found_data}->{$section} = FALSE; $pinf_db->{section_type}->{$section} = SECTION_NAME_VALUE; # $$pirec += 1; # skip section name # my @section_data = (); for ( ; $$pirec < $max_rec; ) { my $record = $praw_data->[$$pirec]; # if ($record =~ m/^\s*$/) { $$pirec += 1; last; } elsif ($record =~ m/^\[[^\]]*\]/) { # section is corrupted. it lacks the required empty # line to indicate the end of the section. last; } push @section_data, $record; $$pirec += 1; } # printf $log_fh "%d: <%s>\n", __LINE__, join("\n", @section_data) if ($verbose >= MAXVERBOSE); # if (scalar(@section_data) <= 0) { $pinf_db->{$section} = {}; printf $log_fh "%d: NO NAME-VALUE DATA FOUND IN SECTION %s. Lines read: %d\n", __LINE__, $section, scalar(@section_data); return FAIL; } # %{$pinf_db->{$section}->{data}} = map { split /\s*=\s*/, $_, 2 } @section_data; # # remove any double quotes. for my $key (keys %{$pinf_db->{$section}->{data}}) { $pinf_db->{$section}->{data}->{$key} =~ s/^\s*"([^"]*)"\s*$/$1/; } # $pinf_db->{found_data}->{$section} = TRUE; # printf $log_fh "%d: Number of key-value pairs: %d\n", __LINE__, scalar(keys %{$pinf_db->{$section}->{data}}) if ($verbose >= MINVERBOSE); printf $log_fh "%d: Lines read: %d\n", __LINE__, scalar(@section_data) if ($verbose >= MINVERBOSE); # return SUCCESS; } # sub split_quoted_string { my $rec = shift; my $separator = shift; # my $rec_len = length($rec); # my $istart = -1; my $iend = -1; my $in_string = 0; # my @tokens = (); my $token = ""; # for (my $i=0; $i<$rec_len; $i++) { my $c = substr($rec, $i, 1); # if ($in_string == 1) { if ($c eq '"') { $in_string = 0; } else { $token .= $c; } } elsif ($c eq '"') { $in_string = 1; } elsif ($c eq $separator) { # printf $log_fh "Token ... <%s>\n", $token; push (@tokens, $token); $token = ''; } else { $token .= $c; } } # if (length($token) > 0) { # printf $log_fh "Token ... <%s>\n", $token; push (@tokens, $token); $token = ''; } else { # null-length string $token = ''; push (@tokens, $token); } # # printf $log_fh "Tokens: \n%s\n", join("\n",@tokens); # return @tokens; } # sub load_list { my ($praw_data, $section, $pirec, $max_rec, $pinf_db) = @_; # $pinf_db->{found_data}->{$section} = FALSE; $pinf_db->{section_type}->{$section} = SECTION_LIST; # $$pirec += 1; # skip section name # my @section_data = (); for ( ; $$pirec < $max_rec; ) { my $record = $praw_data->[$$pirec]; # if ($record =~ m/^\s*$/) { $$pirec += 1; last; } elsif ($record =~ m/^\[[^\]]*\]/) { # section is corrupted. it lacks the required empty # line to indicate the end of the section. last; } push @section_data, $record; $$pirec += 1; } # printf $log_fh "%d: <%s>\n", __LINE__, join("\n", @section_data) if ($verbose >= MAXVERBOSE); # if (scalar(@section_data) <= 0) { $pinf_db->{$section} = {}; printf $log_fh "%d: NO LIST DATA FOUND IN SECTION %s. Lines read: %d\n", __LINE__, $section, scalar(@section_data) if ($verbose >= MINVERBOSE); return SUCCESS; } # $pinf_db->{$section}->{header} = shift @section_data; @{$pinf_db->{$section}->{column_names}} = split / /, $pinf_db->{$section}->{header}; my $number_columns = scalar(@{$pinf_db->{$section}->{column_names}}); # @{$pinf_db->{$section}->{data}} = (); # printf $log_fh "%d: Number of Columns: %d\n", __LINE__, $number_columns if ($verbose >= MINVERBOSE); # foreach my $record (@section_data) { # # sanity check since MAI or CRB file may be corrupted. # last if (($record =~ m/^\[[^\]]*\]/) || ($record =~ m/^\s*$/)); # my @tokens = split_quoted_string($record, ' '); my $number_tokens = scalar(@tokens); # printf $log_fh "%d: Number of tokens in record: %d\n", __LINE__, $number_tokens if ($verbose >= MAXVERBOSE); # if ($number_tokens == $number_columns) { my %data = (); @data{@{$pinf_db->{$section}->{column_names}}} = @tokens; # unshift @{$pinf_db->{$section}->{data}}, \%data; printf $log_fh "%d: Current Number of Records: %d\n", __LINE__, scalar(@{$pinf_db->{$section}->{data}}) if ($verbose >= MAXVERBOSE); } else { printf $log_fh "%d: ERROR: Section: %s, SKIPPING RECORD - NUMBER TOKENS (%d) != NUMBER COLUMNS (%d)\n", __LINE__, $section, $number_tokens, $number_columns; } } # $pinf_db->{found_data}->{$section} = TRUE; # return SUCCESS; } # ###################################################################### # # load and process product files # sub read_file { my ($inf_file, $praw_data) = @_; # printf $log_fh "%d: Reading Product file: %s\n", __LINE__, $inf_file; # if ( ! -r $inf_file ) { printf $log_fh "%d: ERROR: file $inf_file is NOT readable\n\n", __LINE__; return FAIL; } # unless (open(INFD, $inf_file)) { printf $log_fh "%d: ERROR: unable to open $inf_file.\n\n", __LINE__; return FAIL; } @{$praw_data} = <INFD>; close(INFD); # # remove any CR-NL sequences from Windose. chomp(@{$praw_data}); s/\r//g for @{$praw_data}; # printf $log_fh "%d: Lines read: %d\n", __LINE__, scalar(@{$praw_data}) if ($verbose >= MINVERBOSE); # return SUCCESS; } # sub process_data { my ($inf_file, $praw_data, $pinf_db) = @_; # printf $log_fh "%d: Processing product data: %s\n", __LINE__, $inf_file; # my $max_rec = scalar(@{$praw_data}); my $sec_no = 0; # for (my $irec=0; $irec<$max_rec; ) { my $rec = $praw_data->[$irec]; # # remove non-ascii garbage characters. the first line contains junk. # $rec =~ s/[^[:ascii:]]//g; # printf $log_fh "%d: Record %04d: <%s>\n", __LINE__, $irec, $rec if ($verbose >= MINVERBOSE); # if ($rec =~ m/^(\[[^\]]*\])/) { my $section = ${1}; # printf $log_fh "%d: Section %03d: %s\n", __LINE__, ++$sec_no, $section; # if ($verbose >= MINVERBOSE); # $rec = $praw_data->[${irec}+1]; # if ($rec =~ m/^\s*$/) { $irec += 2; printf $log_fh "%d: Empty section - %s\n", __LINE__, $section; } elsif ($rec =~ m/.*=.*/) { load_name_value($praw_data, $section, \$irec, $max_rec, $pinf_db); } else { load_list($praw_data, $section, \$irec, $max_rec, $pinf_db); } } else { $irec += 1; } } # return SUCCESS; } # sub name_to_value { my ($pinf_db, $section, $key, $default_value) = @_; # my $value = $default_value; # if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { if (exists($pinf_db->{$section}->{data}->{$key})) { $value = $pinf_db->{$section}->{data}->{$key}; } } # return $value; } # sub export_to_xml { my ($inf_file, $pinf_db) = @_; # printf $log_fh "%d: Writing product data to XML: %s\n", __LINE__, $inf_file; # my $prod_name = basename($inf_file); # $prod_name =~ tr/a-z/A-Z/; # my $prod_xml_path = ''; if ($use_same_path == TRUE) { my $same_path = dirname($inf_file); $prod_xml_path = $same_path . '/XML_' . $prod_name; } else { $prod_xml_path = $xml_path . '/XML_' . $prod_name; } # printf $log_fh "%d: product %s XML file: %s\n", __LINE__, $prod_name, $prod_xml_path; # open(my $outfh, ">" , $prod_xml_path) || die $!; # printf $outfh '<?xml version="1.0" encoding="utf-8" ?>' . "\n"; # printf $outfh '<iLNB_UIF>' . "\n"; # printf $outfh '<ProductInfo Format="200">' . "\n"; # my $section = '[LotInformation]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { my $LotID = name_to_value($pinf_db, $section, 'Lot', ''); my $ModelID = name_to_value($pinf_db, $section, 'ModelID', ''); my $Side = name_to_value($pinf_db, $section, 'Side', '0'); my $ProductData = name_to_value($pinf_db, $section, 'ProductData', ''); my $Comment1 = name_to_value($pinf_db, $section, 'Comment1', ''); my $Comment2 = name_to_value($pinf_db, $section, 'Comment2', ''); my $Comment3 = name_to_value($pinf_db, $section, 'Comment3', ''); # printf $outfh '<LotInformation LotID="%s" ModelID="%s" Side="%s" ProductData="%s" Comment1="%s" Comment2="%s" Comment3="%s"/>' . "\n", $LotID, $ModelID, $Side, $ProductData, $Comment1, $Comment2, $Comment3; } # $section = '[Information]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { my $DataType = name_to_value($pinf_db, $section, 'Datatype', '0'); my $Code = name_to_value($pinf_db, $section, 'Code', '0'); my $ProductData = name_to_value($pinf_db, $section, 'ProductData', '0'); my $ActualTime = name_to_value($pinf_db, $section, 'ActualTime', '0'); my $BoardCount = name_to_value($pinf_db, $section, 'BoardCount', '0'); # printf $outfh '<Information DataType="%s" Code="%s" ProductData="%s" ActualTime="%s" BoardCount="%s"/>' . "\n", $DataType, $Code, $ProductData, $ActualTime, $BoardCount; } # $section = '[StopTime]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { my $StopTime = name_to_value($pinf_db, $section, 'StopTime', '0'); my $FWaitTime = name_to_value($pinf_db, $section, 'FWaitTime', '0'); my $RWaitTime = name_to_value($pinf_db, $section, 'RWaitTime', '0'); my $PWaitTime = name_to_value($pinf_db, $section, 'PWaitTime', '0'); my $ErrorStopTime = name_to_value($pinf_db, $section, 'ErrorStopTime', '0'); # printf $outfh '<StopTime StopTime="%s" FWaitTime="%s" RWaitTime="%s" PWaitTime="%s" ErrorStopTime="%s"/>' . "\n", $StopTime, $FWaitTime, $RWaitTime, $PWaitTime, $ErrorStopTime; } # $section = '[StopCount]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { my $StopCount = name_to_value($pinf_db, $section, 'StopCount', '0'); my $FWaitCount = name_to_value($pinf_db, $section, 'FWaitCount', '0'); my $RWaitCount = name_to_value($pinf_db, $section, 'RWaitCount', '0'); my $PWaitCount = name_to_value($pinf_db, $section, 'PWaitCount', '0'); my $ErrorStopCount = name_to_value($pinf_db, $section, 'ErrorStopCount', '0'); # printf $outfh '<StopCount StopCount="%s" FWaitCount="%s" RWaitCount="%s" PWaitCount="%s" ErrorStopCount="%s"/>' . "\n", $StopCount, $FWaitCount, $RWaitCount, $PWaitCount, $ErrorStopCount; } # $section = '[Inspection]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { my $OKCount = name_to_value($pinf_db, $section, 'OKCount', '0'); my $NGCount = name_to_value($pinf_db, $section, 'NGCount', '0'); my $PassCount = name_to_value($pinf_db, $section, 'PassCount', '0'); my $TakeOutCount = name_to_value($pinf_db, $section, 'TakeOutCount', '0'); # printf $outfh '<Inspection OKCount="%s" NGCount="%s" PassCount="%s" TakeOutCount="%s"/>' . "\n", $OKCount, $NGCount, $PassCount, $TakeOutCount; } # $section = '[EquipmentSpecific]'; if ((exists($pinf_db->{found_data}->{$section})) && ($pinf_db->{found_data}->{$section} == TRUE)) { printf $outfh '<EquipmentSpecific>' . "\n"; # foreach my $key (keys %{$pinf_db->{$section}->{data}}) { printf $outfh "%s=%s\n", $key, $pinf_db->{$section}->{data}->{$key}; } # printf $outfh '</EquipmentSpecific>' . "\n"; } # printf $outfh '</ProductInfo>' . "\n"; # printf $outfh '</iLNB_UIF>' . "\n"; # close($outfh); # return SUCCESS; } # sub process_file { my ($inf_file) = @_; # printf $log_fh "\n%d: Processing product File: %s\n", __LINE__, $inf_file; # my @raw_data = (); my %inf_db = (); # my $status = FAIL; if (read_file($inf_file, \@raw_data) != SUCCESS) { printf $log_fh "%d: ERROR: Reading product file: %s\n", __LINE__, $inf_file; } elsif (process_data($inf_file, \@raw_data, \%inf_db) != SUCCESS) { printf $log_fh "%d: ERROR: Processing product file: %s\n", __LINE__, $inf_file; } elsif (export_to_xml($inf_file, \%inf_db) != SUCCESS) { printf $log_fh "%d: ERROR: Exporting product file to XML: %s\n", __LINE__, $inf_file; } else { printf $log_fh "%d: Success processing product file: %s\n", __LINE__, $inf_file; $status = SUCCESS; } # return $status; } # ###################################################################### # # usage: $arg0 [-?] [-h] \\ # [-w | -W |-v level] \\ # [-l logfile] \\ # [-B base path] \\ # [-R relative path] \\ # [-P path] \\ # [-S] \\ # [-r] \\ # INF-file ... # my %opts; if (getopts('?hwWv:l:B:R:P:Sr', \%opts) != 1) { usage($cmd); exit 2; } # foreach my $opt (%opts) { if (($opt eq 'h') or ($opt eq '?')) { usage($cmd); exit 0; } elsif ($opt eq 'r') { $rmv_xml_dir = TRUE; } elsif ($opt eq 'S') { $use_same_path = TRUE; } elsif ($opt eq 'w') { $verbose = MINVERBOSE; } elsif ($opt eq 'W') { $verbose = MIDVERBOSE; } elsif ($opt eq 'v') { if ($opts{$opt} =~ m/^[0123]$/) { $verbose = $opts{$opt}; } elsif (exists($verbose_levels{$opts{$opt}})) { $verbose = $verbose_levels{$opts{$opt}}; } else { printf $log_fh "\n%d: ERROR: Invalid verbose level: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } } elsif ($opt eq 'l') { local *FH; $logfile = $opts{$opt}; open(FH, '>', $logfile) or die $!; $log_fh = *FH; printf $log_fh "\n%d: Log File: %s\n", __LINE__, $logfile; } elsif ($opt eq 'P') { $xml_path = $opts{$opt} . '/'; printf $log_fh "\n%d: XML path: %s\n", __LINE__, $xml_path; } elsif ($opt eq 'R') { $xml_rel_path = $opts{$opt} . '/'; $xml_path = $xml_base_path . '/' . $xml_rel_path; printf $log_fh "\n%d: XML relative path: %s\n", __LINE__, $xml_rel_path; } elsif ($opt eq 'B') { $xml_base_path = $opts{$opt} . '/'; $xml_path = $xml_base_path . '/' . $xml_rel_path; printf $log_fh "\n%d: XML base path: %s\n", __LINE__, $xml_base_path; } } # if ( -t STDIN ) { # # getting a list of files from command line. # if (scalar(@ARGV) == 0) { printf $log_fh "%d: ERROR: No product files given.\n", __LINE__; usage($cmd); exit 2; } # rmtree($xml_path) if ($rmv_xml_dir == TRUE); ( mkpath($xml_path) || die $! ) unless ( -d $xml_path ); # foreach my $inf_file (@ARGV) { process_file($inf_file); } # } else { printf $log_fh "%d: Reading STDIN for list of files ...\n", __LINE__; # rmtree($xml_path) if ($rmv_xml_dir == TRUE); ( mkpath($xml_path) || die $! ) unless ( -d $xml_path ); # while( defined(my $inf_file = <STDIN>) ) { chomp($inf_file); process_file($inf_file); } } # exit 0; # parsing LNB-style XML messages # package mylnbxml; # use myconstants; # sub new { my $class = shift; my $self = {}; # $self->{booklist} = undef; $self->{xml} = undef; $self->{deparse_xml} = undef; $self->{logger} = undef; $self->{errors} = 0; # # $self->{xml} = shift if @_; # $self->{logger} = shift if @_; # if (scalar(@_) == 1) { $self->{logger} = shift; } elsif (scalar(@_) == 2) { $self->{xml} = shift; $self->{logger} = shift; } # bless $self, $class; # return($self); } # sub xml { my $self = shift; # if (@_) { $self->{xml} = shift; $self->{booklist} = undef; $self->{deparse_xml} = undef; $self->{errors} = 0; } # return($self->{xml}); } # sub booklist { my $self = shift; # return($self->{booklist}); } # # sub errors { my $self = shift; # return($self->{errors}); } # sub accept_token { my $self = shift; my ($ptokens, $pidx, $lnno) = @_; # $$pidx += 1; } # sub is_end_tag { my $self = shift; my ($start_tag, $token) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token($ptokens, $pidx, __LINE__); # $proot = $proot->[-1]->{SIBLINGS}; } else { $self->element_xml($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if ($self->is_end_tag($tag_name, $token) == TRUE) { $self->accept_token($ptokens, $pidx, __LINE__); } else { $self->{errors} += 1; $self->{logger}->log_err("MISSING END TAG : <%s,%s>\n", $tag_name, $token); $self->accept_token($ptokens, $pidx, __LINE__); } } elsif ($token =~ m/^<\/[^>]+>$/) { if ($self->is_end_tag($first_start_tag, $token) == TRUE) { $self->accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED END TAG : <%s>\n", $token); } } else { $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED TOKEN : <%s>\n", $token); $self->accept_token($ptokens, $pidx, __LINE__); } } } # sub start_xml { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { $self->accept_token($ptokens, $pidx, __LINE__); $self->element_xml($ptokens, $pidx, $maxtoken, $proot); } else { $self->{errors} += 1; $self->{logger}->log_err("NOT XML 1.0 DOC: <%s>\n", $token); } # return($proot); } # sub parse_xml { my $self = shift; my ($xml_rec) = @_; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; # $self->start_xml(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } # sub parse { my $self = shift; # $self->{booklist} = undef; $self->{deparse_xml} = undef; # if (defined($self->{xml})) { $self->{errors} = 0; $self->{booklist} = $self->parse_xml($self->{xml}); if ($self->{errors} > 0) { $self->{logger}->log_err("Parse failed.\n"); $self->{booklist} = undef; } } # return($self->{booklist}); } # sub accept_token_2 { my $self = shift; my ($ptokens, $pidx, $lnno) = @_; # $$pidx += 1; } # sub is_end_tag_2 { my $self = shift; my ($start_tag, $token) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml_2 { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token_2($ptokens, $pidx, __LINE__); # $proot = $proot->[-1]->{SIBLINGS}; } else { $self->element_xml_2($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token_2($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if ($self->is_end_tag_2($tag_name, $token) == TRUE) { $self->accept_token_2($ptokens, $pidx, __LINE__); } else { $self->{errors} += 1; $self->{logger}->log_err("MISSING END TAG : <%s,%s>\n", $tag_name, $token); $self->accept_token_2($ptokens, $pidx, __LINE__); } } elsif ($token =~ m/^<\/[^>]+>$/) { if ($self->is_end_tag($first_start_tag, $token) == TRUE) { $self->accept_token_2($ptokens, $pidx, __LINE__); $done = TRUE; } else { $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED END TAG : <%s>\n", $token); } } else { $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED TOKEN : <%s>\n", $token); $self->accept_token_2($ptokens, $pidx, __LINE__); } } } # sub start_xml_2 { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { $self->accept_token_2($ptokens, $pidx, __LINE__); $self->element_xml_2($ptokens, $pidx, $maxtoken, $proot); } else { $self->{errors} += 1; $self->{logger}->log_err("NOT XML 1.0 DOC: <%s>\n", $token); } # return($proot); } # sub parse_xml_2 { my $self = shift; my ($xml_rec) = @_; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; # $self->start_xml_2(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } sub parse_2 { my $self = shift; # $self->{booklist} = undef; $self->{deparse_xml} = undef; # if (defined($self->{xml})) { $self->{errors} = 0; $self->{booklist} = $self->parse_xml_2($self->{xml}); if ($self->{errors} > 0) { $self->{logger}->log_err("Parse failed.\n"); $self->{booklist} = undef; } } # return($self->{booklist}); } # sub end_tag { my $self = shift; my ($start_tag) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # return($end_tag); } # sub deparse_start_xml { my $self = shift; my ($ptree, $pxstr) = @_; # if (ref($ptree) eq "ARRAY") { for (my $i=0; $i<scalar(@{$ptree}); ++$i) { my $name = $ptree->[$i]->{NAME}; # if (scalar(@{$ptree->[$i]->{SIBLINGS}}) > 0) { $$pxstr .= $name; $self->deparse_start_xml($ptree->[$i]->{SIBLINGS}, $pxstr); $$pxstr .= $self->end_tag($name); } elsif (defined($ptree->[$i]->{VALUE})) { my $value = $ptree->[$i]->{VALUE}; $$pxstr .= $name . $value . $self->end_tag($name); } else { my $value = $ptree->[$i]->{VALUE}; $$pxstr .= $name . $self->end_tag($name); } } } else { $self->{errors} += 1; $self->{logger}->log_err("EXPECTING ARRAY REF: <%s>\n", ref($ptree)); } } # sub deparse_xml { my $self = shift; my ($ptree) = @_; # my $xml_string = '<?xml version="1.0" encoding="UTF-8"?>'; $self->deparse_start_xml($ptree, \$xml_string); # return($xml_string); } # sub deparse { my $self = shift; # $self->{deparse_xml} = undef; # if (defined($self->{booklist})) { $self->{errors} = 0; $self->{deparse_xml} = $self->deparse_xml($self->{booklist}); if ($self->{errors} > 0) { $self->{logger}->log_err("Deparse failed.\n"); $self->{deparse_xml} = undef; } } # return($self->{deparse_xml}); } # sub to_xml { my $self = shift; my ($ptree, $pxml, $last_element) = @_; # my $ref_type = ref($ptree); # if ($ref_type eq "ARRAY") { my $imax = scalar(@{$ptree}); # for (my $i=0; $i<$imax; ++$i) { $$pxml .= "<$last_element>" if ($i > 0); $self->to_xml($ptree->[$i], $pxml, $last_element); $$pxml .= "</$last_element>" if ($i < ($imax-1)); } } elsif ($ref_type eq "HASH") { foreach my $element ( sort keys %{$ptree} ) { $$pxml .= "<$element>"; $self->to_xml($ptree->{$element}, $pxml, $element); $$pxml .= "</$element>"; } } else { $$pxml .= "$ptree"; } } # sub msg_to_xml { my $self = shift; my ($ptree) = @_; # my $xml = '<?xml version="1.0" encoding="UTF-8"?>'; my $last_element = ""; $self->to_xml($ptree, \$xml, $last_element); # $self->{xml} = $xml; $self->{booklist} = undef; $self->{deparse_xml} = undef; $self->{errors} = 0; # return $xml; } # # exit with success # 1; #!/usr/bin/perl -w # use strict; # my $binpath; # BEGIN { use File::Basename; # $binpath = dirname($0); $binpath = "." if ($binpath eq ""); } # use lib $binpath; # use myconstants; use mylogger; use mylnbxml; # my $plog = mylogger->new(); # my $plnbxml = mylnbxml->new($plog); # my $pmsg = { root => { Header => { SystemName => 'OTHERSYSTEM', SystemVersion => 1.00, SessionId => 58628, CommandName => 'ProgramDataSend' }, ProgramDataSend => { Element => [ { Date => '2017/03/23,00:00:45', MCNo => 1, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, { Date => '2017/03/23,00:00:45', MCNo => 2, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, ] }, }, }; # my $xml = $plnbxml->msg_to_xml($pmsg); printf "MSG-to-XML ... %s\n", $xml; # $plnbxml->parse(); my $xml2 = $plnbxml->deparse(); printf "MSG-to-XML-to-Internal-to-XML ... %s\n", $xml2; # if ($xml eq $xml2) { printf "XMls are the same !!!\n"; } else { printf "XMls are NOT the same !!!\n"; } # $xml = $plnbxml->msg_to_xml( { root => { Header => { SystemName => 'OTHERSYSTEM', SystemVersion => 1.00, SessionId => 58628, CommandName => 'ProgramDataSend' }, ProgramDataSend => { Element => [ { Date => '2017/03/23,00:00:45', MCNo => 1, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, { Date => '2017/03/23,00:00:45', MCNo => 2, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, ] }, }, }); printf "MSG-to-XML ... %s\n", $xml; # $plnbxml->parse(); $xml2 = $plnbxml->deparse(); printf "MSG-to-XML-to-Internal-to-XML ... %s\n", $xml2; # if ($xml eq $xml2) { printf "XMls are the same !!!\n"; } else { printf "XMls are NOT the same !!!\n"; } # exit 0; __DATA__ #!/usr/bin/perl -w # ################################################################ # # LNB simulator # ################################################################ # use strict; # ################################################################ # # read official and local mods # my $binpath; # BEGIN { use File::Basename; # $binpath = dirname($0); $binpath = "." if ($binpath eq ""); } # # perl mods # use Getopt::Std; use Socket; use FileHandle; use POSIX qw(:errno_h); # # my mods # use lib $binpath; # use myconstants; use mylogger; use mytimer; use mytimerpqueue; use mytaskdata; use mylnbxml; # ################################################################ # # local constants # use constant SOH => 1; use constant STX => 2; use constant ETX => 3; # ################################################################ # # globals # my $cmd = $0; my $default_cfg_file = "mylnb.cfg"; # my $plog = mylogger->new(); die "Unable to create logger: $!" unless (defined($plog)); # my $pq = mytimerpqueue->new(); die "Unable to create priority queue: $!" unless (defined($pq)); # my $pservices = mytaskdata->new(); die "Unable to create services data: $!" unless (defined($pservices)); # my $pfh_services = mytaskdata->new(); die "Unable to create file-handler-to-services data: $!" unless (defined($pfh_services)); # my $pfh_data = mytaskdata->new(); die "Unable to create task-specific data: $!" unless (defined($pfh_data)); # my $event_loop_done = FALSE; # my %service_params = ( name => { required => FALSE(), handler => FALSE(), }, service => { required => TRUE(), handler => FALSE(), }, host_name => { required => TRUE(), handler => FALSE(), }, io_handler => { required => TRUE(), handler => TRUE(), }, service_handler => { required => TRUE(), handler => TRUE(), }, timer_handler => { required => TRUE(), handler => TRUE(), }, client_io_handler => { required => TRUE(), handler => TRUE(), }, client_service_handler => { required => TRUE(), handler => TRUE(), }, client_timer_handler => { required => TRUE(), handler => TRUE(), }, enabled => { required => TRUE(), }, port => { required => FALSE(), }, ); # # vectors for select() # my $rin = ''; my $win = ''; my $ein = ''; # my $rout = ''; my $wout = ''; my $eout = ''; # ################################################################ # # miscellaneous functions # sub usage { my ($arg0) = @_; my $log_fh = $plog->log_fh(); print $log_fh <<EOF; usage: $arg0 [-?] [-h] \\ [-w | -W |-v level] \\ [-l logfile] \\ [config-file [config-file2 ...]] where: -? or -h - print this usage. -w - enable warning (level=min=1) -W - enable warning and trace (level=mid=2) -v - verbose level: 0=off,1=min,2=mid,3=max -l logfile - log file path config-file is the configuration file containing lists of services to create. one or more config files can be given. if a config file is not given, then the default is to look for the file generic-server.cfg in the current directory. EOF } # sub read_file { my ($file_nm, $praw_data) = @_; # if ( ! -r $file_nm ) { $plog->log_err("File %s is NOT readable\n", $file_nm); return FAIL; } # unless (open(INFD, $file_nm)) { $plog->log_err("Unable to open %s.\n", $file_nm); return FAIL; } @{$praw_data} = <INFD>; close(INFD); # # remove any CR-NL sequences from windows. # chomp(@{$praw_data}); s/\r//g for @{$praw_data}; # $plog->log_vmid("Lines read: %d\n", scalar(@{$praw_data})); return SUCCESS; } # ################################################################ # # read and parse config file. # sub check_service_data { my ($pservice) = @_; # foreach my $key (keys %service_params) { if ((!exists($pservice->{$key})) && ($service_params{$key}{required} == TRUE)) { $plog->log_err("Required field missing: %s\n", $key); return FALSE; } } # return TRUE; } # sub parse_cfg_file { my ($pdata) = @_; # my $lnno = 0; my $pservice = { }; my $in_service = FALSE; # foreach my $record (@{$pdata}) { $plog->log_vmin("Processing record (%d) : %s\n", ++$lnno, $record); # if (($record =~ m/^\s*#/) || ($record =~ m/^\s*$/)) { # skip comments or white-space-only lines next; } elsif ($record =~ m/^\s*service\s*start\s*$/) { if ($in_service != FALSE) { $plog->log_err("Previous service not ended (%d).\n", $lnno); return FAIL; } # $pservice = { }; $in_service = TRUE; } elsif ($record =~ m/^\s*service\s*end\s*$/) { if ($in_service != TRUE) { $plog->log_err("Missing service name (%d).\n", $lnno); return FAIL; } elsif ((exists($pservice->{name})) && ($pservice->{name} ne "")) { my $name = $pservice->{name}; # $plog->log_msg("Storing service: %s\n", $name); # if ($pservices->exists($name) == TRUE) { $plog->log_err("Duplicate service name (%d): %s\n", $lnno, $name); return FAIL; } # if (check_service_data($pservice) != TRUE) { $plog->log_err("Service sanity check failed (%d): %s\n", $lnno, $name); return FAIL; } # $pservices->set($name, $pservice); } else { $plog->log_err("Unknown service name (%d).\n", $lnno); return FAIL; } # $pservice = { }; $in_service = FALSE; } elsif ($record =~ m/^\s*([^\s]+)\s*=\s*(.*)$/i) { my $key = ${1}; my $value = ${2}; # if (exists($service_params{$key})) { $plog->log_vmin("Setting %s to %s (%d)\n", $key, $value, $lnno); $pservice->{$key} = $value; } else { $plog->log_err("Record %d with unknown key: %s\n", $lnno, $key, $record); return FAIL; } } else { $plog->log_err("Unknown record %d: %s\n", $lnno, $record); return FAIL; } } # return SUCCESS; } # sub read_cfg_file { my ($cfgfile) = @_; # my @data = (); if ((read_file($cfgfile, \@data) == SUCCESS) && (parse_cfg_file(\@data) == SUCCESS)) { $plog->log_vmin("Successfully processed cfg file %s.\n", $cfgfile); return SUCCESS; } else { $plog->log_err("Processing cfg file %s failed.\n", $cfgfile); return FAIL; } } # ################################################################ # # generic service handlers # sub socket_stream_accept_io_handler { my ($pservice) = @_; # # do the accept # my $pfh = $pservice->{fh}; # my $new_fh = FileHandle->new(); my $new_fh = undef; if (my $client_paddr = accept($new_fh, $$pfh)) { $plog->log_msg("accept() succeeded for service %s\n", $pservice->{name}); # fcntl($new_fh, F_SETFL, O_NONBLOCK); # my ($client_port, $client_packed_ip) = sockaddr_in($client_paddr); my $client_ascii_ip = inet_ntoa($client_packed_ip); # vec($rin, fileno($new_fh), 1) = 1; vec($ein, fileno($new_fh), 1) = 1; # my $io_handler = undef; die "unknown client io handler: $!" unless (exists($pservice->{client_io_handler})); $io_handler = $pservice->{client_io_handler}; # my $service_handler = undef; die "unknown client service handler: $!" unless (exists($pservice->{client_service_handler})); $service_handler = $pservice->{client_service_handler}; # my $timer_handler = $pservice->{client_timer_handler}; # my $pnew_service = { client => TRUE(), name => "client_of_" . $pservice->{name}, client_port => $client_port, client_host_name => $client_ascii_ip, client_paddr => $client_paddr, fh => \$new_fh, io_handler => $io_handler, service_handler => $service_handler, timer_handler => $timer_handler, total_buffer => "", }; # my $fileno = fileno($new_fh); $pfh_services->set($fileno, $pnew_service); $pfh_data->reallocate($fileno); # # call ctor if it exists. # my $ctor = $pservice->{'ctor'}; if (defined($ctor)) { my $status = &{$ctor}($pnew_service); } return SUCCESS; } else { $plog->log_err("accept() failed for service %s\n", $pservice->{name}); return FAIL; } } # sub generic_stream_io_handler { my ($pservice) = @_; # $plog->log_msg("entering generic_stream_io_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $buffer = undef; my $nr = sysread($$pfh, $buffer, 1024*4); # if (defined($nr)) { if ($nr > 0) { # # read something ... process it ... # my $local_buffer = unpack("H*", $buffer); $plog->log_msg("nr ... <%d>\n", $nr); $plog->log_msg("buffer ... <%s>\n", $buffer); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buffer); # $pfh_data->set($fileno, 'input', $buffer); $pfh_data->set($fileno, 'input_length', $nr); # return &{$pservice->{service_handler}}($pservice); } else { # # EOF. close socket and clean up. # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); # return SUCCESS; } } elsif ($! != EAGAIN) { # # some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_err("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); # return FAIL; } else { # EAGAIN ... try again return SUCCESS; } } # sub generic_stream_service_handler { my ($pservice) = @_; # $plog->log_msg("entering generic_stream_service_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = $pfh_data->get($fileno, 'input_length'); my $buffer = $pfh_data->get($fileno, 'input'); # if ( ! defined(send($$pfh, $buffer, $nr))) { return FAIL; } # return SUCCESS; } # sub generic_stream_client_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); return FAIL; } } else { $plog->log_err("Parsing failed.\n"); return FAIL; } # $pxml = undef; return SUCCESS; } # ################################################################ # # LNB-specific io handler # sub lnb_io_handler { my ($pservice) = @_; # $plog->log_msg("entering lnb_io_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = 0; my $buffer = undef; # # for testing use a small buffer ... # while (defined($nr = sysread($$pfh, $buffer, 8*4)) && ($nr > 0)) # while (defined($nr = sysread($$pfh, $buffer, 1024*4)) && ($nr > 0)) { $plog->log_msg("nr ... <%d>\n", $nr); $plog->log_msg("buffer ... <%s>\n", $buffer); # my $local_buffer = unpack("H*", $buffer); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buffer); # if ($nr > 0) { my $total_buffer = $pfh_data->get($fileno, 'total_buffer'); $total_buffer = $total_buffer . $buffer; my $tblen = length($total_buffer); my $sohi = -1; my $stxi = -1; my $etxi = -1; for (my $tbi = 0; $tbi < $tblen; $tbi += 1) { my $ch = substr($total_buffer, $tbi, 1); if ($ch =~ m/^\x01/) { $sohi = $tbi; $stxi = -1; $etxi = -1; } elsif ($ch =~ m/^\x02/) { $stxi = $tbi; } elsif ($ch =~ m/^\x03/) { $etxi = $tbi; } # if (($stxi != -1) && ($etxi != -1)) { my $xml_start = $stxi + 1; my $xml_end = $etxi - 1; my $xml_length = $xml_end - $xml_start + 1; my $xml_buffer = substr($total_buffer, $xml_start, $xml_length); # $pfh_data->set($fileno, 'input', $xml_buffer); $pfh_data->set($fileno, 'input_length', $xml_length); # &{$pservice->{service_handler}}($pservice); # $sohi = -1; $stxi = -1; $etxi = -1; } } # # reset for partially read messages. # if ($sohi != -1) { $plog->log_msg("Partial read ... got back for more.\n"); $total_buffer = substr($total_buffer, $sohi); $pfh_data->set($fileno, 'total_buffer', $total_buffer); } } } # if ((( ! defined($nr)) && ($! != EAGAIN)) || (defined($nr) && ($nr == 0))) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } # return SUCCESS; } # sub send_xml_msg { my ($pservice, $xml) = @_; # my $pfh = $pservice->{fh}; # my $buflen = sprintf("%06d", length($xml)); # # c ==>> SOH # A* ==>> XML length # c ==>> STX # A* ==>> XML # c ==>> ETX # my $buf = pack("cA*cA*c", SOH, $buflen, STX, $xml, ETX); # # len(SOH) + len(xml_length) + len(STX) + len(xml) + len(ETX) # my $nw = 1 + 6 + 1 + length($xml) + 1; # my $local_buf = unpack("H*", $buf); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buf); # # handle partial writes. # # die $! if ( ! defined(send($$pfh, $buf, $nw))); for (my $ntow=$nw; ($ntow > 0) && defined($nw = send($$pfh, $buf, $ntow)); $ntow -= $nw) { } die $! if ( ! defined($nw) ); } # ################################################################ # # lnb service handlers # sub test_lnb_client_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); $pxml = undef; return SUCCESS; } else { $plog->log_err("Deparsing failed.\n"); $pxml = undef; return FAIL; } } else { $plog->log_err("Parsing failed.\n"); $pxml = undef; return FAIL; } } # sub lnbcvthost_client_io_handler { return lnb_io_handler(@_); } # sub lnbcvthost_client_service_handler { return test_lnb_client_service_handler(@_); } # sub lnbcvthost_client_timer_handler { return SUCCESS; } # sub lnbcvthost_io_handler { return socket_stream_accept_io_handler(@_); } # sub lnbcvthost_service_handler { return SUCCESS; } # sub lnbcvthost_timer_handler { return SUCCESS; } # sub lnblmhost_client_io_handler { return lnb_io_handler(@_); } # sub lnblmhost_client_service_handler { return test_lnb_client_service_handler(@_); } # sub lnblmhost_client_timer_handler { return SUCCESS; } # sub lnblmhost_io_handler { return socket_stream_accept_io_handler(@_); } # sub lnblmhost_service_handler { return SUCCESS; } # sub lnblmhost_timer_handler { return SUCCESS; } # sub lnbmihost_client_io_handler { return lnb_io_handler(@_); } # sub lnbmihost_client_service_handler { return test_lnb_client_service_handler(@_); } # sub lnbmihost_client_timer_handler { return SUCCESS; } # sub lnbmihost_io_handler { return socket_stream_accept_io_handler(@_); } # sub lnbmihost_service_handler { return SUCCESS; } # sub lnbmihost_timer_handler { return SUCCESS; } # sub lnbspcvthost_client_io_handler { return lnb_io_handler(@_); } # sub lnbspcvthost_client_service_handler { return test_lnb_client_service_handler(@_); } # sub lnbspcvthost_client_timer_handler { return SUCCESS; } # sub lnbspcvthost_io_handler { return socket_stream_accept_io_handler(@_); } # sub lnbspcvthost_service_handler { return SUCCESS; } # sub lnbspcvthost_timer_handler { return SUCCESS; } # sub lnbspmihost_client_io_handler { return lnb_io_handler(@_); } # sub lnbspmihost_client_service_handler { return test_lnb_client_service_handler(@_); } # sub lnbspmihost_client_timer_handler { return SUCCESS; } # sub lnbspmihost_io_handler { return socket_stream_accept_io_handler(@_); } # sub lnbspmihost_service_handler { return SUCCESS; } # sub lnbspmihost_timer_handler { return SUCCESS; } # sub my_echo_io_handler { return generic_stream_io_handler(@_); } # sub my_echo_service_handler { return generic_stream_service_handler(@_); } # sub null_handler { return SUCCESS; } # sub stdin_timer_handler { my ($ptimer, $pservice) = @_; # $plog->log_vmin("sanity timer handler ... %s\n", $ptimer->{label}); # start_timer($ptimer->{fileno}, $ptimer->{delta}, $ptimer->{label}); } # sub stdin_handler { my ($pservice) = @_; # my $data = <STDIN>; chomp($data); # if (defined($data)) { $plog->log_msg("input ... <%s>\n", $data); if ($data =~ m/^q$/i) { $event_loop_done = TRUE; } elsif (($data =~ m/^[h?]$/i) || ($data eq "")) { my $log_fh = $plog->log_fh(); print $log_fh <<EOF; Available commnds: q - quit ? - help h - help l - list services s - print services lc - list clients cc <fileno> - close client t - print timers v0 - no verbose v1 - min verbose v2 - mid verbose v3 - max verbose EOF } elsif ($data =~ m/^v0$/i) { $plog->verbose(NOVERBOSE); } elsif ($data =~ m/^v1$/i) { $plog->verbose(MINVERBOSE); } elsif ($data =~ m/^v2$/i) { $plog->verbose(MIDVERBOSE); } elsif ($data =~ m/^v3$/i) { $plog->verbose(MAXVERBOSE); } elsif ($data =~ m/^s$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); $plog->log_msg("FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); if ((defined($pservice->{port})) && ($pservice->{port} > 0)) { $plog->log_msg("FileNo: %d, Port: %s\n", $fileno, $pservice->{port}); } if ((defined($pservice->{file_name})) && ($pservice->{file_name} ne "")) { $plog->log_msg("FileNo: %d, File Name: %s\n", $fileno, $pservice->{file_name}); } if ((defined($pservice->{client_host_name})) && ($pservice->{client_host_name} ne "")) { $plog->log_msg("FileNo: %d, Client Host Name: %s\n", $fileno, $pservice->{client_host_name}); } if ((defined($pservice->{client_port})) && ($pservice->{client_port} > 0)) { $plog->log_msg("FileNo: %d, Client Port: %d\n", $fileno, $pservice->{client_port}); } } } elsif ($data =~ m/^l$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); $plog->log_msg("FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); } } elsif ($data =~ m/^lc$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); if ((defined($pservice->{client})) && ($pservice->{client} == TRUE)) { $plog->log_msg("Client: FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); } } } elsif ($data =~ m/^cc\s*(\d+)\s*$/i) { my $fileno_to_close = $1; if (defined($fileno_to_close) && ($fileno_to_close >= 0)) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); if ((defined($pservice->{client})) && ($pservice->{client} == TRUE) && ($fileno == $fileno_to_close)) { $plog->log_msg("Closing Client: FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # my $pfh = $pservice->{fh}; close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } } } else { $plog->log_msg("Invalid client file no.\n"); } } elsif ($data =~ m/^t$/i) { $pq->dump(); } } } # ################################################################ # # create services and service handlers # sub add_stdin_to_services { my $fno = fileno(STDIN); # $pfh_services->set($fno, { name => "STDIN", io_handler => \&stdin_handler, timer_handler => \&stdin_timer_handler, }); # $pfh_data->reallocate($fno); # $plog->log_msg("Adding STDIN service ... %s\n", $pfh_services->get($fno, 'name')); # vec($rin, fileno(STDIN), 1) = 1; } # sub function_defined { my ($func_name) = @_; if (defined(&{$func_name})) { return TRUE; } else { return FALSE; } } # sub get_handler { my ($handler) = @_; # if (function_defined($handler) == TRUE) { # turn off strict so we can convert name to function. no strict 'refs'; return \&{$handler}; } else { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return undef } } # sub create_socket_stream { my ($pservice) = @_; # $plog->log_msg("Creating stream socket for %s.\n", $pservice->{name}); # my $fh = undef; socket($fh, PF_INET, SOCK_STREAM, getprotobyname('tcp')); setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, 1); # $plog->log_msg("calling gethostbyname($pservice->{host_name})\n"); my $ipaddr = gethostbyname($pservice->{host_name}); defined($ipaddr) or die "gethostbyname: $!"; # my $port = undef; if (exists($pservice->{service}) && defined($pservice->{service})) { # get port from services file $port = getservbyname($pservice->{service}, 'tcp') or die "Can't get port for service $pservice->{service}: $!"; $plog->log_msg("getservbyname($pservice->{service}, 'tcp') port = $port\n"); $pservice->{port} = $port; } else { $port = $pservice->{port}; $plog->log_msg("Config file port = $port\n"); } my $paddr = sockaddr_in($port, $ipaddr); defined($paddr) or die "sockaddr_in: $!"; # bind($fh, $paddr) or die "bind error for $pservice->{name}: $!"; listen($fh, SOMAXCONN) or die "listen: $!"; # $plog->log_vmin("File Handle is ... $fh, %d\n", fileno($fh)); # $pservice->{fh} = \$fh; # # check for handlers # foreach my $key (keys %service_params) { if (exists($service_params{$key}{handler}) && ($service_params{$key}{handler} == TRUE)) { my $handler = $pservice->{$key}; $pservice->{$key} = get_handler($handler); if ( ! defined($pservice->{$key})) { $plog->log_err("Function %s does NOT EXIST.\n", $key); return FAIL; } } } # return SUCCESS; } # sub create_services { my $piter = $pservices->iterator(); while (defined(my $service = $piter->())) { $plog->log_msg("Creating server onection for %s ...\n", $service); # my $pservice = $pservices->get($service); if ( ! defined($pservice)) { $plog->log_err("Service %s not found.\n", $service); return FAIL; } # if (create_socket_stream($pservice) != SUCCESS) { $plog->log_err("Failed to create server socket/pipe for %s\n", $service); return FAIL; } # my $pfh = $pservice->{'fh'}; my $fileno = fileno($$pfh); $plog->log_msg("Successfully create server socket/pipe for %s (%d)\n", $service, $fileno); $pfh_services->set($fileno, $pservice); $pfh_data->reallocate($fileno); } # return SUCCESS; } # ################################################################ # # real-time events loop # sub set_io_nonblock { my $piter = $pservices->iterator(); while (defined(my $service = $piter->())) { my $pfh = $pservices->get($service, 'fh'); fcntl($$pfh, F_SETFL, O_NONBLOCK); } } # sub start_timer { my ($fileno, $delta, $label) = @_; # my $timerid = int(rand(1000000000)); # if ($delta <= 0) { $plog->log_err("Timer length is zero for %s. Skipping it.\n", $fileno); return; } # $plog->log_vmin("starttimer: " . "fileno=${fileno} " . "label=${label} " . "delta=${delta} " . "id=$timerid "); # my $ptimer = mytimer->new($fileno, $delta, $timerid, $label); # $plog->log_vmin("fileno = $ptimer->{fileno} " . "delta = $ptimer->{delta} " . "expire = $ptimer->{expire} " . "id = $ptimer->{id} " . "label = $ptimer->{label} "); # $pq->enqueue($ptimer); } # sub run_event_loop { # # mark all file handles as non-blocking # set_io_nonblock(); # my $psit = $pservices->iterator(); while (defined(my $service = $psit->())) { my $pfh = $pservices->get($service, 'fh'); vec($rin, fileno($$pfh), 1) = 1; } # # enter event loop # my $sanity_time = 5; # $plog->log_msg("Start event loop ...\n"); # my $mydelta = 0; my $start_time = time(); my $current_time = $start_time; my $previous_time = 0; # while ($event_loop_done == FALSE) { # # save current time as the last time we did anything. # $previous_time = $current_time; # if ($pq->is_empty()) { start_timer(fileno(STDIN), $sanity_time, "sanity-timer"); } # my $ptimer = undef; die "Empty timer queue: $!" unless ($pq->front(\$ptimer) == 1); # $mydelta = $ptimer->{expire} - $current_time; $mydelta = 0 if ($mydelta < 0); # my ($nf, $timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $mydelta); # # update current timers # $current_time = time(); # if ($timeleft <= 0) { $plog->log_vmid("Time expired ...\n"); # $ptimer = undef; while ($pq->dequeue(\$ptimer) != 0) { if ($ptimer->{expire} > $current_time) { $pq->enqueue($ptimer); last; } # my $fileno = $ptimer->{fileno}; my $pservice = $pfh_services->get($fileno); # &{$pservice->{timer_handler}}($ptimer, $pservice); $ptimer = undef; } } elsif ($nf > 0) { $plog->log_vmid("NF, TIMELEFT ... (%d,%d)\n", $nf, $timeleft); my $pfhit = $pfh_services->iterator(); while (defined(my $fileno = $pfhit->())) { my $pfh = $pfh_services->get($fileno, 'fh'); my $pservice = $pfh_services->get($fileno); # if (vec($eout, $fileno, 1)) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); } elsif (vec($rout, $fileno, 1)) { # # ready for a read # $plog->log_vmid("input available for %s ...\n", $pservice->{name}); # # call handler # &{$pservice->{io_handler}}($pservice); } } } } # $plog->log_msg("Event-loop done ...\n"); # return SUCCESS; } # ################################################################ # # start of main # $plog->disable_stdout_buffering(); # my %opts; if (getopts('?hwWv:l:', \%opts) != 1) { usage($cmd); exit 2; } # foreach my $opt (%opts) { if (($opt eq 'h') or ($opt eq '?')) { usage($cmd); exit 0; } elsif ($opt eq 'w') { $plog->verbose(MINVERBOSE); } elsif ($opt eq 'W') { $plog->verbose(MIDVERBOSE); } elsif ($opt eq 'v') { if (!defined($plog->verbose($opts{$opt}))) { $plog->log_err("Invalid verbose level: $opts{$opt}\n"); usage($cmd); exit 2; } } elsif ($opt eq 'l') { $plog->logfile($opts{$opt}); $plog->log_msg("Log File: %s\n", $opts{$opt}); } } # # check if config file was given. # if (scalar(@ARGV) == 0) { # # use default config file. # $plog->log_msg("Using default config file: %s\n", $default_cfg_file); if (read_cfg_file($default_cfg_file) != SUCCESS) { $plog->log_err_exit("read_cfg_file failed. Done.\n"); } } else { # # read in config files and start up services. # foreach my $cfg_file (@ARGV) { $plog->log_msg("Reading config file %s ...\n", $cfg_file); if (read_cfg_file($cfg_file) != SUCCESS) { $plog->log_err_exit("read_cfg_file failed. Done.\n"); } } } # # create server sockets or pipes as needed. # if (create_services() != SUCCESS) { $plog->log_err_exit("create_server_connections failed. Done.\n"); } # # monitor stdin for i/o with user. # add_stdin_to_services(); # # event loop to handle connections, etc. # if (run_event_loop() != SUCCESS) { $plog->log_err_exit("run_event_loop failed. Done.\n"); } # $plog->log_msg("All is well that ends well.\n"); # exit 0; __DATA__ #!/usr/bin/perl -w # ################################################################ # # generic server for stream/datagram and socket/unix. # ################################################################ # use strict; # my $binpath; # BEGIN { use File::Basename; # $binpath = dirname($0); $binpath = "." if ($binpath eq ""); } # # perl mods # use Getopt::Std; use Socket; use FileHandle; use POSIX qw(:errno_h); # # my mods # use lib $binpath; # use myconstants; use mylogger; use mytimer; use mytimerpqueue; use mytaskdata; use mylnbxml; # ################################################################ # # local constants # use constant SOCKET_STREAM => 'SOCKET_STREAM'; use constant SOCKET_DATAGRAM => 'SOCKET_DATAGRAM'; use constant UNIX_STREAM => 'UNIX_STREAM'; use constant UNIX_DATAGRAM => 'UNIX_DATAGRAM'; use constant TTY_STREAM => 'TTY_STREAM'; # use constant SOH => 1; use constant STX => 2; use constant ETX => 3; # ################################################################ # # globals # my $cmd = $0; my $default_cfg_file = "generic-server.cfg"; # my $plog = mylogger->new(); die "Unable to create logger: $!" unless (defined($plog)); # my $pq = mytimerpqueue->new(); die "Unable to create priority queue: $!" unless (defined($pq)); # # default service values # my %default_service_params = ( name => { use_default => FALSE(), default_value => "", translate => undef, }, type => { use_default => TRUE(), default_value => SOCKET_STREAM(), translate => \&to_uc, }, host_name => { use_default => TRUE(), default_value => "localhost", translate => undef, }, file_name => { use_default => TRUE(), default_value => "", translate => undef, }, port => { use_default => TRUE(), default_value => -1, translate => undef, }, service => { use_default => TRUE(), default_value => undef, translate => undef, }, client => { use_default => TRUE(), default_value => FALSE(), translate => undef, }, io_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, service_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, timer_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, ctor => { use_default => TRUE(), default_value => undef, translate => undef, }, client_io_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, client_service_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, client_timer_handler => { use_default => TRUE(), default_value => undef, translate => undef, }, client_ctor => { use_default => TRUE(), default_value => undef, translate => undef, }, ); # # vectors for select() # my $rin = ''; my $win = ''; my $ein = ''; # my $rout = ''; my $wout = ''; my $eout = ''; # # map connection type to create connection routine # my %create_connection = ( SOCKET_STREAM() => \&create_socket_stream, SOCKET_DATAGRAM() => \&create_socket_dgram, UNIX_STREAM() => \&create_unix_stream, UNIX_DATAGRAM() => \&create_unix_dgram, TTY_STREAM() => undef ); # # private data for each service instance # my $pservices = mytaskdata->new(); die "Unable to create services data: $!" unless (defined($pservices)); # my $pfh_services = mytaskdata->new(); die "Unable to create file-handler-to-services data: $!" unless (defined($pfh_services)); # my $pfh_data = mytaskdata->new(); die "Unable to create task-specific data: $!" unless (defined($pfh_data)); # # misc # my $event_loop_done = FALSE; # ################################################################ # # misc functions # sub usage { my ($arg0) = @_; my $log_fh = $plog->log_fh(); print $log_fh <<EOF; usage: $arg0 [-?] [-h] \\ [-w | -W |-v level] \\ [-l logfile] \\ [config-file [config-file2 ...]] where: -? or -h - print this usage. -w - enable warning (level=min=1) -W - enable warning and trace (level=mid=2) -v - verbose level: 0=off,1=min,2=mid,3=max -l logfile - log file path config-file is the configuration file containing lists of services to create. one or more config files can be given. if a config file is not given, then the default is to look for the file generic-server.cfg in the current directory. EOF } # ################################################################ # # read and parse data files. # sub read_file { my ($file_nm, $praw_data) = @_; # if ( ! -r $file_nm ) { $plog->log_err("File %s is NOT readable\n", $file_nm); return FAIL; } # unless (open(INFD, $file_nm)) { $plog->log_err("Unable to open %s.\n", $file_nm); return FAIL; } @{$praw_data} = <INFD>; close(INFD); # # remove any CR-NL sequences from Windose. # chomp(@{$praw_data}); s/\r//g for @{$praw_data}; # $plog->log_vmin("Lines read: %d\n", scalar(@{$praw_data})); return SUCCESS; } # sub fill_in_missing_data { my ($pservice) = @_; # foreach my $key (keys %default_service_params) { if (( ! exists($pservice->{$key})) && ($default_service_params{$key}{use_default} == TRUE)) { $plog->log_vmin("Defaulting missing %s field.\n", $key); $pservice->{$key} = $default_service_params{$key}{default_value}; } } } # sub to_uc { my ($in) = @_; return uc($in); } # sub parse_file { my ($pdata) = @_; # my $lnno = 0; my $pservice = { }; # foreach my $record (@{$pdata}) { $plog->log_vmin("Processing record (%d) : %s\n", ++$lnno, $record); # if (($record =~ m/^\s*#/) || ($record =~ m/^\s*$/)) { # skip comments or white-space-only lines next; } elsif ($record =~ m/^\s*service\s*start\s*$/) { $pservice = { }; } elsif ($record =~ m/^\s*service\s*end\s*$/) { if ((exists($pservice->{name})) && ($pservice->{name} ne "")) { my $name = $pservice->{name}; # $plog->log_msg("Storing service: %s\n", $name); # die "ERROR: duplicate service $name: $!" if ($pservices->exists($name) == TRUE); # fill_in_missing_data($pservice); $pservices->set($name, $pservice); } else { $plog->log_err("Unknown service name (%d).\n", $lnno); return FAIL; } # $pservice = { }; } else { my $found = FALSE; foreach my $key (keys %default_service_params) { if ($record =~ m/^\s*${key}\s*=\s*(.*)$/i) { $plog->log_vmin("Setting %s to %s (%d)\n", $key, ${1}, $lnno); if (defined($default_service_params{$key}{translate})) { # massage the data value $pservice->{$key} = &{$default_service_params{$key}{translate}}(${1}); } else { $pservice->{$key} = ${1}; } $found = TRUE; last; } } if ($found == FALSE) { $plog->log_err_exit("Unknown record %d: %s\n", $lnno, $record); } } } # return SUCCESS; } # sub read_cfg_file { my ($cfgfile) = @_; # my @data = (); if ((read_file($cfgfile, \@data) == SUCCESS) && (parse_file(\@data) == SUCCESS)) { $plog->log_vmin("Successfully processed cfg file %s.\n", $cfgfile); return SUCCESS; } else { $plog->log_err("Processing cfg file %s failed.\n", $cfgfile); return FAIL; } } # ################################################################ # # default timer, io and service handlers # sub null_timer_handler { my ($ptimer, $pservice) = @_; # $plog->log_vmin("null timer handler ... %s\n", $ptimer->{label}); } # sub stdin_timer_handler { my ($ptimer, $pservice) = @_; # $plog->log_vmin("sanity timer handler ... %s\n", $ptimer->{label}); # start_timer($ptimer->{fileno}, $ptimer->{delta}, $ptimer->{label}); } # sub stdin_handler { my ($pservice) = @_; # my $data = <STDIN>; chomp($data); # if (defined($data)) { $plog->log_msg("input ... <%s>\n", $data); if ($data =~ m/^q$/i) { $event_loop_done = TRUE; } elsif (($data =~ m/^[h?]$/i) || ($data eq "")) { my $log_fh = $plog->log_fh(); print $log_fh <<EOF; Available commnds: q - quit ? - help h - help l - list services s - print services lc - list clients cc <fileno> - close client t - print timers EOF } elsif ($data =~ m/^s$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); $plog->log_msg("FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); if ((defined($pservice->{port})) && ($pservice->{port} > 0)) { $plog->log_msg("FileNo: %d, Port: %s\n", $fileno, $pservice->{port}); } if ((defined($pservice->{file_name})) && ($pservice->{file_name} ne "")) { $plog->log_msg("FileNo: %d, File Name: %s\n", $fileno, $pservice->{file_name}); } } } elsif ($data =~ m/^l$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); $plog->log_msg("FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); } } elsif ($data =~ m/^lc$/i) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); if ((defined($pservice->{client})) && ($pservice->{client} == TRUE)) { $plog->log_msg("Client: FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); } } } elsif ($data =~ m/^cc\s*(\d+)\s*$/i) { my $fileno_to_close = $1; if (defined($fileno_to_close) && ($fileno_to_close >= 0)) { my $pfhit = $pfh_services->iterator('n'); while (defined(my $fileno = $pfhit->())) { my $pservice = $pfh_services->get($fileno); if ((defined($pservice->{client})) && ($pservice->{client} == TRUE) && ($fileno == $fileno_to_close)) { $plog->log_msg("Closing Client: FileNo: %d, Service: %s\n", $fileno, $pservice->{name}); vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # my $pfh = $pservice->{fh}; close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } } } else { $plog->log_msg("Invalid client file no.\n"); } } elsif ($data =~ m/^t$/i) { $pq->dump(); } } } # sub generic_stream_io_handler { my ($pservice) = @_; # $plog->log_msg("entering generic_stream_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = 0; my $buffer = undef; while (defined($nr = sysread($$pfh, $buffer, 1024*4)) && ($nr > 0)) { my $local_buffer = unpack("H*", $buffer); $plog->log_msg("nr ... <%d>\n", $nr); $plog->log_msg("buffer ... <%s>\n", $buffer); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buffer); # $pfh_data->set($fileno, 'input', $buffer); $pfh_data->set($fileno, 'input_length', $nr); &{$pservice->{service_handler}}($pservice); } # if ((( ! defined($nr)) && ($! != EAGAIN)) || (defined($nr) && ($nr == 0))) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } } # sub generic_stream_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = $pfh_data->get($fileno, 'input_length'); my $buffer = $pfh_data->get($fileno, 'input'); # die $! if ( ! defined(send($$pfh, $buffer, $nr))); } # sub generic_datagram_io_handler { my ($pservice) = @_; # $plog->log_msg("entering generic_datagram_io_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $recvpaddr = undef; my $buffer = undef; while (defined($recvpaddr = recv($$pfh, $buffer, 1024*4, 0))) { my $local_buffer = unpack("H*", $buffer); $plog->log_msg("buffer ... <%s>\n", $buffer); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buffer); # $pfh_data->set($fileno, 'input', $buffer); $pfh_data->set($fileno, 'input_length', length($buffer)); $pfh_data->set($fileno, 'recvpaddr', $recvpaddr); &{$pservice->{service_handler}}($pservice); } # if (( ! defined($recvpaddr)) && ($! != EAGAIN)) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } } # sub generic_datagram_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = $pfh_data->get($fileno, 'input_length'); my $buffer = $pfh_data->get($fileno, 'input'); my $recvpaddr = $pfh_data->get($fileno, 'recvpaddr'); # die $! if ( ! defined(send($$pfh, $buffer, 0, $recvpaddr))); } # sub socket_stream_accept_io_handler { my ($pservice) = @_; # # do the accept # my $pfh = $pservice->{fh}; # my $new_fh = FileHandle->new(); my $new_fh = undef; if (my $client_paddr = accept($new_fh, $$pfh)) { $plog->log_msg("accept() succeeded for service %s\n", $pservice->{name}); # fcntl($new_fh, F_SETFL, O_NONBLOCK); # my ($client_port, $client_packed_ip) = sockaddr_in($client_paddr); my $client_ascii_ip = inet_ntoa($client_packed_ip); # vec($rin, fileno($new_fh), 1) = 1; vec($ein, fileno($new_fh), 1) = 1; # my $io_handler = undef; die "unknown client io handler: $!" unless (exists($pservice->{client_io_handler})); $io_handler = $pservice->{client_io_handler}; # my $service_handler = undef; die "unknown client service handler: $!" unless (exists($pservice->{client_service_handler})); $service_handler = $pservice->{client_service_handler}; # my $timer_handler = $pservice->{client_timer_handler}; # my $pnew_service = { client => TRUE(), name => "client_of_" . $pservice->{name}, client_port => $client_port, client_host_name => $client_ascii_ip, client_paddr => $client_paddr, fh => \$new_fh, io_handler => $io_handler, service_handler => $service_handler, timer_handler => $timer_handler, total_buffer => "", }; # my $fileno = fileno($new_fh); $pfh_services->set($fileno, $pnew_service); $pfh_data->reallocate($fileno); # # call ctor if it exists. # my $ctor = $pservice->{'ctor'}; if (defined($ctor)) { my $status = &{$ctor}($pnew_service); } } else { $plog->log_err("accept() failed for service %s\n", $pservice->{name}); } } # sub unix_stream_accept_io_handler { my ($pservice) = @_; # # do the accept # my $pfh = $pservice->{fh}; # my $new_fh = FileHandle->new(); my $new_fh = undef; if (my $client_paddr = accept($new_fh, $$pfh)) { $plog->log_msg("accept() succeeded for service %s\n", $pservice->{name}); # fcntl($new_fh, F_SETFL, O_NONBLOCK); # my ($client_filename) = sockaddr_un($client_paddr); # vec($rin, fileno($new_fh), 1) = 1; vec($ein, fileno($new_fh), 1) = 1; # my $io_handler = undef; die "unknown client handler: $!" unless (exists($pservice->{client_io_handler})); $io_handler = $pservice->{client_io_handler}; # my $service_handler = undef; die "unknown client handler: $!" unless (exists($pservice->{client_service_handler})); $service_handler = $pservice->{client_service_handler}; # my $timer_handler = $pservice->{client_timer_handler}; # my $pnew_service = { client => TRUE(), name => "client_of_" . $pservice->{name}, client_filename => $client_filename, client_paddr => $client_paddr, fh => \$new_fh, io_handler => $io_handler, service_handler => $service_handler, timer_handler => $timer_handler, total_buffer => "", }; # my $fileno = fileno($new_fh); $pfh_services->set($fileno, $pnew_service); $pfh_data->reallocate($fileno); # # call ctor if it exists. # my $ctor = $pservice->{'ctor'}; if (defined($ctor)) { my $status = &{$ctor}($pnew_service); } } else { $plog->log_err("accept() failed for service %s\n", $pservice->{name}); } } # sub socket_stream_accept_service_handler { my ($pservice) = @_; } # sub unix_stream_accept_service_handler { my ($pservice) = @_; } # sub socket_stream_io_handler { my ($pservice) = @_; generic_stream_io_handler($pservice); } # sub socket_stream_service_handler { my ($pservice) = @_; generic_stream_service_handler($pservice); } # sub socket_datagram_io_handler { my ($pservice) = @_; generic_datagram_io_handler($pservice); } # sub socket_datagram_service_handler { my ($pservice) = @_; generic_datagram_service_handler($pservice); } # sub unix_stream_io_handler { my ($pservice) = @_; generic_stream_io_handler($pservice); } # sub unix_stream_service_handler { my ($pservice) = @_; generic_stream_service_handler($pservice); } # sub unix_datagram_io_handler { my ($pservice) = @_; generic_datagram_io_handler($pservice); } # sub unix_datagram_service_handler { my ($pservice) = @_; generic_datagram_service_handler($pservice); } # ################################################################ # # LNB-specific io, timer, and servers # sub lnb_io_handler { my ($pservice) = @_; # $plog->log_msg("entering lnb_io_handler() for %s\n", $pservice->{name}); # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $nr = 0; my $buffer = undef; while (defined($nr = sysread($$pfh, $buffer, 1024*4)) && ($nr > 0)) { $plog->log_msg("nr ... <%d>\n", $nr); $plog->log_msg("buffer ... <%s>\n", $buffer); # my $local_buffer = unpack("H*", $buffer); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buffer); # if ($nr > 0) { my $total_buffer = $pfh_data->get($fileno, 'total_buffer'); $total_buffer = $total_buffer . $buffer; my $tblen = length($total_buffer); my $sohi = -1; my $stxi = -1; my $etxi = -1; for (my $tbi = 0; $tbi < $tblen; $tbi += 1) { my $ch = substr($total_buffer, $tbi, 1); if ($ch =~ m/^\x01/) { $sohi = $tbi; $stxi = -1; $etxi = -1; } elsif ($ch =~ m/^\x02/) { $stxi = $tbi; } elsif ($ch =~ m/^\x03/) { $etxi = $tbi; } # if (($stxi != -1) && ($etxi != -1)) { my $xml_start = $stxi + 1; my $xml_end = $etxi - 1; my $xml_length = $xml_end - $xml_start + 1; my $xml_buffer = substr($total_buffer, $xml_start, $xml_length); # $pfh_data->set($fileno, 'input', $xml_buffer); $pfh_data->set($fileno, 'input_length', $xml_length); # &{$pservice->{service_handler}}($pservice); # $sohi = -1; $stxi = -1; $etxi = -1; } } # # reset for partially read messages. # if ($sohi != -1) { $total_buffer = substr($total_buffer, $sohi); $pfh_data->set($fileno, 'total_buffer', $total_buffer); } } } # if ((( ! defined($nr)) && ($! != EAGAIN)) || (defined($nr) && ($nr == 0))) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); $pfh_data->deallocate($fileno); } } # sub send_xml_msg { my ($pservice, $xml) = @_; # my $pfh = $pservice->{fh}; # my $buflen = sprintf("%06d", length($xml)); # # c ==>> SOH # A* ==>> XML length # c ==>> STX # A* ==>> XML # c ==>> ETX # my $buf = pack("cA*cA*c", SOH, $buflen, STX, $xml, ETX); # # len(SOH) + len(xml_length) + len(STX) + len(xml) + len(ETX) # my $nw = 1 + 6 + 1 + length($xml) + 1; # my $local_buf = unpack("H*", $buf); $plog->log_vmin("unpacked buffer ... <%s>\n", $local_buf); # # handle partial writes. # # die $! if ( ! defined(send($$pfh, $buf, $nw))); for (my $ntow=$nw; ($ntow > 0) && defined($nw = send($$pfh, $buf, $ntow)); $ntow -= $nw) { } die $! if ( ! defined($nw) ); } # sub lnbcvthost_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); } } else { $plog->log_err("Parsing failed.\n"); } # $pxml = undef; } # sub lnblmhost_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); } } else { $plog->log_err("Parsing failed.\n"); } # $pxml = undef; } # sub lnbmihost_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); } } else { $plog->log_err("Parsing failed.\n"); } # $pxml = undef; } # sub lnbspcvthost_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); } } else { $plog->log_err("Parsing failed.\n"); } # $pxml = undef; } # sub lnbspmihost_service_handler { my ($pservice) = @_; # my $pfh = $pservice->{fh}; my $fileno = fileno($$pfh); # my $xml = $pfh_data->get($fileno, 'input'); my $xml_len = $pfh_data->set($fileno, 'input_length'); # $plog->log_msg("%s: xml <%s>\n", $pservice->{name}, $xml); # my $pxml = mylnbxml->new($xml, $plog); die "Unable to create xml parser: $!" unless (defined($pxml)); # if (defined($pxml->parse())) { $plog->log_msg("Parsing succeeded.\n"); # $xml = $pxml->deparse(); if (defined($xml)) { $plog->log_msg("Deparsing succeeded.\n"); send_xml_msg($pservice, $xml); } else { $plog->log_err("Deparsing failed.\n"); } } else { $plog->log_err("Parsing failed.\n"); } # $pxml = undef; } # sub lnbcvthost_timer_handler { my ($pservice) = @_; } # sub lnblmhost_timer_handler { my ($pservice) = @_; } # sub lnbmihost_timer_handler { my ($pservice) = @_; } # sub lnbspcvthost_timer_handler { my ($pservice) = @_; } # sub lnbspmihost_timer_handler { my ($pservice) = @_; } # ################################################################ # # create services # sub function_defined { my ($func_name) = @_; if (defined(&{$func_name})) { return TRUE; } else { return FALSE; } } # sub add_stdin_to_services { my $fno = fileno(STDIN); # $pfh_services->set($fno, { name => "STDIN", type => TTY_STREAM(), io_handler => \&stdin_handler, timer_handler => \&stdin_timer_handler, }); # $pfh_data->reallocate($fno); # $plog->log_msg("Adding STDIN service ...\n"); $plog->log_msg("name ... %s type ... %s\n", $pfh_services->get($fno, 'name'), $pfh_services->get($fno, 'type')); # vec($rin, fileno(STDIN), 1) = 1; } # sub get_handler { my ($handler) = @_; # if (function_defined($handler) == TRUE) { # turn off strict so we can convert name to function. no strict 'refs'; return \&{$handler}; } else { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return undef } } # sub create_socket_stream { my ($pservice) = @_; # $plog->log_msg("Creating stream socket for %s.\n", $pservice->{name}); # # my $fh = FileHandle->new; my $fh = undef; socket($fh, PF_INET, SOCK_STREAM, getprotobyname('tcp')); setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, 1); # $plog->log_msg("calling gethostbyname($pservice->{host_name})\n"); my $ipaddr = gethostbyname($pservice->{host_name}); defined($ipaddr) or die "gethostbyname: $!"; # my $port = undef; if (exists($pservice->{service}) && defined($pservice->{service})) { # get port from services file $port = getservbyname($pservice->{service}, 'tcp') or die "Can't get port for service $pservice->{service}: $!"; $plog->log_msg("getservbyname($pservice->{service}, 'tcp') port = $port\n"); $pservice->{port} = $port; } else { $port = $pservice->{port}; $plog->log_msg("config file port = $port\n"); } my $paddr = sockaddr_in($port, $ipaddr); defined($paddr) or die "sockaddr_in: $!"; # bind($fh, $paddr) or die "bind error for $pservice->{name}: $!"; listen($fh, SOMAXCONN) or die "listen: $!"; # $plog->log_vmin("File Handle is ... $fh, %d\n", fileno($fh)); # $pservice->{fh} = \$fh; # # check for required handlers # my $handler = $pservice->{io_handler}; $pservice->{io_handler} = get_handler($handler); if ( ! defined($pservice->{io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{service_handler}; $pservice->{service_handler} = get_handler($handler); if ( ! defined($pservice->{service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{client_io_handler}; $pservice->{client_io_handler} = get_handler($handler); if ( ! defined($pservice->{client_io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{client_service_handler}; $pservice->{client_service_handler} = get_handler($handler); if ( ! defined($pservice->{client_service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # # check for optional handlers # $handler = $pservice->{timer_handler}; if (defined($handler)) { $pservice->{timer_handler} = get_handler($handler); if ( ! defined($pservice->{timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{ctor}; if (defined($handler)) { $pservice->{ctor} = get_handler($handler); if ( ! defined($pservice->{ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{client_timer_handler}; if (defined($handler)) { $pservice->{client_timer_handler} = get_handler($handler); if ( ! defined($pservice->{client_timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{client_ctor}; if (defined($handler)) { $pservice->{client_ctor} = get_handler($handler); if ( ! defined($pservice->{client_ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # return SUCCESS; } # sub create_socket_dgram { my ($pservice) = @_; # $plog->log_msg("Creating dgram socket for %s.\n", $pservice->{name}); # # my $fh = FileHandle->new; my $fh = undef; socket($fh, PF_INET, SOCK_DGRAM, getprotobyname('udp')); setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, 1); # my $ipaddr = gethostbyname($pservice->{host_name}); defined($ipaddr) or die "gethostbyname: $!"; # my $port = undef; if (exists($pservice->{service}) && defined($pservice->{service})) { # get port from services file $port = getservbyname($pservice->{service}, 'udp') or die "Can't get port for service $pservice->{service}: $!"; $plog->log_msg("getservbyname($pservice->{service}, 'udp') port = $port\n"); } else { $port = $pservice->{port}; $plog->log_msg("config file port = $port\n"); } my $paddr = sockaddr_in($port, $ipaddr); defined($paddr) or die "sockaddr_in: $!"; # bind($fh, $paddr) or die "bind: $!"; # $plog->log_vmin("File Handle is ... $fh, %d\n", fileno($fh)); # $pservice->{fh} = \$fh; # # check for required handlers # my $handler = $pservice->{io_handler}; $pservice->{io_handler} = get_handler($handler); if ( ! defined($pservice->{io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{service_handler}; $pservice->{service_handler} = get_handler($handler); if ( ! defined($pservice->{service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # # check for optional handlers # $handler = $pservice->{timer_handler}; if (defined($handler)) { $pservice->{timer_handler} = get_handler($handler); if ( ! defined($pservice->{timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{ctor}; if (defined($handler)) { $pservice->{ctor} = get_handler($handler); if ( ! defined($pservice->{ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # return SUCCESS; } # sub create_unix_stream { my ($pservice) = @_; # $plog->log_msg("Creating stream unix pipe for %s.\n", $pservice->{name}); # # my $fh = FileHandle->new; my $fh = undef; socket($fh, PF_UNIX, SOCK_STREAM, 0); # unlink($pservice->{file_name}); # $plog->log_msg("unix stream file = %s\n", $pservice->{file_name}); my $paddr = sockaddr_un($pservice->{file_name}); defined($paddr) or die "sockaddr_un: $!"; # bind($fh, $paddr) or die "bind: $!"; listen($fh, SOMAXCONN) or die "listen: $!"; # $plog->log_vmin("File Handle is ... $fh, %d\n", fileno($fh)); # $pservice->{fh} = \$fh; # # check for required handlers # my $handler = $pservice->{io_handler}; $pservice->{io_handler} = get_handler($handler); if ( ! defined($pservice->{io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{service_handler}; $pservice->{service_handler} = get_handler($handler); if ( ! defined($pservice->{service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{client_io_handler}; $pservice->{client_io_handler} = get_handler($handler); if ( ! defined($pservice->{client_io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{client_service_handler}; $pservice->{client_service_handler} = get_handler($handler); if ( ! defined($pservice->{client_service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # # check for optional handlers # $handler = $pservice->{timer_handler}; if (defined($handler)) { $pservice->{timer_handler} = get_handler($handler); if ( ! defined($pservice->{timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{ctor}; if (defined($handler)) { $pservice->{ctor} = get_handler($handler); if ( ! defined($pservice->{ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{client_timer_handler}; if (defined($handler)) { $pservice->{client_timer_handler} = get_handler($handler); if ( ! defined($pservice->{client_timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{client_ctor}; if (defined($handler)) { $pservice->{client_ctor} = get_handler($handler); if ( ! defined($pservice->{client_ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # return SUCCESS; } # sub create_unix_dgram { my ($pservice) = @_; # $plog->log_msg("Creating dgram unix pipe for %s.\n", $pservice->{name}); # # my $fh = FileHandle->new; my $fh = undef; socket($fh, PF_UNIX, SOCK_DGRAM, 0); # unlink($pservice->{file_name}); # $plog->log_msg("unix datagram file = %s\n", $pservice->{file_name}); my $paddr = sockaddr_un($pservice->{file_name}); defined($paddr) or die "sockaddr_un: $!"; # bind($fh, $paddr) or die "bind: $!"; # $plog->log_vmin("File Handle is ... $fh, %d\n", fileno($fh)); # $pservice->{fh} = \$fh; # # check for required handlers # my $handler = $pservice->{io_handler}; $pservice->{io_handler} = get_handler($handler); if ( ! defined($pservice->{io_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # $handler = $pservice->{service_handler}; $pservice->{service_handler} = get_handler($handler); if ( ! defined($pservice->{service_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } # # check for optional handlers # $handler = $pservice->{timer_handler}; if (defined($handler)) { $pservice->{timer_handler} = get_handler($handler); if ( ! defined($pservice->{timer_handler})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # $handler = $pservice->{ctor}; if (defined($handler)) { $pservice->{ctor} = get_handler($handler); if ( ! defined($pservice->{ctor})) { $plog->log_err("Function %s does NOT EXIST.\n", $handler); return FALSE; } } # return SUCCESS; } # sub create_server_connections { my $piter = $pservices->iterator(); while (defined(my $service = $piter->())) { $plog->log_msg("Creating server conection for %s ...\n", $service); # my $type = $pservices->get($service, 'type'); die "ERROR: connection type $type is unknown: $!" unless (exists($create_connection{$type})); my $status = &{$create_connection{$type}}($pservices->get($service)); if ($status == SUCCESS) { my $pfh = $pservices->get($service, 'fh'); my $fileno = fileno($$pfh); $plog->log_msg("Successfully create server socket/pipe for %s (%d)\n", $service, $fileno); $pfh_services->set($fileno, $pservices->get($service)); $pfh_data->reallocate($fileno); # # call ctor if it exists. # my $ctor = $pservices->get($service, 'ctor'); if (defined($ctor)) { $status = &{$ctor}($pservices->get($service)); } } else { $plog->log_err("Failed to create server socket/pipe for %s\n", $service); return FAIL; } } # return SUCCESS; } # ################################################################ # # event loop for timers and i/o (via select) # sub set_io_nonblock { my $piter = $pservices->iterator(); while (defined(my $service = $piter->())) { my $pfh = $pservices->get($service, 'fh'); fcntl($$pfh, F_SETFL, O_NONBLOCK); } } # sub start_timer { my ($fileno, $delta, $label) = @_; # my $timerid = int(rand(1000000000)); # if ($delta <= 0) { $plog->log_err("Timer length is zero for %s. Skipping it.\n", $fileno); return; } # $plog->log_vmin("starttimer: " . "fileno=${fileno} " . "label=${label} " . "delta=${delta} " . "id=$timerid "); # my $ptimer = mytimer->new($fileno, $delta, $timerid, $label); # $plog->log_vmin("fileno = $ptimer->{fileno} " . "delta = $ptimer->{delta} " . "expire = $ptimer->{expire} " . "id = $ptimer->{id} " . "label = $ptimer->{label} "); # $pq->enqueue($ptimer); } # sub run_event_loop { # # mark all file handles as non-blocking # set_io_nonblock(); # my $psit = $pservices->iterator(); while (defined(my $service = $psit->())) { my $pfh = $pservices->get($service, 'fh'); vec($rin, fileno($$pfh), 1) = 1; } # # enter event loop # my $sanity_time = 5; # $plog->log_msg("Start event loop ...\n"); # my $mydelta = 0; my $start_time = time(); my $current_time = $start_time; my $previous_time = 0; # while ($event_loop_done == FALSE) { # # save current time as the last time we did anything. # $previous_time = $current_time; # if ($pq->is_empty()) { start_timer(fileno(STDIN), $sanity_time, "sanity-timer"); } # my $ptimer = undef; die "Empty timer queue: $!" unless ($pq->front(\$ptimer) == 1); # $mydelta = $ptimer->{expire} - $current_time; $mydelta = 0 if ($mydelta < 0); # my ($nf, $timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $mydelta); # # update current timers # $current_time = time(); # if ($timeleft <= 0) { $plog->log_vmin("Time expired ...\n"); # $ptimer = undef; while ($pq->dequeue(\$ptimer) != 0) { if ($ptimer->{expire} > $current_time) { $pq->enqueue($ptimer); last; } # my $fileno = $ptimer->{fileno}; my $pservice = $pfh_services->get($fileno); # &{$pservice->{timer_handler}}($ptimer, $pservice); $ptimer = undef; } } elsif ($nf > 0) { $plog->log_msg("NF, TIMELEFT ... (%d,%d)\n", $nf, $timeleft); my $pfhit = $pfh_services->iterator(); while (defined(my $fileno = $pfhit->())) { my $pfh = $pfh_services->get($fileno, 'fh'); my $pservice = $pfh_services->get($fileno); # if (vec($eout, $fileno, 1)) { # # EOF or some error # vec($rin, $fileno, 1) = 0; vec($ein, $fileno, 1) = 0; vec($win, $fileno, 1) = 0; # close($$pfh); # $plog->log_msg("closing socket (%d) for service %s ...\n", $fileno, $pservice->{name}); $pfh_services->deallocate($fileno); } elsif (vec($rout, $fileno, 1)) { # # ready for a read # $plog->log_msg("input available for %s ...\n", $pservice->{name}); # # call handler # &{$pservice->{io_handler}}($pservice); } } } } # $plog->log_msg("Event-loop done ...\n"); return SUCCESS; } # ################################################################ # # start execution # $plog->disable_stdout_buffering(); # my %opts; if (getopts('?hwWv:l:', \%opts) != 1) { usage($cmd); exit 2; } # foreach my $opt (%opts) { if (($opt eq 'h') or ($opt eq '?')) { usage($cmd); exit 0; } elsif ($opt eq 'w') { $plog->verbose(MINVERBOSE); } elsif ($opt eq 'W') { $plog->verbose(MIDVERBOSE); } elsif ($opt eq 'v') { if (!defined($plog->verbose($opts{$opt}))) { $plog->log_err("Invalid verbose level: $opts{$opt}\n"); usage($cmd); exit 2; } } elsif ($opt eq 'l') { $plog->logfile($opts{$opt}); $plog->log_msg("Log File: %s\n", $opts{$opt}); } } # # check if config file was given. # if (scalar(@ARGV) == 0) { # # use default config file. # $plog->log_msg("Using default config file: %s\n", $default_cfg_file); if (read_cfg_file($default_cfg_file) != SUCCESS) { $plog->log_err_exit("read_cfg_file failed. Done.\n"); } } else { # # read in config files and start up services. # foreach my $cfg_file (@ARGV) { $plog->log_msg("Reading config file %s ...\n", $cfg_file); if (read_cfg_file($cfg_file) != SUCCESS) { $plog->log_err_exit("read_cfg_file failed. Done.\n"); } } } # # create server sockets or pipes as needed. # if (create_server_connections() != SUCCESS) { $plog->log_err_exit("create_server_connections failed. Done.\n"); } # # monitor stdin for i/o with user. # add_stdin_to_services(); # # event loop to handle connections, etc. # if (run_event_loop() != SUCCESS) { $plog->log_err_exit("run_event_loop failed. Done.\n"); } # $plog->log_msg("All is well that ends well.\n"); # exit 0; __DATA__ #!/usr/bin/perl -w # use strict; # use Data::Dumper; # my $log_fh = *STDOUT; # use constant NOVERBOSE => 0; use constant MINVERBOSE => 1; use constant MIDVERBOSE => 2; use constant MAXVERBOSE => 3; # use constant FALSE => 0; use constant TRUE => 1; # my $verbose = NOVERBOSE; # my $pmsg = { root => { Header => { SystemName => 'OTHERSYSTEM', SystemVersion => 1.00, SessionId => 58628, CommandName => 'ProgramDataSend' }, ProgramDataSend => { Element => [ { Date => '2017/03/23,00:00:45', MCNo => 1, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, { Date => '2017/03/23,00:00:45', MCNo => 2, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, ] }, }, }; # sub pretty_print { my $var; foreach $var (@_) { my $level = -1; my %already_seen = (); if (ref ($var)) { print_ref(\%already_seen, \$level, $var); } else { print_scalar(\%already_seen, \$level, $var); } } } sub print_scalar { my $palready_seen = shift; my $plevel = shift; ++$$plevel; my $var = shift; print_indented($palready_seen, $plevel, $var); --$$plevel; } sub print_ref { my $palready_seen = shift; my $plevel = shift; my $r = shift; if (exists ($palready_seen->{$r})) { print_indented($palready_seen, $plevel, "$r (Seen earlier)"); return; } else { $palready_seen->{$r}=1; } my $ref_type = ref($r); if ($ref_type eq "ARRAY") { print_array($palready_seen, $plevel, $r); } elsif ($ref_type eq "SCALAR") { print "Ref -> $r"; print_scalar($palready_seen, $plevel, $$r); } elsif ($ref_type eq "HASH") { print_hash($palready_seen, $plevel, $r); } elsif ($ref_type eq "REF") { ++$$plevel; print_indented($palready_seen, $plevel, "Ref -> ($r)"); print_ref($palready_seen, $plevel, $$r); --$$plevel; } else { print_indented($palready_seen, $plevel, "$ref_type (not supported)"); } } sub print_array { my $palready_seen = shift; my $plevel = shift; my ($r_array) = @_; ++$$plevel; print_indented($palready_seen, $plevel, "[ # $r_array"); foreach my $var (@$r_array) { if (ref ($var)) { print_ref($palready_seen, $plevel, $var); } else { print_scalar($palready_seen, $plevel, $var); } } print_indented($palready_seen, $plevel, "]"); --$$plevel; } sub print_hash { my $palready_seen = shift; my $plevel = shift; my($r_hash) = @_; my($key, $val); ++$$plevel; print_indented($palready_seen, $plevel, "{ # $r_hash"); while (($key, $val) = each %$r_hash) { $val = ($val ? $val : '""'); ++$$plevel; if (ref ($val)) { print_indented($palready_seen, $plevel, "$key => "); print_ref($palready_seen, $plevel, $val); } else { print_indented($palready_seen, $plevel, "$key => $val"); } --$$plevel; } print_indented($palready_seen, $plevel, "}"); --$$plevel; } sub print_indented { my $palready_seen = shift; my $plevel = shift; my $spaces = ": " x $$plevel; print "${spaces}$_[0]\n"; } # sub to_xml { my ($ptree, $pxml, $last_element) = @_; # my $ref_type = ref($ptree); # if ($ref_type eq "ARRAY") { my $imax = scalar(@{$ptree}); # for (my $i=0; $i<$imax; ++$i) { $$pxml .= "<$last_element>" if ($i > 0); to_xml($ptree->[$i], $pxml, $last_element); $$pxml .= "</$last_element>" if ($i < ($imax-1)); } } elsif ($ref_type eq "HASH") { foreach my $element ( sort keys %{$ptree} ) { $$pxml .= "<$element>"; to_xml($ptree->{$element}, $pxml, $element); $$pxml .= "</$element>"; } } else { $$pxml .= "$ptree"; } } # sub msg_to_xml { my ($ptree) = @_; # my $xml = '<?xml version="1.0" encoding="UTF-8"?>'; my $last_element = ""; to_xml($ptree, \$xml, $last_element); # return $xml; } # sub accept_token { my ($ptokens, $pidx, $lnno) = @_; # $$pidx += 1; } # sub is_end_tag { my $self = shift; my ($start_tag, $token) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); # my $last_element = scalar(@{$proot})-1; $proot = $proot->[$last_element]->{SIBLINGS}; } else { element_xml($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if (is_end_tag($tag_name, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); } else { printf "%d; MISSING END TAG : <%s,%s>\n", __LINE__, $tag_name, $token; accept_token($ptokens, $pidx, __LINE__); } } elsif ($token =~ m/^<\/[^>]+>$/) { if (is_end_tag($first_start_tag, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { printf "%d: UNEXPECTED END TAG : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); } } else { printf "%d: UNEXPECTED TOKEN : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); } } } # sub start_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { accept_token($ptokens, $pidx, __LINE__); element_xml($ptokens, $pidx, $maxtoken, $proot); } else { printf "ERROR: NOT XML 1.0 DOC: <%s>\n", $token; } # return($proot); } # sub xml_to_msg { my ($xml_rec) = @_; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; # printf $log_fh "\n%d: DEBUG - TOKENS: \n\t%s\n", __LINE__, join("\n\t", @tokens) if ($verbose >= MINVERBOSE); # start_xml(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } # printf "\n%d: DUMPER Original msg = %s\n", __LINE__, Dumper($pmsg); printf "\n%d: PP Original msg =\n", __LINE__; pretty_print($pmsg); # my $xml = msg_to_xml($pmsg); printf "\n%d: XML msg = %s\n", __LINE__, $xml; # my $pmsg2 = xml_to_msg($xml); printf "\n%d: DUMPER XML-converted msg = %s\n", __LINE__, Dumper($pmsg2); printf "\n%d: XML-converted PP deparsed msg =\n", __LINE__; pretty_print($pmsg2); # exit 0; __DATA__ #!/usr/bin/perl -w # use strict; # use Data::Dumper; # my $log_fh = *STDOUT; # use constant NOVERBOSE => 0; use constant MINVERBOSE => 1; use constant MIDVERBOSE => 2; use constant MAXVERBOSE => 3; # my $verbose = NOVERBOSE; # my $pmsg = { root => { Header => { SystemName => 'OTHERSYSTEM', SystemVersion => 1.00, SessionId => 58628, CommandName => 'ProgramDataSend' }, ProgramDataSend => { Element => [ { Date => '2017/03/23,00:00:45', MCNo => 1, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, { Date => '2017/03/23,00:00:45', MCNo => 2, Stage => 1, Lane => 1, MjsFileName => 'CO3', MjsGroupName => '1', LotName => 'NPMW-C1', LotNumber => 1, LotName2 => '', LotNumber2 => 0, Rev => 1 }, ] }, }, }; # # my $pmsg2 = # { # root => [ # { # Header => [ # { SystemName => 'OTHERSYSTEM' }, # { SystemVersion => 1.00 }, # { SessionId => 58628 }, # { CommandName => 'ProgramDataSend' } # ] # }, # { # ProgramDataSend => [ # Element => [ # [ # { Data => '2017/03/23,00:00:45' }, # { MCNo => 1 }, # { Stage => 1 }, # { Lane => 1 }, # { MjsFileName => 'CO3' }, # { MjsGroupName => '1' }, # { LotName => 'NPMW-C1' }, # { LotNumber => 1 }, # { LotName2 => '' }, # { LotNumber2 => 0 }, # { Rev => 1 }, # ], # [ # { Data => '2017/03/23,00:00:45' }, # { MCNo => 2 }, # { Stage => 1 }, # { Lane => 1 }, # { MjsFileName => 'CO3' }, # { MjsGroupName => '1' }, # { LotName => 'NPMW-C1' }, # { LotNumber => 1 }, # { LotName2 => '' }, # { LotNumber2 => 0 }, # { Rev => 1 }, # ], # ], # ] # }, # ], # }; # sub pretty_print { my $var; foreach $var (@_) { my $level = -1; my %already_seen = (); if (ref ($var)) { print_ref(\%already_seen, \$level, $var); } else { print_scalar(\%already_seen, \$level, $var); } } } sub print_scalar { my $palready_seen = shift; my $plevel = shift; ++$$plevel; my $var = shift; print_indented($palready_seen, $plevel, $var); --$$plevel; } sub print_ref { my $palready_seen = shift; my $plevel = shift; my $r = shift; if (exists ($palready_seen->{$r})) { print_indented($palready_seen, $plevel, "$r (Seen earlier)"); return; } else { $palready_seen->{$r}=1; } my $ref_type = ref($r); if ($ref_type eq "ARRAY") { print_array($palready_seen, $plevel, $r); } elsif ($ref_type eq "SCALAR") { print "Ref -> $r"; print_scalar($palready_seen, $plevel, $$r); } elsif ($ref_type eq "HASH") { print_hash($palready_seen, $plevel, $r); } elsif ($ref_type eq "REF") { ++$$plevel; print_indented($palready_seen, $plevel, "Ref -> ($r)"); print_ref($palready_seen, $plevel, $$r); --$$plevel; } else { print_indented($palready_seen, $plevel, "$ref_type (not supported)"); } } sub print_array { my $palready_seen = shift; my $plevel = shift; my ($r_array) = @_; ++$$plevel; print_indented($palready_seen, $plevel, "[ # $r_array"); foreach my $var (@$r_array) { if (ref ($var)) { print_ref($palready_seen, $plevel, $var); } else { print_scalar($palready_seen, $plevel, $var); } } print_indented($palready_seen, $plevel, "]"); --$$plevel; } sub print_hash { my $palready_seen = shift; my $plevel = shift; my($r_hash) = @_; my($key, $val); ++$$plevel; print_indented($palready_seen, $plevel, "{ # $r_hash"); while (($key, $val) = each %$r_hash) { $val = ($val ? $val : '""'); ++$$plevel; if (ref ($val)) { print_indented($palready_seen, $plevel, "$key => "); print_ref($palready_seen, $plevel, $val); } else { print_indented($palready_seen, $plevel, "$key => $val"); } --$$plevel; } print_indented($palready_seen, $plevel, "}"); --$$plevel; } sub print_indented { my $palready_seen = shift; my $plevel = shift; my $spaces = ": " x $$plevel; print "${spaces}$_[0]\n"; } # sub to_xml { my ($ptree, $pxml, $last_element) = @_; # my $ref_type = ref($ptree); # if ($ref_type eq "ARRAY") { for (my $i=0; $i<scalar(@{$ptree}); ++$i) { $$pxml .= " <$last_element> "; to_xml($ptree->[$i], $pxml, $last_element); $$pxml .= " </$last_element> "; } } elsif ($ref_type eq "HASH") { foreach my $element ( sort keys %{$ptree} ) { $$pxml .= " <$element> " unless (ref($ptree->{$element}) eq "ARRAY"); to_xml($ptree->{$element}, $pxml, $element); $$pxml .= " </$element> " unless (ref($ptree->{$element}) eq "ARRAY"); } } else { $$pxml .= " $ptree "; } } # sub to_xml2 { my ($ptree, $pxml, $last_element) = @_; # my $ref_type = ref($ptree); # if ($ref_type eq "ARRAY") { my $imax = scalar(@{$ptree}); # for (my $i=0; $i<$imax; ++$i) { $$pxml .= "<$last_element>" if ($i > 0); to_xml2($ptree->[$i], $pxml, $last_element); $$pxml .= "</$last_element>" if ($i < ($imax-1)); } } elsif ($ref_type eq "HASH") { foreach my $element ( sort keys %{$ptree} ) { $$pxml .= "<$element>"; to_xml2($ptree->{$element}, $pxml, $element); $$pxml .= "</$element>"; } } else { $$pxml .= "$ptree"; } } # sub convert_to_xml { my ($ptree) = @_; # my $xml = '<?xml version="1.0" encoding="UTF-8"?>'; my $last_element = ""; to_xml($ptree, \$xml, $last_element); # return $xml; } # sub convert_to_xml2 { my ($ptree) = @_; # my $xml = '<?xml version="1.0" encoding="UTF-8"?>'; my $last_element = ""; to_xml2($ptree, \$xml, $last_element); # return $xml; } # printf "\n%d: DUMPER msg = %s\n", __LINE__, Dumper($pmsg); # printf "\n%d: DUMPER msg2 = %s\n", __LINE__, Dumper($pmsg2); # printf "\n%d: PP msg =\n", __LINE__; pretty_print($pmsg); # printf "\n%d: PP msg2 =\n", __LINE__; # pretty_print($pmsg2); # printf "\n%d: XML msg = %s\n", __LINE__, convert_to_xml($pmsg); printf "\n%d: XML2 msg = %s\n", __LINE__, convert_to_xml2($pmsg); # printf "\n%d: XML msg2 = %s\n", __LINE__, convert_to_xml($pmsg2); # exit 0; #!/usr/bin/perl -w ###################################################################### # # trace XML msg flow in a PanaCIM log file. typical examples are # log files for LNB CVT, LNB MI and LNB LM. # ###################################################################### # use strict; # use Carp; use Getopt::Std; use File::Find; use File::Path qw(mkpath); use File::Basename; use File::Path 'rmtree'; use XML::Simple; use Data::Dumper; # ###################################################################### # # logical constants # use constant TRUE => 1; use constant FALSE => 0; # use constant SUCCESS => 1; use constant FAIL => 0; # # verbose levels # use constant NOVERBOSE => 0; use constant MINVERBOSE => 1; use constant MIDVERBOSE => 2; use constant MAXVERBOSE => 3; # # message types # use constant NO_MSGS => 0; use constant XML_MSGS => 1; use constant PM_MSGS => 2; use constant ALL_MSGS => 3; # # comparison types # use constant NOT_A_DATE => -2; use constant BEFORE_WINDOW => -1; use constant IN_WINDOW => 0; use constant AFTER_WINDOW => +1; # ###################################################################### # # globals # my $cmd = $0; my $log_fh = *STDOUT; # my $xml = new XML::Simple(ForceArray => 1); my $xml = new XML::Simple(); my $full_trace = TRUE; my $print_raw = FALSE; my $print_raw_record = FALSE; my $trace_msg_type = XML_MSGS; my $use_private_parser = FALSE; my $do_deparse_xml = FALSE; my $start_date = ""; my $end_date = ""; my $last_date = ""; my $exit_upon_enddate = FALSE; # # cmd line options # my $logfile = ''; my $verbose = NOVERBOSE; # my %verbose_levels = ( off => NOVERBOSE(), min => MINVERBOSE(), mid => MIDVERBOSE(), max => MAXVERBOSE() ); # my %trace_msg_types = ( none => NO_MSGS(), xml => XML_MSGS(), pm => PM_MSGS(), all => ALL_MSGS() ); # my %xml_tally = ( ); my %pm_tally = ( ); my %total_xml_tally = ( TOTAL_MSGS => 0 ); my %total_pm_tally = ( TOTAL_MSGS => 0 ); # ###################################################################### # # miscellaneous functions # sub usage { my ($arg0) = @_; print $log_fh <<EOF; usage: $arg0 [-?] [-h] \\ [-w | -W |-v level] \\ [-l logfile] \\ [-t | -T] [-R] [-r] \\ [-P xml|pm|all] [-p] [-d] \\ [-S yyyymmddhhmmss] [-E yyyymmddhhmmss] [-x] \\ [-X yyyymmddhhmmss] \\ panacim-log-file ... where: -? or -h - print this usage. -w - enable warning (level=min=1). -W - enable warning and trace (level=mid=2). -v - verbose level: 0=off,1=min,2=mid,3=max. -l logfile - log file path to a separate file. -t - simple trace, only message command name is listed. -T - full trace and translation of messages (default). -R - list raw message also. -r - print raw record as read from file. -P xml|pm|all - type of message to trace (XML=default). -p - use private parser, if available (only XML for now). -d - deparse, that is, generate XML from XML parse tree generated by private parser (-p option). -S yyyymmddhhmmss - start date/time for parsing -E yyyymmddhhmmss - end date/time for parsing -x - exit when end date/time is exceeded. -X yyyymmddhhmmss - exact date/time for parsing EOF } # sub ftrace { my @data = @_; # return if ($verbose < MAXVERBOSE); # if (scalar(@data) == 1) { printf $log_fh "\n%d: DEBUG TRACE\n", $data[0]; } elsif (scalar(@data) == 2) { printf $log_fh "\n%d: DEBUG TRACE: %s\n", $data[0], $data[1]; } } # sub tally_ho { my ($ptally, $ptotals, $name) = @_; # if (exists($ptally->{$name})) { $ptally->{$name} += 1; } else { $ptally->{$name} = 1; } if (exists($ptotals->{$name})) { $ptotals->{$name} += 1; } else { $ptotals->{$name} = 1; } $ptotals->{TOTAL_MSGS} += 1; } # sub pm_tally_ho { my ($name) = @_; # tally_ho(\%pm_tally, \%total_pm_tally, $name); } # sub xml_tally_ho { my ($name) = @_; # tally_ho(\%xml_tally, \%total_xml_tally, $name); } # sub init_tally { %pm_tally = ( ); %xml_tally = ( ); } # sub print_file_tally { printf $log_fh "\n%d: XML MSG TALLY:\n", __LINE__; printf $log_fh "$_ = $xml_tally{$_}\n" for sort keys %xml_tally; # printf $log_fh "\n%d: PM MSG TALLY:\n", __LINE__; printf $log_fh "$_ = $pm_tally{$_}\n" for sort keys %pm_tally; } # sub print_total_tally { printf $log_fh "\n%d: TOTAL XML MSG TALLY:\n", __LINE__; printf $log_fh "$_ = $total_xml_tally{$_}\n" for sort keys %total_xml_tally; # printf $log_fh "\n%d: TOTAL PM MSG TALLY:\n", __LINE__; printf $log_fh "$_ = $total_pm_tally{$_}\n" for sort keys %total_pm_tally; } # ###################################################################### # # read in PanaCIM log file and filter out XML messages to and from LNB. # sub print_pm { my ($post_raw_nl, $tstamp, $label, $msg_src, $msg_dest, $msg_class, $msg_type, $rec) = @_; ftrace(__LINE__); # pm_tally_ho($msg_class . '::' . $msg_type); # if ($full_trace == TRUE) { $rec =~ m/^.*(MessageSource\s*=\s[^\s]+\s*,\s*MessageDestination\s*=\s*[^\s]+.*)$/; my $pm_rec = $1; # printf $log_fh "%d: %s %s - (src,dst,cls,type) = (%s,%s,%s,%s)\n\t%s\n", __LINE__, $tstamp, $label, $msg_src, $msg_dest, $msg_class, $msg_type, join("\n\t", split(",", $pm_rec)); } else { printf $log_fh "%d: %s %s - (src,dst,cls,type) = (%s,%s,%s,%s)\n", __LINE__, $tstamp, $label, $msg_src, $msg_dest, $msg_class, $msg_type; } } # sub process_pm { my ($post_raw_nl, $tstamp, $rec) = @_; ftrace(__LINE__); # my $done = FALSE; # if ($rec =~ m/\t([^\s]+)\s*,\s*MessageSource\s*=\s([^\s]+)\s*,\s*MessageDestination\s*=\s*([^\s]+)\s*,\s*MessageClass\s*=\s*([^\s]+)\s*,\s*MessageType\s*=\s*([^\s]+)/) { my $label = $1; my $msg_src = $2; my $msg_dest = $3; my $msg_class = $4; my $msg_type = $5; # printf $log_fh "\n%d: %s %s - %s\n", __LINE__, $tstamp, $label, $rec if ($print_raw == TRUE); # print_pm($post_raw_nl, $tstamp, $label, $msg_src, $msg_dest, $msg_class, $msg_type, $rec); # $done = TRUE; } # return($done); } # sub start_get_value { my ($ptree, $search_name, $pvalue, $pdone) = @_; ftrace(__LINE__); # if (ref($ptree) eq "ARRAY") { for (my $i=0; ($$pdone == FALSE) && ($i<scalar(@{$ptree})); ++$i) { my $name = $ptree->[$i]->{NAME}; if ($search_name eq $name) { if (defined($ptree->[$i]->{VALUE})) { $$pvalue = $ptree->[$i]->{VALUE}; } else { $$pvalue = ""; } $$pdone = TRUE; } elsif (scalar(@{$ptree->[$i]->{SIBLINGS}}) > 0) { start_get_value($ptree->[$i]->{SIBLINGS}, $search_name, $pvalue, $pdone); } } } else { printf $log_fh "\n%d: ERROR - EXPECTING ARRAY REF: <%s>\n", __LINE__, ref($ptree); $$pdone = TRUE; } } # sub get_value { my ($ptree, $search_name) = @_; ftrace(__LINE__); # my $value = "UNKNOWN"; my $done = FALSE; # start_get_value($ptree, $search_name, \$value, \$done); # return($value); } # sub print_xml { my($post_raw_nl, $label, $tstamp, $pbooklist) = @_; ftrace(__LINE__); # if ($full_trace == TRUE) { my $cmdnm = ''; if ($use_private_parser == TRUE) { $cmdnm = get_value($pbooklist, "<CommandName>"); xml_tally_ho($cmdnm); } else { $cmdnm = $pbooklist->{'Header'}->{'CommandName'}; xml_tally_ho($pbooklist->{'Header'}->{'CommandName'}); } printf $log_fh "%d: %s %s - %s - %s\n", __LINE__, $tstamp, $label, $cmdnm, Dumper($pbooklist); } elsif ($use_private_parser == TRUE) { my $cmdnm = get_value($pbooklist, "<CommandName>"); xml_tally_ho($cmdnm); printf $log_fh "%s%d: %s %s - %s\n", $post_raw_nl, __LINE__, $tstamp, $label, $cmdnm; } else { xml_tally_ho($pbooklist->{'Header'}->{'CommandName'}); printf $log_fh "%s%d: %s %s - %s\n", $post_raw_nl, __LINE__, $tstamp, $label, $pbooklist->{'Header'}->{'CommandName'}; } } # sub accept_token { my ($ptokens, $pidx, $lnno) = @_; ftrace(__LINE__); # printf $log_fh "\n%d: DEBUG - ACCEPTING TOKEN AT %d: %s\n", __LINE__, $lnno, $ptokens->[$$pidx] if ($verbose >= MIDVERBOSE); $$pidx += 1; } # sub is_end_tag { my ($start_tag, $token) = @_; ftrace(__LINE__); # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; ftrace(__LINE__); # printf $log_fh "\n%d: DEBUG - ENTRY: (%s,%s,%s,%s)\n", __LINE__, $ptokens, $pidx, $maxtoken, $proot if ($verbose >= MIDVERBOSE); # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); # my $last_element = scalar(@{$proot})-1; $proot = $proot->[$last_element]->{SIBLINGS}; } else { my $last_element = scalar(@{$proot})-1; element_xml($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; accept_token($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if (is_end_tag($tag_name, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); } else { printf $log_fh "\n%d: ERROR - MISSING END TAG : <%s,%s>\n", __LINE__, $tag_name, $token; accept_token($ptokens, $pidx, __LINE__); } } elsif ($token =~ m/^<\/[^>]+>$/) { if (is_end_tag($first_start_tag, $token) == TRUE) { accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { printf $log_fh "\n%d: ERROR - UNEXPECTED END TAG : <%s>\n", __LINE__, $token; } } else { printf $log_fh "\n%d: ERROR - UNEXPECTED TOKEN : <%s>\n", __LINE__, $token; accept_token($ptokens, $pidx, __LINE__); } } } # sub start_xml { my ($ptokens, $pidx, $maxtoken, $proot) = @_; ftrace(__LINE__); # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { accept_token($ptokens, $pidx, __LINE__); element_xml($ptokens, $pidx, $maxtoken, $proot); } else { printf $log_fh "\n%d: ERROR - NOT XML 1.0 DOC: <%s>\n", __LINE__, $token; } # return($proot); } # sub parse_xml { my ($xml_rec) = @_; ftrace(__LINE__); # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; # printf $log_fh "\n%d: DEBUG - TOKENS: \n\t%s\n", __LINE__, join("\n\t", @tokens) if ($verbose >= MINVERBOSE); # start_xml(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } # sub end_tag { my ($start_tag) = @_; ftrace(__LINE__); # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; return($end_tag); } # sub deparse_start_xml { my ($ptree, $pxstr) = @_; ftrace(__LINE__); # if (ref($ptree) eq "ARRAY") { for (my $i=0; $i<scalar(@{$ptree}); ++$i) { my $name = $ptree->[$i]->{NAME}; # if (scalar(@{$ptree->[$i]->{SIBLINGS}}) > 0) { printf $log_fh "\n%d: %s\n", __LINE__, $name if ($verbose >= MINVERBOSE); $$pxstr .= $name; deparse_start_xml($ptree->[$i]->{SIBLINGS}, $pxstr); printf $log_fh "\n%d: %s\n", __LINE__, end_tag($name) if ($verbose >= MINVERBOSE); $$pxstr .= end_tag($name); } elsif (defined($ptree->[$i]->{VALUE})) { my $value = $ptree->[$i]->{VALUE}; printf $log_fh "\n%d: %s%s%s\n", __LINE__, $name, $value, end_tag($name) if ($verbose >= MINVERBOSE); $$pxstr .= $name . $value . end_tag($name); } else { my $value = $ptree->[$i]->{VALUE}; printf $log_fh "\n%d: %s%s\n", __LINE__, $name, end_tag($name) if ($verbose >= MINVERBOSE); $$pxstr .= $name . end_tag($name); } } } else { printf $log_fh "\n%d: ERROR - EXPECTING ARRAY REF: <%s>\n", __LINE__, ref($ptree); } } # sub deparse_xml { my ($ptree, $tstamp) = @_; ftrace(__LINE__); # printf $log_fh "\n%d: DEPARSE START:\n", __LINE__; # my $xml_string = '<?xml version="1.0" encoding="UTF-8"?>'; deparse_start_xml($ptree, \$xml_string); # printf $log_fh "\n%d: %s DEPARSE XML STRING: %s\n", __LINE__, $tstamp, $xml_string; } # sub process_xml { my ($post_raw_nl, $tstamp, $rec) = @_; ftrace(__LINE__, $rec); # my $done = FALSE; my $booklist = undef; # if ($rec =~ m/\tDATA OUT:\s*(.*)$/) { my $do_rec = $1; printf $log_fh "\n%d: %s PanaCIM ==>> LNB - %s\n", __LINE__, $tstamp, $do_rec if ($print_raw == TRUE); # if ($use_private_parser == TRUE) { $booklist = parse_xml($do_rec); } else { $booklist = $xml->XMLin($do_rec); } # print_xml($post_raw_nl, "PanaCIM ==>> LNB", $tstamp, $booklist); $done = TRUE; } elsif ($rec =~ m/\tDATA IN:\s*(.*)$/) { my $di_rec = $1; printf $log_fh "\n%d: %s PanaCIM <<== LNB - %s\n", __LINE__, $tstamp, $di_rec if ($print_raw == TRUE); # if ($use_private_parser == TRUE) { $booklist = parse_xml($di_rec); } else { $booklist = $xml->XMLin($di_rec); } # print_xml($post_raw_nl, "PanaCIM <<== LNB", $tstamp, $booklist); $done = TRUE; } # deparse_xml($booklist, $tstamp) if (($do_deparse_xml == TRUE) && ($use_private_parser == TRUE) && ($done == TRUE)); # $booklist = undef; # return($done); } # sub process_other { my ($post_raw_nl, $tstamp, $rec) = @_; ftrace(__LINE__); # my $done = FALSE; # if ($rec =~ m/(STARTING INFO LOGGING)/) { my $start_rec = $1; printf $log_fh "%d: %s PROCESS STARTUP - %s\n", __LINE__, $tstamp, $start_rec; } # return($done); } # sub process_rec { my($post_raw_nl, $rec, $tstamp) = @_; ftrace(__LINE__, $rec); # if (($trace_msg_type == XML_MSGS) || ($trace_msg_type == ALL_MSGS)) { ftrace(__LINE__); return if (process_xml($post_raw_nl, $tstamp, $rec) == TRUE); } if (($trace_msg_type == PM_MSGS) || ($trace_msg_type == ALL_MSGS)) { ftrace(__LINE__); return if (process_pm($post_raw_nl, $tstamp, $rec) == TRUE); } ftrace(__LINE__); process_other($post_raw_nl, $tstamp, $rec); } # # use constant BEFORE_WINDOW => -1; # use constant IN_WINDOW => 0; # use constant AFTER_WINDOW => +1; # sub date_filter { my ($rec, $ptstamp) = @_; ftrace(__LINE__); # if ($rec !~ m/\t\d\d\d\d\/\d\d\/\d\d \d\d:\d\d:\d\d.\d\d\d\t/) { # does not contain a date. skip it. return NOT_A_DATE; } # my @data = split("\t", $rec, 3); # $$ptstamp = $data[1]; $$ptstamp =~ s?[ /:]??g; $$ptstamp = substr $$ptstamp, 0, 14; # $last_date = $$ptstamp; # if ($verbose < MIDVERBOSE) { return BEFORE_WINDOW if (($start_date ne "") && ($start_date gt $$ptstamp)); return AFTER_WINDOW if (($end_date ne "") && ($end_date lt $$ptstamp)); return IN_WINDOW; } elsif (($start_date ne "") && ($start_date gt $$ptstamp)) { printf $log_fh "\n%d: DEBUG - START DATE TEST - RETURN FALSE (%s,%s)\n", __LINE__, $start_date, $$ptstamp; return BEFORE_WINDOW; } elsif (($end_date ne "") && ($end_date lt $$ptstamp)) { printf $log_fh "\n%d: DEBUG - END DATE TEST - RETURN FALSE (%s,%s)\n", __LINE__, $end_date, $$ptstamp; return AFTER_WINDOW; } else { printf $log_fh "\n%d: DEBUG - DATE TEST - RETURN TRUE (%s)\n", __LINE__, $$ptstamp; return IN_WINDOW; } } # sub is_xml_start { my ($rec) = @_; # if ($rec =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/i) { return TRUE; } else { return FALSE; } } # sub process_xml_block { my ($post_raw_nl, $infh, $rec, $tstamp) = @_; ftrace(__LINE__); # my @recs = (); # push @recs, $rec; # my $done = FALSE; my $first_start_tag = ""; my $first_end_tag = ""; # while (($done == FALSE) && ($rec = <$infh>)) { $rec =~ s/\r*\n$//; # if (($first_start_tag eq "") && ($rec =~ m/^<([^\/>\s]+)/)) { $first_start_tag = "<" . ${1} . ">"; $first_end_tag = end_tag($first_start_tag); } elsif ($rec =~ m/$first_end_tag/) { $done = TRUE; } # push @recs, $rec; } # printf $log_fh "\n%d: XML block: \n\t%s\n", __LINE__, join("\n\t", @recs) if ($verbose >= MINVERBOSE); } # sub process_file { my ($log_file) = @_; ftrace(__LINE__); # printf $log_fh "\n%d: START PROCESSING PanaCIM LOG FILE: %s\n\n", __LINE__, $log_file; # init_tally(); open(my $infh, "<", $log_file) || die $!; # my $post_raw_nl = ''; $post_raw_nl = "\n" if ($print_raw == TRUE); # while (my $rec = <$infh>) { $rec =~ s/\r*\n$//; # printf $log_fh "%d: Raw File Record: %s\n", __LINE__, $rec if ($print_raw_record == TRUE); # my $tstamp = ""; my $result = date_filter($rec, \$tstamp); if ($result == IN_WINDOW) { process_rec($post_raw_nl, $rec, $tstamp); } elsif (($exit_upon_enddate == TRUE) && ($result == AFTER_WINDOW)) { printf $log_fh "\n%d: Exiting processing loop at: %s\n", __LINE__, $tstamp; last; } elsif ($result == NOT_A_DATE) { if (is_xml_start($rec) == TRUE) { # we have the start of a multiline xml block. process_xml_block($post_raw_nl, $infh, $rec, $last_date); } } } # close($infh); # print_file_tally(); # return; } # ###################################################################### # # usage: $arg0 [-?] [-h] \\ # [-w | -W |-v level] \\ # [-l logfile] \\ # [-t | -T] [-R] \\ # [-P xml|pm|all] [-p] [-d] \\ # my %opts; if (getopts('?hwWv:l:tTRrP:pdS:E:X:x', \%opts) != 1) { usage($cmd); exit 2; } # foreach my $opt (keys %opts) { printf "\n%d: Option: $opt, $opts{$opt}\n", __LINE__; # if (($opt eq 'h') or ($opt eq '?')) { usage($cmd); exit 0; } elsif ($opt eq 'x') { $exit_upon_enddate = TRUE; } elsif ($opt eq 'w') { $verbose = MINVERBOSE; } elsif ($opt eq 'W') { $verbose = MIDVERBOSE; } elsif ($opt eq 't') { $full_trace = FALSE; } elsif ($opt eq 'T') { $full_trace = TRUE; } elsif ($opt eq 'r') { $print_raw_record = TRUE; } elsif ($opt eq 'R') { $print_raw = TRUE; } elsif ($opt eq 'p') { $use_private_parser = TRUE; } elsif ($opt eq 'd') { $do_deparse_xml = TRUE; } elsif ($opt eq 'P') { if ($opts{$opt} =~ m/^[0123]$/) { $trace_msg_type = $opts{$opt}; } elsif (exists($trace_msg_types{$opts{$opt}})) { $trace_msg_type = $trace_msg_types{$opts{$opt}}; } else { printf $log_fh "\n%d: Invalid message type: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } } elsif ($opt eq 'v') { if ($opts{$opt} =~ m/^[0123]$/) { $verbose = $opts{$opt}; } elsif (exists($verbose_levels{$opts{$opt}})) { $verbose = $verbose_levels{$opts{$opt}}; } else { printf $log_fh "\n%d: Invalid verbose level: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } } elsif ($opt eq 'X') { if ($opts{$opt} =~ m/^(19|20)\d\d(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[01])(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]$/) { $start_date = $opts{$opt}; $end_date = $opts{$opt}; } else { printf $log_fh "\n%d: Invalid exact date: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } printf $log_fh "\n%d: exact date: $opts{$opt}\n", __LINE__; } elsif ($opt eq 'S') { if ($opts{$opt} =~ m/^(19|20)\d\d(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[01])(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]$/) { $start_date = $opts{$opt}; } else { printf $log_fh "\n%d: Invalid start date: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } printf $log_fh "\n%d: start date: $opts{$opt}\n", __LINE__; } elsif ($opt eq 'E') { if ($opts{$opt} =~ m/^(19|20)\d\d(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[01])(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]$/) { $end_date = $opts{$opt}; } else { printf $log_fh "\n%d: Invalid end date: $opts{$opt}\n", __LINE__; usage($cmd); exit 2; } printf $log_fh "\n%d: end date: $opts{$opt}\n", __LINE__; } elsif ($opt eq 'l') { local *FH; $logfile = $opts{$opt}; open(FH, '>', $logfile) or die $!; $log_fh = *FH; printf $log_fh "\n%d: Log File: %s\n", __LINE__, $logfile; } } # if (($start_date ne "") && ($end_date ne "") && ($start_date gt $end_date)) { printf $log_fh "%d: ERROR - start date after end date.\n(%s > %s)\n", __LINE__, $start_date, $end_date; exit 2; } # if ( -t STDIN ) { # # getting a list of files from command line. # if (scalar(@ARGV) == 0) { printf $log_fh "%d: ERROR - No log files given.\n", __LINE__; usage($cmd); exit 2; } # foreach my $panacim_log_file (@ARGV) { process_file($panacim_log_file); } print_total_tally(); # } else { printf $log_fh "%d: Reading STDIN for list of files ...\n", __LINE__; # while ( defined(my $panacim_log_file = <STDIN>) ) { chomp($panacim_log_file); process_file($panacim_log_file); } print_total_tally(); } # exit 0; # parsing LNB-style XML messages # package mylnbxml; # use myconstants; # sub new { my $class = shift; my $self = {}; # $self->{booklist} = undef; $self->{xml} = undef; $self->{deparse_xml} = undef; $self->{logger} = undef; $self->{errors} = 0; # $self->{xml} = shift if @_; $self->{logger} = shift if @_; # bless $self, $class; # return($self); } # sub xml { my $self = shift; # if (@_) { $self->{xml} = shift; $self->{booklist} = undef; $self->{deparse_xml} = undef; $self->{errors} = 0; } # return($self->{xml}); } # sub booklist { my $self = shift; # return($self->{booklist}); } # # sub errors { my $self = shift; # return($self->{errors}); } # sub accept_token { my $self = shift; my ($ptokens, $pidx, $lnno) = @_; # $$pidx += 1; } # sub is_end_tag { my $self = shift; my ($start_tag, $token) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # if ($token eq $end_tag) { return TRUE; } else { return FALSE; } } # sub element_xml { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $done = FALSE; my $first_start_tag = ""; # while (($$pidx < $maxtoken) && ($done == FALSE)) { my $token = $ptokens->[$$pidx]; # if ($token =~ m/^<[^\/>]+>$/) { # a start tag alone if ($first_start_tag eq "") { $first_start_tag = $token; # push @{$proot}, { NAME => $token, VALUE => undef, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token($ptokens, $pidx, __LINE__); # my $last_element = scalar(@{$proot})-1; $proot = $proot->[$last_element]->{SIBLINGS}; } else { $self->element_xml($ptokens, $pidx, $maxtoken, $proot); } } elsif ($token =~ m/^(<[^\/>]+>)(.+)$/) { # a start tag with a value my $tag_name = $1; my $tag_value = $2; push @{$proot}, { NAME => $tag_name, VALUE => $tag_value, ATTRIBUTES => [], SIBLINGS => [] }; $self->accept_token($ptokens, $pidx, __LINE__); $token = $ptokens->[$$pidx]; if ($self->is_end_tag($tag_name, $token) == TRUE) { $self->accept_token($ptokens, $pidx, __LINE__); } else { # printf "\n%d: ERROR - MISSING END TAG : <%s,%s>\n", # __LINE__, $tag_name, $token; $self->{errors} += 1; $self->{logger}->log_err("MISSING END TAG : <%s,%s>\n", $tag_name, $token); $self->accept_token($ptokens, $pidx, __LINE__); } } elsif ($token =~ m/^<\/[^>]+>$/) { if ($self->is_end_tag($first_start_tag, $token) == TRUE) { $self->accept_token($ptokens, $pidx, __LINE__); $done = TRUE; } else { # printf "\n%d: ERROR - UNEXPECTED END TAG : <%s>\n", # __LINE__, $token; $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED END TAG : <%s>\n", $token); } } else { # printf "\n%d: ERROR - UNEXPECTED TOKEN : <%s>\n", __LINE__, $token; $self->{errors} += 1; $self->{logger}->log_err("UNEXPECTED TOKEN : <%s>\n", $token); $self->accept_token($ptokens, $pidx, __LINE__); } } } # sub start_xml { my $self = shift; my ($ptokens, $pidx, $maxtoken, $proot) = @_; # my $token = $ptokens->[$$pidx]; if ($token =~ m/<.xml\s+version="1.0"\s+encoding="UTF-8".>/) { $self->accept_token($ptokens, $pidx, __LINE__); $self->element_xml($ptokens, $pidx, $maxtoken, $proot); } else { # printf "\n%d: ERROR - NOT XML 1.0 DOC: <%s>\n", __LINE__, $token; $self->{errors} += 1; $self->{logger}->log_err("NOT XML 1.0 DOC: <%s>\n", $token); } # return($proot); } # sub parse_xml { my $self = shift; my ($xml_rec) = @_; # my $idx = 0; my @tokens = map { s/^/</; $_; } grep { ! /^\s*$/ } split("<", $xml_rec); my $proot = [ ]; # $self->start_xml(\@tokens, \$idx, scalar(@tokens), $proot); # return($proot); } # sub parse { my $self = shift; # $self->{booklist} = undef; $self->{deparse_xml} = undef; # if (defined($self->{xml})) { $self->{errors} = 0; $self->{booklist} = $self->parse_xml($self->{xml}); if ($self->{errors} > 0) { $self->{logger}->log_err("Parse failed.\n"); $self->{booklist} = undef; } } # return($self->{booklist}); } # sub end_tag { my $self = shift; my ($start_tag) = @_; # my $end_tag = $start_tag; $end_tag =~ s?^<?</?; # return($end_tag); } # sub deparse_start_xml { my $self = shift; my ($ptree, $pxstr) = @_; # if (ref($ptree) eq "ARRAY") { for (my $i=0; $i<scalar(@{$ptree}); ++$i) { my $name = $ptree->[$i]->{NAME}; # if (scalar(@{$ptree->[$i]->{SIBLINGS}}) > 0) { $$pxstr .= $name; $self->deparse_start_xml($ptree->[$i]->{SIBLINGS}, $pxstr); $$pxstr .= $self->end_tag($name); } elsif (defined($ptree->[$i]->{VALUE})) { my $value = $ptree->[$i]->{VALUE}; $$pxstr .= $name . $value . $self->end_tag($name); } else { my $value = $ptree->[$i]->{VALUE}; $$pxstr .= $name . $self->end_tag($name); } } } else { # printf $log_fh "\n%d: ERROR - EXPECTING ARRAY REF: <%s>\n", # __LINE__, ref($ptree); $self->{errors} += 1; $self->{logger}->log_err("EXPECTING ARRAY REF: <%s>\n", ref($ptree)); } } # sub deparse_xml { my $self = shift; my ($ptree) = @_; # my $xml_string = '<?xml version="1.0" encoding="UTF-8"?>'; $self->deparse_start_xml($ptree, \$xml_string); # return($xml_string); } # sub deparse { my $self = shift; # $self->{deparse_xml} = undef; # if (defined($self->{booklist})) { $self->{errors} = 0; $self->{deparse_xml} = $self->deparse_xml($self->{booklist}); if ($self->{errors} > 0) { $self->{logger}->log_err("Deparse failed.\n"); $self->{deparse_xml} = undef; } } # return($self->{deparse_xml}); } # # exit with success # 1; #!/usr/bin/perl # use strict; use XML::Simple; # my $depth = 0; my $verbose = 0; # sub read_file { my ($infile, $pdata) = @_; # # is file readable? # if ( ! -r $infile ) { printf "ERROR: file $infile is NOT readable\n"; exit -1; } # # read in file # unless (open(INFD, $infile)) { printf "ERROR: unable to open $infile.\n"; exit -1; } my @buf = <INFD>; close(INFD); # # return data. # unshift @{$pdata}, @buf; # return; } # sub traverse { my ($p, $pdl) = @_; # $depth += 1; my $indent = (' ' x ($depth*2)); # if (ref($p) eq 'SCALAR') { print "${indent}SCALAR REF: $p\n"; } elsif (ref($p) eq 'ARRAY') { print "${indent}ARRAY REF: $p\n" if ($verbose); foreach my $element (@{$p}) { traverse($element, $pdl); } } elsif (ref($p) eq 'HASH') { print "${indent}HASH REF: $p\n" if ($verbose); foreach my $key (keys(%{$p})) { traverse($p->{$key}, $pdl); } } elsif (ref($p) eq 'CODE') { print "${indent}CODE REF: $p\n" if ($verbose); } elsif (ref($p) eq 'REF') { print "${indent}REF REF: $p\n" if ($verbose); } elsif (ref($p) eq 'GLOB') { print "${indent}GLOB REF: $p\n" if ($verbose); } elsif (ref($p) eq 'LVALUE') { print "${indent}LVALUE REF: $p\n" if ($verbose); } elsif (ref($p) eq 'FORMAT') { print "${indent}FORMAT REF: $p\n" if ($verbose); } elsif (ref($p) eq 'IO') { print "${indent}IO REF: $p\n" if ($verbose); } elsif (ref($p) eq 'VSTRING') { print "${indent}VSTRING REF: $p\n" if ($verbose); } elsif (ref($p) eq 'Regexp') { print "${indent}Regexp REF: $p\n" if ($verbose); } else { print "${indent}SCALAR: $p\n" if ($verbose); $$pdl += length($p); } # $depth -= 1; } # if ($#ARGV>=0) { if ($ARGV[0] eq '-v') { $verbose = 1; shift @ARGV; } } # foreach my $xml_file (@ARGV) { printf "\nProcessing XML file: %s\n", $xml_file; # my @raw_xml = (); read_file($xml_file, \@raw_xml); # my $xml = join '', @raw_xml; my $xml_length = length($xml); # my $ref = XMLin($xml); # my $data_length = 0; traverse($ref,\$data_length); # printf "XML Tags and Data length: %d\n", $xml_length; printf "Data length: %d\n", $data_length; printf "Percent Data/(Data+XML) = %6.2f%%\n", 100.0*($data_length/$xml_length); } # exit 0;
ombt/analytics
apex/testbin/mylnbsim/old/xxx.pl
Perl
mit
184,168
#!/usr/bin/perl # The MIT License (MIT) # Copyright (c) 2013 Matt Okeson-Harlow # 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. # wordpress comment spam cleanup use strict; use warnings; use English qw( -no_match_vars ); use Carp; use DBI; use Getopt::Long; use Term::ReadKey; # database settings # these can be set to your defaults to avoid having to enter them as cli # options. my $database = q{}; my $username = q{}; my $password = q{}; my $prefix = q{wp_}; my $ip_limit = 3; # how many times does an IP have to be listed to get banned # flags my $debug; my $ip_report; # print ip counts my $word_report; # print word counts my $tables; # print ip tables block my $delete; # do delete my $verbose; my $output = q{-}; my $output_fh; my %ip_list; my %word_list; my @delete_id; # process command line options my $options_ok = GetOptions( 'database=s' => \$database, 'username=s' => \$username, 'password=s' => \$password, 'prefix=s' => \$prefix, 'output=s' => \$output, 'limit=i' => \$ip_limit, 'ip' => \$ip_report, 'tables' => \$tables, 'delete' => \$delete, 'word' => \$word_report, 'verbose' => \$verbose, ); croak q{Username required.} if $username eq q{}; croak q{Database required.} if $database eq q{}; # setup our output filehandle if ( $output eq q{-} ) { $output_fh = \*STDOUT; } else { open $output_fh, '>', $output or croak qq{ERROR: $OS_ERROR}; } # if a password is not configured in the script and it is not specified on the # cli, prompt for one. if ( $password eq q{} ) { print {$output_fh} qq{Enter password for '$username' on '$database': }; ReadMode 'noecho'; $password = ReadLine 0; chomp $password; ReadMode 'normal'; } print {$output_fh} qq{\nWorking...\n}; # setup the database DSN for later my $dsn = qq{DBI:mysql:database=$database}; my $comment_table = $prefix . q{comments}; # words that will be checked against comment_author, comment_author_url, # comment_content # in vim, select the list, then :!sort my @banned_list = ( 'acyclovir', 'adderall', 'adipex', 'allegra', 'ambien', 'amoxicillin', 'ativan', 'carisoprodol', 'casino', 'celebrex', 'cialis', 'claritin', 'clomid', 'codiene', 'codeine', 'coumadin', 'crestor', 'diflucan', 'effexor', 'ephedra', 'ephedrine', 'erectile', 'femdom', 'fioricet', 'flexeril', 'flonase', 'forex', 'fuck', 'hoodia', 'hydrocodone', 'incest', 'ionamin', 'lamisil', 'lasix', 'lexapro', 'levitra', 'lipitor', 'lortab', 'mevacor', 'milf', 'morphine', 'nexium', 'nude', 'oxycodone', 'oxycontin', 'parishilton', 'paxil', 'percocet', 'plavix', 'porn', 'prevacid', 'prilosec', 'propecia', 'prozac', 'ringtone', 'ring tone', 'rolex', 'soma', 'tagamet', 'tamoxifen', 'tenuate', 'tramadol', 'tramal', 'ultram', 'valium', 'valtrex', 'viagra', 'vicodin', 'vioxx', 'wellbutrin', 'xanax', 'xxx', 'zithromax', 'zoloft', 'zyban', 'zyrtec', ); # regexp matches, use this for website url's mostly my @banned_regexp = ( '[.]cn/', 'quizilla[.]com', ); # setup the database connection my $dbh = DBI->connect($dsn,$username,$password) or croak qq{ERROR: $DBI::errstr}; # process the banned list # get the comment ID and IP address for my $word (@banned_list) { my $sql = qq{ select comment_ID,comment_author_IP from $comment_table where comment_author_url like '%$word%' or comment_content like '%$word%' or comment_author like '%$word%'}; my $sth = $dbh->prepare($sql) or croak qq{ERROR: $DBI::errstr}; $sth->execute or croak qq{ERROR: $DBI::errstr}; while ( my ($id,$ip) = $sth->fetchrow_array ) { $ip_list{$ip}++; push @delete_id, $id; } $word_list{$word} = $DBI::rows; $sth->finish; } # process the regexp list for my $regexp (@banned_regexp) { my $sql = qq{ select comment_ID,comment_author_IP from $comment_table where comment_author_url regexp '$regexp' or comment_content regexp '$regexp' or comment_author regexp '$regexp'}; my $sth = $dbh->prepare($sql) or croak qq{ERROR: $DBI::errstr}; $sth->execute or croak qq{ERROR: $DBI::errstr}; while ( my ($id,$ip) = $sth->fetchrow_array ) { $ip_list{$ip}++; push @delete_id, $id; } $word_list{$regexp} = $DBI::rows; $sth->finish; } # reporting for my $ip ( keys %ip_list) { if ( $ip_report) { print {$output_fh} qq{IP: $ip : $ip_list{$ip}\n}; } if ($tables) { if ( $ip_list{$ip} ge $ip_limit ) { print {$output_fh} qq{iptables -A INPUT -p tcp -m tcp --src $ip --dport 80 -j DROP -m comment --comment 'WordPress $database spam'\n} or croak qq{ERROR: $OS_ERROR}; } } } if ( $word_report ) { for my $word ( sort keys %word_list) { if ( $word_list{$word} ) { print {$output_fh} qq{WORD : $word : $word_list{$word}\n} or croak qq{ERROR: $OS_ERROR}; } } } # deleting if ( $delete ) { my $sql = qq{delete from $comment_table where comment_id=?}; my $sth = $dbh->prepare($sql) or croak qq{ERROR: $DBI::errstr}; for my $id ( @delete_id ) { if ( $verbose ) { print {$output_fh} qq{Deleting $id\n} or croak qq{ERROR :$OS_ERROR}; } $sth->execute($id) or croak qq{ERROR: $DBI::errstr}; } $sth->finish or croak qq{ERROR: $DBI::errstr}; } $dbh->disconnect;
greppy/misc-scripts
wordpress_spam_cleanup.pl
Perl
mit
6,770
#! /usr/bin/perl # # Copyright 1999-2010 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. # use strict; use Test::More; use IO::File; my $test_exec = "./two-phase-commit-test"; my $gass_cache = "globus-gass-cache"; my $globusrun = "globusrun"; if ($ENV{CONTACT_STRING} eq "") { die "CONTACT_STRING not set"; } my @tests; my @todo; my $testno=1; sub two_phase_test { my ($errors,$rc) = ("",0); my ($output); my $cache_cmd; my ($contact, $mode, $timeout) = @_; my $tag; my $valgrind = ""; if (exists $ENV{VALGRIND}) { $valgrind = "valgrind --log-file=VALGRIND-globus_gram_client_two_phase_commit_test" . $testno++ . ".log"; if (exists $ENV{VALGRIND_OPTIONS}) { $valgrind .= ' ' . $ENV{VALGRIND_OPTIONS}; } } my $fh = new IO::File( "$valgrind $test_exec \"$contact\" $mode $timeout |"); $tag = join('', <$fh>); $fh->close(); chomp($tag); $rc = $?>> 8; if ($rc != 0) { $errors .= "Test exited with $rc. "; } if($tag eq '') { $errors .= "Didn't get a real job id from the test.\n"; } else { sleep($timeout+5); if (($mode eq 'no-commit-end')) { my $cache_out = `$gass_cache -list -tag $tag | wc -l`; chomp($cache_out); if($cache_out eq "0") { $errors .= "Test should have left droppings"; } else { print STDERR `$gass_cache -cleanup-tag $tag`; system("$globusrun", "-r", "$ENV{CONTACT_STRING}", "&(restart=$tag)"); } } else { my $cache_out = `$gass_cache -list -tag $tag`; chomp($cache_out); if($cache_out ne '') { $errors .= "Test left unexpected droppings in the cache:\n" . "$cache_out"; print STDERR `$gass_cache -cleanup-tag $tag`; } } } ok($errors eq "", "$test_exec \"$contact\" $mode $timeout"); } push(@tests, "two_phase_test('$ENV{CONTACT_STRING}','no-commit','1');"); push(@tests, "two_phase_test('$ENV{CONTACT_STRING}','no-commit-end','10');"); push(@tests, "two_phase_test('$ENV{CONTACT_STRING}','commit', '10');"); push(@tests, "two_phase_test('$ENV{CONTACT_STRING}','late-commit-end', '10');"); # Now that the tests are defined, set up the Test to deal with them. plan tests => scalar(@tests), todo => \@todo; foreach (@tests) { eval "&$_"; }
eunsungc/gt6-RAMSES_8_5
gram/jobmanager/source/test/client/two-phase-commit-test.pl
Perl
apache-2.0
3,109
#!/usr/bin/perl -w # # Copyright 2019, 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. # # This example adds various types of negative criteria to a customer. These # criteria will be applied to all campaigns for the customer. use strict; use warnings; use utf8; use FindBin qw($Bin); use lib "$Bin/../../lib"; use Google::Ads::GoogleAds::Client; use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; use Google::Ads::GoogleAds::V10::Resources::CustomerNegativeCriterion; use Google::Ads::GoogleAds::V10::Common::ContentLabelInfo; use Google::Ads::GoogleAds::V10::Common::PlacementInfo; use Google::Ads::GoogleAds::V10::Enums::ContentLabelTypeEnum qw(TRAGEDY); use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; sub add_customer_negative_criteria { my ($api_client, $customer_id) = @_; # Create a negative customer criterion excluding the content label type of 'TRAGEDY'. my $tragedy_criterion = Google::Ads::GoogleAds::V10::Resources::CustomerNegativeCriterion->new({ contentLabel => Google::Ads::GoogleAds::V10::Common::ContentLabelInfo->new({ type => TRAGEDY })}); # Create a negative customer criterion excluding the placement with url # 'http://www.example.com'. my $placement_criterion = Google::Ads::GoogleAds::V10::Resources::CustomerNegativeCriterion->new({ placement => Google::Ads::GoogleAds::V10::Common::PlacementInfo->new({ url => "http://example.com" })}); # Create the operations. my $operations = [{create => $tragedy_criterion}, {create => $placement_criterion}]; # Add the negative customer criteria. my $customer_negative_criteria_response = $api_client->CustomerNegativeCriterionService()->mutate({ customerId => $customer_id, operations => $operations }); my $customer_negative_criterion_results = $customer_negative_criteria_response->{results}; printf "Created %d new negative customer criteria.\n", scalar @$customer_negative_criterion_results; foreach my $result (@{$customer_negative_criterion_results}) { printf "Created new negative customer criteria with resource name '%s'.\n", $result->{resourceName}; } return 1; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id); # Print the help message if the parameters are not initialized in the code nor # in the command line. pod2usage(2) if not check_params($customer_id); # Call the example. add_customer_negative_criteria($api_client, $customer_id =~ s/-//gr); =pod =head1 NAME add_customer_negative_criteria =head1 DESCRIPTION This example adds various types of negative criteria to a customer. These criteria will be applied to all campaigns for the customer. =head1 SYNOPSIS add_customer_negative_criteria.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. =cut
googleads/google-ads-perl
examples/targeting/add_customer_negative_criteria.pl
Perl
apache-2.0
4,216
package Paws::EC2::ConversionTask; use Moose; has ConversionTaskId => (is => 'ro', isa => 'Str', request_name => 'conversionTaskId', traits => ['NameInRequest'], required => 1); has ExpirationTime => (is => 'ro', isa => 'Str', request_name => 'expirationTime', traits => ['NameInRequest']); has ImportInstance => (is => 'ro', isa => 'Paws::EC2::ImportInstanceTaskDetails', request_name => 'importInstance', traits => ['NameInRequest']); has ImportVolume => (is => 'ro', isa => 'Paws::EC2::ImportVolumeTaskDetails', request_name => 'importVolume', traits => ['NameInRequest']); has State => (is => 'ro', isa => 'Str', request_name => 'state', traits => ['NameInRequest'], required => 1); has StatusMessage => (is => 'ro', isa => 'Str', request_name => 'statusMessage', traits => ['NameInRequest']); has Tags => (is => 'ro', isa => 'ArrayRef[Paws::EC2::Tag]', request_name => 'tagSet', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::EC2::ConversionTask =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::EC2::ConversionTask object: $service_obj->Method(Att1 => { ConversionTaskId => $value, ..., Tags => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::EC2::ConversionTask object: $result = $service_obj->Method(...); $result->Att1->ConversionTaskId =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 B<REQUIRED> ConversionTaskId => Str The ID of the conversion task. =head2 ExpirationTime => Str The time when the task expires. If the upload isn't complete before the expiration time, we automatically cancel the task. =head2 ImportInstance => L<Paws::EC2::ImportInstanceTaskDetails> If the task is for importing an instance, this contains information about the import instance task. =head2 ImportVolume => L<Paws::EC2::ImportVolumeTaskDetails> If the task is for importing a volume, this contains information about the import volume task. =head2 B<REQUIRED> State => Str The state of the conversion task. =head2 StatusMessage => Str The status message related to the conversion task. =head2 Tags => ArrayRef[L<Paws::EC2::Tag>] Any tags assigned to the task. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::EC2> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/EC2/ConversionTask.pm
Perl
apache-2.0
2,830
package Net::FreeIPA::Common; use strict; use warnings; use Net::FreeIPA::API::Magic; use Net::FreeIPA::Error; use Readonly; # Convert find one API method in attribute name to find # This map might be API version dependant Readonly::Hash our %FIND_ONE => { aci => 'aciname', cert => 'cn', delegation => 'aciname', dnsforwardzone => 'idnsname', dnsrecord => 'idnsname', dnszone => 'idnsname', group => 'cn', host => 'fqdn', hostgroup => 'fqdn', server => 'cn', service => 'krbprincipalname', trust => 'cn', user => 'uid', vault => 'cn', }; =head1 NAME Net::FreeIPA::Common provides common convenience methods for Net::FreeIPA =head2 Public methods =over =item find_one Use the C<api> method C<<api_<api>_find>> to retrieve a single answer. The C<criteria> argument of the C<<api_<api>_find>> is the empty string, the C<all> option is set. (Warns if more than one is found, and returns the first one in that case). Returns undef in case of problem or if there is no result. =cut sub find_one { my ($self, $api, $value) = @_; my $res; # Do not use ->can with autoload'ed magic # use API::retrieve (as function) my $func = $api."_find"; my $method = "$Net::FreeIPA::API::API_METHOD_PREFIX$func"; my ($cmds, $fail) = Net::FreeIPA::API::Magic::retrieve($func); if ($fail) { $self->error("find_one: unknown API method $method"); } else { my $attr = $FIND_ONE{$api}; if ($attr) { my $response = $self->$method("", $attr => $value, all => 1); if ($response) { my $count = $response->{answer}->{result}->{count}; if (! $count) { $self->debug("one_find method $method and value $value returns 0 answers."); } else { if ($count > 1) { $self->warn("one_find method $method and value $value returns $count answers"); }; $res = $response->{result}->[0]; } } else { # error is already logged. $self->debug("find_one: method $method failed."); }; } else { $self->error("find_one: no supported attribute for api $api"); } }; return $res; } =item do_one Wrapper for simple call using C<api> and C<method> via C<<api_<api>_<method>(C<name>)>>. Any options are passed as is except C<__noerror>. Following error-type are not reported as error (set/added as defaults for C<__noerror>) (still returns C<undef>): =over =item DuplicateEntry: when C<method> is C<add>, an existing entry is not reported as an error =item AlreadyInactive: when C<method> is C<disable>, an already inactive/disabled entry is not reported as an error =item NotFound: when C<method> is not C<mod> or any of the previous, an missing entry is not reported as an error =back Returns the result attribute on success, or undef otherwise. =cut sub do_one { my ($self, $api, $method, $name, %opts) = @_; my $api_method = $Net::FreeIPA::API::API_METHOD_PREFIX.$api."_$method"; my $msg_map = { $Net::FreeIPA::Error::DUPLICATE_ENTRY => "already exists", $Net::FreeIPA::Error::ALREADY_INACTIVE => "already inactive/disabled", $Net::FreeIPA::Error::NOT_FOUND => "does not exist", }; if ($method eq 'add') { # For add, do not report existing name as error push(@{$opts{__noerror}}, $Net::FreeIPA::Error::DUPLICATE_ENTRY); } elsif ($method eq 'disable') { # For disable, do not report already disabled name as error push(@{$opts{__noerror}}, $Net::FreeIPA::Error::ALREADY_INACTIVE); } if (! grep {$method eq $_ } qw(add mod)) { # For methods except add/mod, do not report missing name as error push(@{$opts{__noerror}}, $Net::FreeIPA::Error::NOT_FOUND); } my $response = $self->$api_method($name, %opts); my $name_msg = ref($name) eq 'ARRAY' ? join(', ', @$name) : $name; my $msg; if ($response) { $msg = "successfully $method-ed $api $name_msg"; } else { $msg = "failed to $method $api $name_msg"; foreach my $noerror (sort keys %$msg_map) { $msg .= " $api ".$msg_map->{$noerror} if ($response->{error} == $noerror); } } $self->debug("$api_method: $msg"); return $response ? $response->{result} : undef; }; =pod =back =cut 1;
stdweird/p5-net-freeipa
lib/Net/FreeIPA/Common.pm
Perl
apache-2.0
4,495
use strict; use warnings; package DZ::Test; # ABSTRACT: this is a sample package for testing Dist::Zilla; =head1 NAME Test - a test thing =cut sub main { return 1; } 1;
gitpan/Dist-Zilla-Plugin-Twitter
corpus/DZ-Test/lib/DZ/Test.pm
Perl
apache-2.0
176
package PYX::Parser; # Pragmas. use strict; use warnings; # Modules. use Class::Utils qw(set_params); use Error::Pure qw(err); use Readonly; # Constants. Readonly::Scalar my $EMPTY_STR => q{}; # Version. our $VERSION = 0.01; # Constructor. sub new { my ($class, @params) = @_; my $self = bless {}, $class; # Parse handlers. $self->{'attribute'} = undef; $self->{'comment'} = undef; $self->{'data'} = undef; $self->{'end_tag'} = undef; $self->{'final'} = undef; $self->{'init'} = undef; $self->{'instruction'} = undef; $self->{'start_tag'} = undef; $self->{'other'} = undef; # Output rewrite. $self->{'output_rewrite'} = 0; # Output handler. $self->{'output_handler'} = \*STDOUT; # Process params. set_params($self, @params); # Processing line. $self->{'line'} = $EMPTY_STR; # Object. return $self; } # Parse PYX text or array of PYX text. sub parse { my ($self, $pyx, $out) = @_; if (! $out) { $out = $self->{'output_handler'}; } # Input data. my @text; if (ref $pyx eq 'ARRAY') { @text = @{$pyx}; } else { @text = split /\n/ms, $pyx; } # Parse. if ($self->{'init'}) { &{$self->{'init'}}($self); } foreach my $line (@text) { $self->_parse($line, $out); } if ($self->{'final'}) { &{$self->{'final'}}($self); } return; } # Parse file with PYX data. sub parse_file { my ($self, $input_file, $out) = @_; open my $inf, '<', $input_file; $self->parse_handler($inf, $out); close $inf; return; } # Parse PYX handler. sub parse_handler { my ($self, $input_file_handler, $out) = @_; if (! $input_file_handler || ref $input_file_handler ne 'GLOB') { err 'No input handler.'; } if (! $out) { $out = $self->{'output_handler'}; } if ($self->{'init'}) { &{$self->{'init'}}($self); } while (my $line = <$input_file_handler>) { chomp $line; $self->_parse($line, $out); } if ($self->{'final'}) { &{$self->{'final'}}($self); } return; } # Parse text string. sub _parse { my ($self, $line, $out) = @_; $self->{'line'} = $line; my ($type, $value) = $line =~ m/\A([A()\?\-_])(.*)\Z/; if (! $type) { $type = 'X'; } # Attribute. if ($type eq 'A') { my ($att, $attval) = $line =~ m/\AA([^\s]+)\s*(.*)\Z/; $self->_is_sub('attribute', $out, $att, $attval); # Start of tag. } elsif ($type eq '(') { $self->_is_sub('start_tag', $out, $value); # End of tag. } elsif ($type eq ')') { $self->_is_sub('end_tag', $out, $value); # Data. } elsif ($type eq '-') { $self->_is_sub('data', $out, $value); # Instruction. } elsif ($type eq '?') { my ($target, $data) = $line =~ m/\A\?([^\s]+)\s*(.*)\Z/; $self->_is_sub('instruction', $out, $target, $data); # Comment. } elsif ($type eq '_') { $self->_is_sub('comment', $out, $value); # Others. } else { if ($self->{'other'}) { &{$self->{'other'}}($self, $line); } else { err "Bad PYX tag at line '$line'."; } } return; } # Helper to defined handlers. sub _is_sub { my ($self, $key, $out, @values) = @_; # Handler with name '$key'. if (exists $self->{$key} && ref $self->{$key} eq 'CODE') { &{$self->{$key}}($self, @values); # Handler rewrite. } elsif (exists $self->{'rewrite'} && ref $self->{'rewrite'} eq 'CODE') { &{$self->{'rewrite'}}($self, $self->{'line'}); # Raw output to output handler handler. } elsif ($self->{'output_rewrite'}) { print {$out} $self->{'line'}, "\n"; } return; } 1; __END__ =pod =encoding utf8 =head1 NAME PYX::Parser - PYX parser with handlers. =head1 SYNOPSIS use PYX::Parser; my $obj = PYX::Parser->new(%parameters); $obj->parse($pyx, $out); $obj->parse_file($input_file, $out); $obj->parse_handle($input_file_handler, $out); =head1 METHODS =over 8 =item C<new(%parameters)> Constructor. =over 8 =item * C<attribute> Attribute handler. Default value is undef. =item * C<comment> Comment handler. Default value is undef. =item * C<data> Data handler. Default value is undef. =item * C<end_tag> End of tag handler. Default value is undef. =item * C<final> Final handler. Default value is undef. =item * C<init> Init handler. Default value is undef. =item * C<instruction> Instruction handler. Default value is undef. =item * C<start_tag> Start of tag handler. Default value is undef. =item * C<output_rewrite> Output rewrite. Default value is 0. =item * C<output_handler> Output handler. Default value is \*STDOUT. =item * C<other> Other handler. Default value is undef. =back =item C<parse($pyx[, $out])> Parse PYX text or array of PYX text. If $out not present, use 'output_handler'. Returns undef. =item C<parse_file($input_file[, $out])> Parse file with PYX data. If $out not present, use 'output_handler'. Returns undef. =item C<parse_handler($input_file_handler[, $out])> Parse PYX handler. If $out not present, use 'output_handler'. Returns undef. =back =head1 ERRORS new(): From Class::Utils::set_params(): Unknown parameter '%s'. parse(): Bad PYX tag at line '%s'. parse_file(): Bad PYX tag at line '%s'. No input handler. parse_handler(): Bad PYX tag at line '%s'. No input handler. =head1 EXAMPLE # Pragmas. use strict; use warnings; # Modules. use PYX::Parser; # Open file. my $file_handler = \*STDIN; my $file = $ARGV[0]; if ($file) { if (! open(INF, '<', $file)) { die "Cannot open file '$file'."; } $file_handler = \*INF; } # PYX::Parser object. my $parser = PYX::Parser->new( 'start_tag' => \&start_tag, 'end_tag' => \&end_tag, ); $parser->parse_handler($file_handler); # Close file. if ($file) { close(INF); } # Start tag handler. sub start_tag { my ($self, $tag) = @_; print "Start of tag '$tag'.\n"; } # End tag handler. sub end_tag { my ($self, $tag) = @_; print "End of tag '$tag'.\n"; } =head1 DEPENDENCIES L<Class::Utils>, L<Error::Pure>. =head1 SEE ALSO L<PYX>, L<PYX::Utils>. =head1 AUTHOR Michal Špaček L<skim@cpan.org>. =head1 LICENSE AND COPYRIGHT BSD 2-Clause License =head1 VERSION 0.01 =cut
gitpan/PYX
PYX/Parser.pm
Perl
bsd-2-clause
6,136
#!/usr/bin/perl # # $Id$ # # Copyright (c) 2007 .SE (The Internet Infrastructure Foundation). # 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ###################################################################### package DNSCheck::Lookup::Resolver; require 5.010001; use warnings; use strict; use utf8; use YAML; use Net::IP; use Time::HiRes qw[gettimeofday tv_interval]; use Carp; use Net::DNS::Resolver; use Net::DNS::Packet; use Net::DNS::RR; our %times; # In order to be able to know for sure where certain information comes from, # and/or modify parts of resolver chains, we need to do our own recursive # lookups rather than rely on an external caching recursive resolver. This # module is supposed to do recursive lookups. It seems to work, but was # written by someone who is not a DNS expert, so comments on the module logic # is very welcome. sub new { my $class = shift; my $parent = shift; my $self = {}; bless $self, $class; $self->{parent} = $parent; my $config = $self->config->get( "dns" ); $self->{debug} = $parent->config->get( "debug" ); $self->{debug} = $ENV{DNSCHECK_DEBUG} if $ENV{DNSCHECK_DEBUG}; $self->{debug} -= 1 if $self->{debug}; $self->{cache} = $parent->config->get( 'root_zone_data' ); $self->{current} = ''; $self->{resolver} = Net::DNS::Resolver->new( # RFC3330 reserved address. As close to guaranteed *not* to have a nameserver # on it as we're likely to get (the module does not accept an empty list). nameservers => ['192.0.2.1'], ); $self->{resolver}->persistent_tcp( 0 ); $self->{resolver}->cdflag( 1 ); $self->{resolver}->recurse( 0 ); $self->{resolver}->dnssec( 0 ); $self->{resolver}->debug( 1 ) if ( $self->{debug} and $self->{debug} > 1 ); $self->{resolver}->udp_timeout( $config->{udp_timeout} ); $self->{resolver}->tcp_timeout( $config->{tcp_timeout} ); $self->{resolver}->retry( $config->{retry} ); $self->{resolver}->retrans( $config->{retrans} ); return $self; } # Standard utility methods ## no critic (Subroutines::RequireArgUnpacking) sub resolver { return $_[0]->{resolver}; } sub parent { return $_[0]->{parent}; } sub cache { return $_[0]->{cache}; } sub config { return $_[0]->parent->config; } sub logger { return $_[0]->parent->logger; } # Timing information ## no critic (Subroutines::ProhibitBuiltinHomonyms) sub times { return \%times; } # Interface methods to underlying Net::DNS::Resolver object sub errorstring { my $self = shift; return $self->resolver->errorstring( @_ ); } sub dnssec { my $self = shift; return $self->resolver->dnssec( @_ ); } sub recursion { my $self = shift; return $self->resolver->recurse( @_ ); } sub cdflag { my $self = shift; return $self->resolver->cdflag( @_ ); } # Methods to support undelegated testing sub add_fake_glue { my $self = shift; my $zone = shift; my $nsname = shift; my $nsip = shift; return unless Net::IP->new( $nsip ); $nsname = $self->canonicalize_name( $nsname ); $zone = $self->canonicalize_name( $zone ); $self->cache->{ns}{$zone}{$nsname} = 1; $self->cache->{ips}{$nsname}{$nsip} = 1; $self->{fake}{ns}{$zone} = 1; $self->{fake}{ips}{$nsname} = 1; return $self; } sub add_fake_ds { my $self = shift; my $ds = shift; push @{ $self->{fake}{ds}{ $ds->name } }, $ds; return $self; } # Return a list of zones with fake glue sub faked_zones { my $self = shift; return map { my $tmp = $_; $tmp =~ s/\.$//; $tmp } keys %{ $self->{fake}{ns} }; } # Return a list of NS names for a zone with fake glue sub faked_zone { my $self = shift; my $name = shift; return unless $name; # An empty name isn't a faked zone. $name = $self->canonicalize_name( $name ); if ( $self->{fake}{ns}{$name} ) { return map { my $tmp = $_; $tmp =~ s/\.$//; $tmp } keys %{ $self->cache->{ns}{$name} }; } else { return; } } # Return a made-up packet with information for a name sub fake_packet { my $self = shift; my $zone = shift; my $name = shift; my $type = shift; $name = $self->canonicalize_name( $name ); my @ns = $self->faked_zone( $zone ); my @ips = keys %{ $self->cache->{ips}{$name} }; my $version; if ( $type eq 'A' ) { $version = 4; } elsif ( $type eq 'AAAA' ) { $version = 6; } elsif ( $type eq 'NS' ) { return $self->fake_ns_packet( $name ); } else { return; # Can't or won't fake that } @ips = map { $_->ip } grep { defined( $_ ) and $_->version == $version } map { Net::IP->new( $_ ) } @ips; my $p = Net::DNS::Packet->new; $p->unique_push( 'answer', Net::DNS::RR->new( "$name 4711 IN $type $_" ) ) for @ips; for my $ns ( @ns ) { $p->unique_push( 'authority', Net::DNS::RR->new( "$zone 4711 IN NS $ns" ) ); for my $ip ( keys %{ $self->cache->{ips}{ $self->canonicalize_name( $ns ) } } ) { my $t = ( Net::IP->new( $ip )->version == 4 ) ? 'A' : 'AAAA'; $p->unique_push( 'additional', Net::DNS::RR->new( "$ns 4711 IN $t $ip" ) ); } } $p->header->aa( 1 ); return $p; } sub fake_ns_packet { my $self = shift; my $zone = shift; my @ns = keys %{ $self->{cache}{ns}{$zone} }; my $p = Net::DNS::Packet->new; foreach my $n ( @ns ) { $p->unique_push( 'answer', Net::DNS::RR->new( "$zone 4711 IN NS $n" ) ); foreach my $ip ( keys %{ $self->{cache}{ips}{$n} } ) { my $t = ( Net::IP->new( $ip )->version == 4 ) ? 'A' : 'AAAA'; $p->unique_push( 'additional', Net::DNS::RR->new( "$n 4711 IN $t $ip" ) ); } } return $p; } sub fake_ds_packet { my $self = shift; my $zone = shift; my $p = Net::DNS::Packet->new; foreach my $rr ( @{ $self->{fake}{ds}{$zone} } ) { $p->unique_push( 'answer', $rr ); } return $p; } # Add stuff to our cache. # # We cache known nameserver lists for names, and IP addresses for names. sub remember { my ( $self, $p ) = @_; return unless defined( $p ); foreach my $rr ( $p->answer, $p->additional, $p->authority ) { my $n = $self->canonicalize_name( $rr->name ); if ( $rr->type eq 'A' or $rr->type eq 'AAAA' ) { $self->{cache}{ips}{$n}{ Net::IP->new( $rr->address )->ip } = 1 unless $self->{fake}{ips}{$n}; } if ( $rr->type eq 'NS' ) { print STDERR "remember: NS $n (" . $rr->name . ") " . $rr->nsdname . ".\n" if ( $self->{debug} and $self->{debug} > 1 ); $self->{cache}{ns}{$n}{ $self->canonicalize_name( $rr->nsdname ) } = 1 unless $self->{fake}{ns}{$n}; } } return $self; } # Class method to generate data with which to preload the cache. sub get_preload_data { my $self = shift; my $source = shift; my %cache; my $res = Net::DNS::Resolver->new; $res->nameservers( $source ) if defined( $source ); my $z = eval { $res->send( '.', 'IN', 'NS' ) }; if ( not defined( $z ) or scalar( $z->answer ) == 0 ) { croak "Failed to get root zone data"; } foreach my $rr ( $z->answer ) { next unless $rr->type eq 'NS'; $cache{ns}{'.'}{ $self->canonicalize_name( $rr->nsdname ) } = 1; } foreach my $nsname ( keys %{ $cache{ns}{'.'} } ) { $nsname = $self->canonicalize_name( $nsname ); my $a = eval { $res->send( $nsname, 'IN', 'A' ) }; next if ( not defined( $a ) or scalar( $a->answer ) == 0 ); foreach my $rr ( $a->answer ) { next unless $rr->type eq 'A'; $cache{ips}{$nsname}{ $rr->address } = 1; } my $aaaa = eval { $res->send( $nsname, 'IN', 'AAAA' ) }; next if ( not defined( $aaaa ) or scalar( $aaaa->answer ) == 0 ); foreach my $rr ( $aaaa->answer ) { next unless $rr->type eq 'AAAA'; $cache{ips}{$nsname}{ $rr->address } = 1; } } return \%cache; } # Reformat a name into a standardized form, for ease of comparison sub canonicalize_name { my $self = shift; my $name = shift; my $i = Net::IP->new( $name ); if ( $name and $name =~ m|^[0-9.:]+$| and defined( $i ) ) { $name = $i->reverse_ip; } $name = lc( $name ); $name .= '.' unless substr( $name, -1 ) eq '.'; return $name; } # Strip the leftmost label off a DNS name. If there are no labels left after # removing one, returns a single period for the root level. sub strip_label { my $self = shift; my $name = shift; my @labels = split /\./, $name; shift @labels; if ( @labels ) { return $self->canonicalize_name( join '.', @labels ); } else { return '.'; } } # Take a name, and return the nameserver names for the highest parent level we # have in cache. Which, at worst, will be the root zone, the data for which we # initialize on object creation. sub highest_known_ns { my $self = shift; my $name = shift; $name = $self->canonicalize_name( $name ); # If there are more than one zone with fake glue, and one is a parent of # another, choose the one with the most labels in it. my $faked = ( sort { $b =~ y/././ <=> $a =~ y/././ } grep { $name =~ /\Q$_\E$/ } $self->faked_zones )[0]; if ( $faked ) { return keys %{ $self->cache->{ns}{$faked} }; } my @candidates; while ( 1 ) { my @tmp; @tmp = $self->simple_names_to_ips( keys %{ $self->{cache}{ns}{$name} } ) if $self->{cache}{ns}{$name}; push @candidates, @tmp if @tmp; if ( $name eq '.' ) { last; } $name = $self->strip_label( $name ); } if ( !@candidates ) { die "Root zone cache missing."; } else { return @candidates; } } sub simple_names_to_ips { my $self = shift; my @names = map { $self->canonicalize_name( $_ ) } @_; my @ips; foreach my $n ( @names ) { if ( $self->cache->{ips}{$n} ) { push @ips, keys %{ $self->cache->{ips}{$n} }; } } return @ips; } sub names_to_ips { my $self = shift; my @names = map { $self->canonicalize_name( $_ ) } @_; my @ips; foreach my $n ( @names ) { if ( $self->cache->{ips}{$n} ) { push @ips, keys %{ $self->cache->{ips}{$n} }; } else { next if $self->{poison}{$n}; $self->{poison}{$n} = 1; # Block lookups of this name my $p = $self->recurse( $n, 'A' ); $self->remember( $p ); $p = $self->recurse( $n, 'AAAA' ); $self->remember( $p ); if ( $self->cache->{ips}{$n} ) { push @ips, keys %{ $self->cache->{ips}{$n} }; $self->{poison}{$n} = 0; # Allow lookups of name } } } return @ips; } # Send a query to a specified set of nameservers and return the result. sub get { my $self = shift; my $name = shift; my $type = shift // 'NS'; my $class = shift // 'IN'; my @ns = @_; print STDERR "get: $name $type $class @ns " . ( caller( 1 ) )[3] . "\n" if $self->{debug}; @ns = map { $_->ip } grep { ( $_->version == 4 and $self->config->get( 'net' )->{ipv4} ) or ( $_->version == 6 and $self->config->get( 'net' )->{ipv6} ) } map { Net::IP->new( $_ ) } @ns; return unless @ns; my @ns_old = $self->{resolver}->nameservers; $self->{resolver}->nameservers( @ns ) if @ns; my $before = [ gettimeofday() ]; my $p = eval { $self->{resolver}->send( $name, $class, $type ) }; my $duration = tv_interval( $before ); if ( $p and $p->answerfrom ) { push @{ $self->times->{ $p->answerfrom } }, $duration; } print STDERR "get: " . $p->string . "\n" if ( defined( $p ) and $self->{debug} and $self->{debug} > 1 ); $self->remember( $p ) if defined( $p ); $self->{resolver}->nameservers( @ns_old ); return $p; } sub trace { my ( $self, $domain ) = @_; $self->{trace}{$domain} = []; $self->recurse( $domain, 'ANY', 'ANY' ); return reverse @{ $self->{trace}{$domain} }; } # Recursively look up stuff. # # Resolution procedure of a name # ============================== # # 1. Get ns names for the highest level we know of (root, probably). # # 2. Do name-to-ip for names. Discard names we can't translate. # # 3. Push IPs on stack of servers to ask, unless they've already been there. # # 4. Pop IP from stack. Send question to it. Remember we asked it. # If the stack is empty, return undef. # # 5. If we get a response, clear the stack. # # 6. If the reply is authoritative, return it. # If it is not, but contains records in Authority section, get names from # those records and go to 2, unless the records point to a name higher in # the chain, in which case we terminate and return undef. sub recurse { my ( $self, $name, $type, $class, $cnames ) = @_; $type //= 'NS'; $class //= 'IN'; $cnames //= {}; print STDERR "recurse: $name $type $class\n" if $self->{debug}; # See if it should be faked if ( ( $type eq 'A' or $type eq 'AAAA' ) and $self->{fake}{ips}{ $self->canonicalize_name( $name ) } ) { return $self->fake_packet( undef, $name, $type ); } elsif ( $type eq 'NS' and $self->{fake}{ns}{ $self->canonicalize_name( $name ) } ) { return $self->fake_packet( undef, $name, $type ); } my @stack = $self->highest_known_ns( $name ); my %seen; my $candidate; my $level = -1; while ( @stack ) { my $ns = pop( @stack ); print STDERR "recurse: Popped $ns (stack is " . scalar( @stack ) . " entries deep).\n" if $self->{debug}; $seen{$ns} = 1; my $p = $self->get( $name, $type, $class, $ns ); if ( !defined( $p ) ) { print STDERR "recurse: No response packet.\n" if $self->{debug}; next; } elsif ( $p->header->rcode ne 'NOERROR' ) { print STDERR "recurse: Response code " . $p->header->rcode . "\n" if $self->{debug}; $candidate = $p unless $candidate; next; } elsif ( scalar( $p->answer ) > 0 and grep { $_->type eq 'CNAME' } $p->answer ) { print STDERR "recurse: Resolving non-auth CNAME.\n" if $self->{debug}; my $cnamerr = ( grep { $_->type eq 'CNAME' } $p->answer )[0]; return $p if $cnames->{ $cnamerr->cname }; # Break loops $cnames->{ $cnamerr->cname } = 1; my $tmp = $self->recurse( $cnamerr->cname, $type, $class, $cnames ); if ( $tmp ) { print STDERR "recurse: Adding CNAME to response packet.\n" if $self->{debug}; $tmp->unique_push( answer => $cnamerr ) unless ( keys %$cnames ) > 1; return $tmp; } else { return $p; } } elsif ( $self->matches( $p, $name, $type, $class ) ) { return $p; } elsif ( scalar( $p->authority ) > 0 ) { my $zname = ( $p->authority )[0]->name; my $m = $self->matching_labels( $name, $zname ); if ( $m < $level ) { print STDERR "recurse: Bad referral. Skipping to next server.\n" if $self->{debug}; next; # Resolving chain redirecting up } push @{ $self->{trace}{$name} }, $zname; # Remember the path we took, so we can use it to find parent domains. $level = $m; print STDERR "recurse: Got " . scalar( $p->authority ) . " authority records. Reloading stack.\n" if $self->{debug}; @stack = (); $self->remember( $p ); if ( my @fns = $self->faked_zone( $zname ) ) { push @stack, grep { !$seen{$_} } $self->simple_names_to_ips( @fns ); } else { push @stack, grep { !$seen{$_} } $self->names_to_ips( map { $_->nsdname } grep { $_->type eq 'NS' } $p->authority ); } next; } else { print STDERR "recurse: Fell through: " . $p->print if $self->{debug}; } } print STDERR "recurse: Ran out of servers.\n" if $self->{debug}; # Ran out of servers before we got a good reply, return what we've got if ( $candidate ) { return $candidate; } else { return; } } sub matches { my ( $self, $p, $name, $type, $class ) = @_; $name = lc( $self->canonicalize_name( $name ) ); $type = lc( $type ); $class = lc( $class ); foreach my $rr ( $p->answer ) { my $rrname = lc( $self->canonicalize_name( $rr->name ) ); my $rrtype = lc( $rr->type ); my $rrclass = lc( $rr->class ); printf STDERR "matches: %s => %s, %s => %s, %s => %s\n", $rrname, $name, $rrtype, $type, $rrclass, $class if $self->{debug}; if ( $rrname eq $name and ( $rrtype eq $type or $type eq 'any' ) and ( $rrclass eq $class or $class eq 'any' ) ) { print STDERR "matches: Found.\n" if $self->{debug}; return 1; } } print STDERR "matches: Not found.\n" if $self->{debug}; return; } sub matching_labels { my $self = shift; my ( $n1, $n2 ) = @_; my @n1 = reverse split /\./, $n1; my @n2 = reverse split /\./, $n2; my $count = 0; while ( @n1 and @n2 ) { my $i = shift @n1; my $j = shift @n2; if ( $i eq $j ) { $count += 1; } else { last; } } return $count; } 1; =head1 NAME DNSCheck::Lookup::Resolver - a recursive DNS resolver for DNSCheck =head1 DESCRIPTION This module does recursive lookups, and is heavily used by L<DNSCheck::Lookup::DNS>. =head1 PUBLIC METHODS =over =item ->new($parent) Creates and configures a new resolver object. The parent object should be a L<DNSCheck> object, and it will be used to find DNS resolver configuration information. =item ->get($name, $type, $class, @nameservers) Send a DNS query to specified servers. =item ->recurse($name, $type, [$class]) Do a recursive query. If the class is not specified, it defaults to IN. =back =head1 INTERNAL METHODS =over =item ->get_preload_data() Class method. Does a recursive global NS lookup for the root zone, using the system paramters, and returns a reference to a nested hash stucture suitable for use as an object cache. =item ->add_fake_glue() Add fake glue for an undelegated test. =item ->add_fake_ds() Add a fake DS record for en undelegated test. =item ->cache() Return a reference to the object's name cache. =item ->canonicalize_name($name) Return the given name in its canonical form, with a trailing dot. =item ->resolver() Returns the underlying L<Net::DNS::Resolver> object that's used to send queries to nameservers. =item ->cdflag() =item ->dnssec() =item ->recursion() =item ->errorstring() These four methods simply proxy to the underlying resolver object. =item ->fake_ns_packet() Create an artificial response packet to an NS query. =item ->fake_ds_packet() Create an artificial response packet to a DS query. =item ->fake_packet() Create an artificial response packet to an A, AAAA or NS query. =item ->faked_zone($zone) Return nameserver names for the given zone if fake glue has been added for it, or C<undefined> if not. =item ->faked_zones() Return a list of the names of all zones we have fake glue data for. =item ->highest_known_ns() Return the nearest ancestor zone we have in cache for the given zone name. =item ->matches($packet, $name, $type, $class) Check if the given L<Net::DNS::Packet> contains any records matching the given name, type and class. =item ->matching_labels($name1, $name2) Count the number of matching labels in the two given names. =item ->names_to_ips(@namelist) Return a list of IP addresses for the given names, doing recursive lookups for them. =item ->simple_names_to_ips() Return a list of IP addresses for the given names, only looking at what is already in the object's cache. =item ->remember($packet) Add data from the given response packet to the object's cache. =item ->strip_label($name) Return a name that's one label shorter than the given name, except if the given name is the root, in which case the root is returned. =item ->parent() =item ->config() =item ->logger() These three are the same as in all other DNSCheck classes. =item ->times() Return a reference to the nested hash structure holding nameserver response time data. =item ->trace($domain) Return a list describing the recursion chain that led from the root to the given domain. =back =cut
dotse/dnscheck
engine/lib/DNSCheck/Lookup/Resolver.pm
Perl
bsd-2-clause
22,468
#!/usr/bin/perl $i = 0; while( $i < 10000000 ) { $i = $i + 1; }
tpo/ten_million_times
increment.pl
Perl
bsd-2-clause
69
# Copyright (c) 2003 # The funknet.org Group. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by The funknet.org # Group and its contributors. # 4. Neither the name of the Group nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE GROUP AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE GROUP 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. package Funknet::Config::FirewallRule; use strict; use Funknet::Config::Validate qw/ is_ipv4 is_ipv6 is_valid_ruletype is_valid_proto is_valid_ifname /; use Funknet::Config::FirewallRule::IPTables; use Funknet::Config::FirewallRule::IPFW; use Funknet::Config::FirewallRule::PF; use Funknet::Config::FirewallRule::IPF; use base qw/ Funknet::Config /; use Funknet::Debug; use Data::Dumper; =head1 NAME Funknet::Config::FirewallRule =head1 DESCRIPTION This is the generic FirewallRule class. It reads the firewall_type parameter set by higher-level code, and calls the appropriate routines in the OS-specific classes, returning an object blessed into a specific class. =head1 EXTENDING Adding a new OS' firewall implementation requires the following changes: extend sub new to read the new firewall_type parameter; likewise the constructor in Funknet::Config::FirewallRuleSet. Add a new module Funknet::Config::FirewallRule::NewType.pm and use it in this module. Add the new firewall's firewall_type flag to Funknet::Config::Validate.pm. Implement specific methods in NewType.pm. =cut sub new { debug("arrived in Config/FirewallRule.pm new"); my ($class, %args) = @_; my $self = bless {}, $class; my $l = Funknet::ConfigFile::Tools->local; unless (defined $args{source} && ($args{source} eq 'whois' || $args{source} eq 'host')) { $self->warn("firewall_rule: missing or invalid source"); return undef; } else { $self->{_type} = $args{type} || 'filter'; unless (is_valid_ruletype($self->{_type})) { $self->warn("firewall_rule: invalid type: $self->{_type}"); return undef; } $self->{_source} = $args{source}; $self->{_source_address} = $args{source_address} || '0.0.0.0/0'; $self->{_destination_address} = $args{destination_address} || '0.0.0.0/0'; $self->{_source_port} = $args{source_port}; $self->{_destination_port} = $args{destination_port}; $self->{_proto} = $args{proto} || 'all'; $self->{_in_interface} = $args{in_interface}; $self->{_out_interface} = $args{out_interface}; $self->{_to_port} = $args{to_port}; $self->{_to_addr} = $args{to_addr}; $self->{_direction} = $args{direction}; if(defined($args{rule_num})) { $self->{_rule_num} = $args{rule_num}; } debug("in Config/FirewallRule.pm new source = $self->{_source}"); } # support the 'local_source' parameter. if it exists, and is a valid # ipv4 address, then replace $self->{_local_endpoint} with it, and # move existing value to $self->{_local_public_endpoint} if (exists $l->{source} && defined $l->{source} && is_ipv4($l->{source})) { $self->{_local_public_endpoint} = $self->{_local_endpoint}; $self->{_local_endpoint} = $l->{source}; } # rebless to the actual firewall type debug("firewall_type in FirewallRule is $l->{firewall_type}"); $l->{firewall_type} eq 'iptables' and bless $self, 'Funknet::Config::FirewallRule::IPTables'; $l->{firewall_type} eq 'ipfw' and bless $self, 'Funknet::Config::FirewallRule::IPFW'; $l->{firewall_type} eq 'pf' and bless $self, 'Funknet::Config::FirewallRule::PF'; $l->{firewall_type} eq 'ipf' and bless $self, 'Funknet::Config::FirewallRule::IPF'; return $self; } sub as_hashkey { my ($self) = @_; my $hash = "$self->{_type}-$self->{_proto}-$self->{_to_addr}-$self->{_to_port}-" . "$self->{_source_address}-$self->{_source_port}-" . "$self->{_in_interface}-$self->{_out_interface}-" . "$self->{_destination_address}-$self->{_destination_port}"; return $hash; } sub interface { my ($self) = @_; return $self->{_interface}; } sub name { my ($self) = @_; return $self->{_name}; } sub type { my ($self) = @_; return $self->{_type}; } sub local_os { my ($self) = @_; return $self->{_local_os}; } sub ifname { my ($self) = @_; return $self->{_ifname}; } sub rule_num { my ($self, $new) = @_; if(defined ($new)) { $self->{_rule_num} = $new; } return $self->{_rule_num}; } sub source { my ($self) = @_; return $self->{_source}; } sub remote_endpoint { my ($self) = @_; return $self->{_remote_endpoint}; } sub local_endpoint { my ($self) = @_; return $self->{_local_endpoint}; } sub to_port { my ($self) = @_; return $self->{_to_port}; } sub to_addr { my ($self) = @_; return $self->{_to_addr}; } sub direction { my ($self) = @_; return $self->{_direction}; } 1;
chrisa/funknet-tools
lib/Funknet/Config/FirewallRule.pm
Perl
bsd-3-clause
6,399
package FuseWrap; use strict; use warnings; use base 'Fuse'; use Carp 'verbose'; use FindBin '$Bin'; use IPC::Run 'run'; use Getopt::Long qw/:config pass_through/; our ($mountpoint, $debug, $allusers, $just_umount); BEGIN { GetOptions( 'mountpoint=s' => \$mountpoint, 'debug+' => \($debug = 0), 'allusers!' => \($allusers = 1), 'umount' => \($just_umount), ); no warnings 'redefine'; sub GetOptions (@) { my $ret = &Getopt::Long::GetOptions; $mountpoint //= shift @ARGV if @ARGV; $ret; } } use Fcntl ':mode'; use POSIX qw/ENOENT EOPNOTSUPP/; our (%default_stat, @stat, @fields); BEGIN { %default_stat = ( qw/dev 1 ino 1 mode 0 nlink 1/ => uid => 0+$< => gid => 0+$( => qw/rdev 0 size 4096/ => map(($_ => time), qw/atime mtime ctime/) => qw/blksize 4096 blocks 4096/, readlink => '', ); @stat = qw/dev ino mode nlink uid gid rdev size atime mtime ctime blksize blocks/; @fields = (readlink => @stat); } sub _fake_attr { my ($name, %stat) = (shift, %default_stat, @_); @stat{@stat} } sub _fake_attr_file { _fake_attr @_, mode => 0100000 | 0644 } sub _fake_attr_dir { _fake_attr @_, nlink => 3, mode => 0040000 | 0755 } sub _fake_attr_ { my $base = (split '/', $_[0])[-1]; if (length($base) and $base eq lc $base) { &_fake_attr_file; } else { &_fake_attr_dir; } } our $mounted; sub _de { my ($name, $sub) = splice @_, 0, 2; my @p = $debug ? @_ : (); my @ret = &$sub; if ($debug) { use Data::Dumper; print Dumper [ $name, $sub, \@p, \@ret ]; } @ret; } my @funcs; BEGIN { @funcs = qw/ getattr getdir readlink mknod mkdir unlink rmdir symlink rename link chmod chown truncate utime open read write statfs flush release fsync setxattr getxattr listxattr removexattr /; } sub umount { my @cmd = (fusermount => -u => $mountpoint); print "@cmd\n"; run \@cmd } sub mounted { local @ARGV = ('/etc/mtab'); grep m{^\S+\s+\Q$mountpoint\E\s}, <> } END { umount if mounted } if ($just_umount) { umount if mounted; exit; } sub main { my $sym = \%::; $sym = $$sym{$_.'::'} for split /::/, __PACKAGE__; my %un; for my $fn (@funcs) { my $sub = (exists $$sym{$fn}) ? \&$fn : sub { $un{$fn}++ or warn "unimplemented($fn)\n"; -&EOPNOTSUPP }; no strict 'refs'; no warnings 'redefine'; *$fn = sub { _de $fn, $sub, @_ }; } $mountpoint // die "Must specify mount point\n"; umount if mounted; Fuse::main( mountpoint => $mountpoint, grep($debug > 1, qw/debug 1/), grep($allusers, qw/mountopts allow_other/), map {; $_ => 'FuseWrap::'.$_ } @funcs ); umount if mounted; } 1;
benizi/dotfiles
perl-lib/FuseWrap.pm
Perl
mit
2,538
# This program is distributed under the terms of # The MIT License (MIT) # # Copyright (c) 2014 Six Apart, Ltd. # # $Id$ package Viewer::L10N::es; use strict; use utf8; use base qw( Viewer::L10N ); our %Lexicon = ( ## lib/MT/App/Viewer.pm 'Loading blog with ID [_1] failed' => 'Falló al cargar el blog con el ID [_1]', 'File not found' => 'Fichero no encontrado', 'Template publishing failed: [_1]' => 'Falló al publicar la plantilla: [_1]', 'Unknown archive type: [_1]' => 'Tipo de archivo desconocido: [_1]', 'Cannot load template [_1]' => 'No se pudo cargar la plantilla [_1]', 'Archive publishing failed: [_1]' => 'Falló al publicar los archivos: [_1]', 'Invalid entry ID [_1].' => 'Entrada con ID [_1] no válida.', 'Entry [_1] was not published.' => 'No se publicó la entrada [_1].', 'Invalid category ID \'[_1]\'' => 'Identificador de categoría no válido \'[_1]\'', 'Invalid author ID \'[_1]\'' => 'Autor no válido, ID \'[_1]\'', ); 1;
movabletype/mt-plugin-mtviewer
plugins/MTViewer/lib/Viewer/L10N/es.pm
Perl
mit
1,035
# <@LICENSE> # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to you under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # </@LICENSE> =head1 NAME Mail::SpamAssassin::Plugin - SpamAssassin plugin base class =head1 SYNOPSIS =head2 SpamAssassin configuration: loadplugin MyPlugin /path/to/myplugin.pm =head2 Perl code: package MyPlugin; use Mail::SpamAssassin::Plugin; our @ISA = qw(Mail::SpamAssassin::Plugin); sub new { my ($class, $mailsa) = @_; # the usual perlobj boilerplate to create a subclass object $class = ref($class) || $class; my $self = $class->SUPER::new($mailsa); bless ($self, $class); # then register an eval rule, if desired... $self->register_eval_rule ("check_for_foo"); # and return the new plugin object return $self; } ...methods... 1; =head1 DESCRIPTION This is the base class for SpamAssassin plugins; all plugins must be objects that implement this class. This class provides no-op stub methods for all the callbacks that a plugin can receive. It is expected that your plugin will override one or more of these stubs to perform its actions. SpamAssassin implements a plugin chain; each callback event is passed to each of the registered plugin objects in turn. Any plugin can call C<$self-E<gt>inhibit_further_callbacks()> to block delivery of that event to later plugins in the chain. This is useful if the plugin has handled the event, and there will be no need for later plugins to handle it as well. If you're looking to write a simple eval rule, skip straight to C<register_eval_rule()>, below. =head1 INTERFACE In all the plugin APIs below, C<options> refers to a reference to a hash containing name-value pairs. This is used to ensure future-compatibility, in that we can add new options in future without affecting objects built to an earlier version of the API. For example, here would be how to print out the C<line> item in a C<parse_config()> method: sub parse_config { my ($self, $opts) = @_; print "MyPlugin: parse_config got ".$opts->{line}."\n"; } =head1 METHODS The following methods can be overridden by subclasses to handle events. =over 4 =cut package Mail::SpamAssassin::Plugin; use Mail::SpamAssassin; use Mail::SpamAssassin::Logger; use strict; use warnings; # use bytes; use re 'taint'; our @ISA = qw(); #Removed $VERSION per BUG 6422 #$VERSION = 'bogus'; ########################################################################### =item $plugin = MyPluginClass->new ($mailsaobject) Constructor. Plugins that need to register themselves will need to define their own; the default super-class constructor will work fine for plugins that just override a method. Note that subclasses must provide the C<$mailsaobject> to the superclass constructor, like so: my $self = $class->SUPER::new($mailsaobject); Lifecycle note: plugins that will need to store per-scan state should not store that on the Plugin object; instead this should be stored on the PerMsgStatus object, see C<check_start()> below. It is also likewise recommended that configuration settings be stored on the Conf object; see C<parse_config()>. =cut sub new { my $class = shift; my $mailsaobject = shift; $class = ref($class) || $class; if (!defined $mailsaobject) { die "plugin: usage: Mail::SpamAssassin::Plugin::new(class,mailsaobject)"; } my $self = { main => $mailsaobject, _inhibit_further_callbacks => 0 }; bless ($self, $class); $self; } # --------------------------------------------------------------------------- # now list the supported methods we will call into. NOTE: we don't have # to implement them here, since the plugin can use "can()" to introspect # the object and determine if it's capable of calling the method anyway. # Nifty! =item $plugin->parse_config ( { options ... } ) Parse a configuration line that hasn't already been handled. C<options> is a reference to a hash containing these options: =over 4 =item line The line of configuration text to parse. This has leading and trailing whitespace, and comments, removed. =item key The configuration key; ie. the first "word" on the line. =item value The configuration value; everything after the first "word" and any whitespace after that. =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =item user_config A boolean: C<1> if reading a user's configuration, C<0> if reading the system-wide configuration files. =back If the configuration line was a setting that is handled by this plugin, the method implementation should call C<$self-E<gt>inhibit_further_callbacks()>. If the setting is not handled by this plugin, the method should return C<0> so that a later plugin may handle it, or so that SpamAssassin can output a warning message to the user if no plugin understands it. Lifecycle note: it is suggested that configuration be stored on the C<Mail::SpamAssassin::Conf> object in use, instead of the plugin object itself. That can be found as C<$plugin-E<gt>{main}-E<gt>{conf}>, or as "conf" in the C<$options> hash reference above. By storing it on C<conf>, this allows per-user and system-wide configuration precedence to be dealt with correctly. =item $plugin->finish_parsing_start ( { options ... } ) Signals that the system-wide configuration has been completely read, but internal data structures are not yet created. It is possible to use this hook to dynamically change the configuration already read in or add new config options. C<options> is a reference to a hash containing these options: =over 4 =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back Note: there are no guarantees that the internal data structures of SpamAssassin will not change from release to release. In particular to this plugin hook, if you modify the rules data structures in a third-party plugin, all bets are off until such time that an API is present for modifying that configuration data. =item $plugin->finish_parsing_end ( { options ... } ) Signals that the system-wide configuration parsing has just finished, and SpamAssassin is nearly ready to check messages. C<options> is a reference to a hash containing these options: =over 4 =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back Note: there are no guarantees that the internal data structures of SpamAssassin will not change from release to release. In particular to this plugin hook, if you modify the rules data structures in a third-party plugin, all bets are off until such time that an API is present for modifying that configuration data. =item $plugin->user_conf_parsing_start ( { options ... } ) Signals that the per-user configuration has been completely read, but not converted to internal data structures. It is possible to use this hook to dynamically change the configuration already read in or add new config options. If C<allow_user_rules> is enabled in the configuration, it is possible that additional rules have been added since the C<finish_parsing_start> plugin hook invocation was called. =over 4 =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back Note: there are no guarantees that the internal data structures of SpamAssassin will not change from release to release. In particular to this plugin hook, if you modify the rules data structures in a third-party plugin, all bets are off until such time that an API is present for modifying that configuration data. =item $plugin->user_conf_parsing_end ( { options ... } ) Signals that the per-user configuration parsing has just finished, and SpamAssassin is nearly ready to check messages. If C<allow_user_rules> is enabled in the configuration, it is possible that additional rules have been added since the C<finish_parsing_end> plugin hook invocation was called. C<options> is a reference to a hash containing these options: =over 4 =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back Note: there are no guarantees that the internal data structures of SpamAssassin will not change from release to release. In particular to this plugin hook, if you modify the rules data structures in a third-party plugin, all bets are off until such time that an API is present for modifying that configuration data. =item $plugin->signal_user_changed ( { options ... } ) Signals that the current user has changed for a new one. =over 4 =item username The new user's username. =item user_dir The new user's home directory. (equivalent to C<~>.) =item userstate_dir The new user's storage directory. (equivalent to C<~/.spamassassin>.) =back =item $plugin->services_authorized_for_username ( { options ... } ) Validates that a given username is authorized to use certain services. In order to authorize a user, the plugin should first check that it can handle any of the services passed into the method and then set the value for each allowed service to true (or any non-negative value). The current supported services are: bayessql =over 4 =item username A username =item services Reference to a hash containing the services you want to check. { 'bayessql' => 0 } =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back =item $plugin->compile_now_start ( { options ... } ) This is called at the beginning of Mail::SpamAssassin::compile_now() so plugins can do any necessary initialization for multi-process SpamAssassin (such as spamd or mass-check -j). =over 4 =item use_user_prefs The value of $use_user_prefs option in compile_now(). =item keep_userstate The value of $keep_userstate option in compile_now(). =back =item $plugin->compile_now_finish ( { options ... } ) This is called at the end of Mail::SpamAssassin::compile_now() so plugins can do any necessary initialization for multi-process SpamAssassin (such as spamd or mass-check -j). =over 4 =item use_user_prefs The value of $use_user_prefs option in compile_now(). =item keep_userstate The value of $keep_userstate option in compile_now(). =back =item $plugin->check_start ( { options ... } ) Signals that a message check operation is starting. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. Lifecycle note: it is recommended that rules that need to track test state on a per-scan basis should store that state on this object, not on the plugin object itself, since the plugin object will be shared between all active scanners. The message being scanned is accessible through the C<$permsgstatus-E<gt>get_message()> API; there are a number of other public APIs on that object, too. See C<Mail::SpamAssassin::PerMsgStatus> perldoc. =back =item $plugin->check_main ( { options ... } ) Signals that a message should be checked. Note that implementations of this hook should return C<1>. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_tick ( { options ... } ) Called periodically during a message check operation. A callback set for this method is a good place to run through an event loop dealing with network events triggered in a C<parse_metadata> method, for example. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_dnsbl ( { options ... } ) Called when DNSBL or other network lookups are being launched, implying current running priority of -100. This is the place to start your own asynchronously-started network lookups. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_post_dnsbl ( { options ... } ) Called after the DNSBL results have been harvested. This is a good place to harvest your own asynchronously-started network lookups. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_cleanup ( { options ... } ) Called just before message check is finishing and before possible auto-learning. This is guaranteed to be always called, unlike check_tick and check_post_dnsbl. Used for cleaning up left callbacks or forked children etc, last chance to make rules hit. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_post_learn ( { options ... } ) Called after auto-learning may (or may not) have taken place. If you wish to perform additional learning, whether or not auto-learning happens, this is the place to do it. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->check_end ( { options ... } ) Signals that a message check operation has just finished, and the results are about to be returned to the caller. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. The current score, names of rules that hit, etc. can be retrieved using the public APIs on this object. =back =item $plugin->finish_tests ( { options ... } ) Called via C<Mail::SpamAssassin::finish>. This should clear up any tests that a plugin has added to the namespace. In certain circumstances, plugins may find it useful to compile perl functions from the ruleset, on the fly. It is important to remove these once the C<Mail::SpamAssassin> object is deleted, however, and this API allows this. Each plugin is responsible for its own generated perl functions. =over 4 =item conf The C<Mail::SpamAssassin::Conf> object on which the configuration data should be stored. =back See also the C<register_generated_rule_method> helper API, below. =item $plugin->extract_metadata ( { options ... } ) Signals that a message is being mined for metadata. Some plugins may wish to add their own metadata as well. =over 4 =item msg The C<Mail::SpamAssassin::Message> object for this message. =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->parsed_metadata ( { options ... } ) Signals that a message's metadata has been parsed, and can now be accessed by the plugin. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->start_rules ( { options ... } ) Called before testing a set of rules of a given type and priority. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =item ruletype The type of the rules about to be performed. =item priority The priority level of the rules about to be performed. =back =item $plugin->hit_rule ( { options ... } ) Called when a rule fires. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =item ruletype The type of the rule that fired. =item rulename The name of the rule that fired. =item score The rule's score in the active scoreset. =back =item $plugin->ran_rule ( { options ... } ) Called after a rule has been tested, whether or not it fired. When the rule fires, the hit_rule callback is always called before this. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =item ruletype The type of the rule that was tested. =item rulename The name of the rule that was tested. =back =item $plugin->autolearn_discriminator ( { options ... } ) Control whether a just-scanned message should be learned as either spam or ham. This method should return one of C<1> to learn the message as spam, C<0> to learn as ham, or C<undef> to not learn from the message at all. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->autolearn ( { options ... } ) Signals that a message is about to be auto-learned as either ham or spam. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =item isspam C<1> if the message is spam, C<0> if ham. =back =item $plugin->per_msg_finish ( { options ... } ) Signals that a C<Mail::SpamAssassin::PerMsgStatus> object is being destroyed, and any per-scan context held on that object by this plugin should be destroyed as well. Normally, any member variables on the C<PerMsgStatus> object will be cleaned up automatically -- but if your plugin has made a circular reference on that object, this is the place to break them so that garbage collection can operate correctly. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->have_shortcircuited ( { options ... } ) Has the current scan operation 'short-circuited'? In other words, can further scanning be skipped, since the message is already definitively classified as either spam or ham? Plugins should return C<0> to indicate that scanning should continue, or C<1> to indicate that short-circuiting has taken effect. =over 4 =item permsgstatus The C<Mail::SpamAssassin::PerMsgStatus> context object for this scan. =back =item $plugin->bayes_learn ( { options ... } ) Called at the end of a bayes learn operation. This phase is the best place to map the raw (original) token value to the SHA1 hashed value. =over 4 =item toksref Reference to hash returned by call to tokenize. The hash takes the format of: { 'SHA1 Hash Value' => 'raw (original) value', ... } NOTE: This data structure has changed since it was originally introduced in version 3.0.0. The values are no longer perl anonymous hashes, they are a single string containing the raw token value. You can test for backward compatibility by checking to see if the value for a key is a reference to a perl HASH, for instance: if (ref($toksref->{$sometokenkey}) eq 'HASH') {... If it is, then you are using the old interface, otherwise you are using the current interface. =item isspam Boolean value stating what flavor of message the tokens represent, if true then message was specified as spam, false is nonspam. Note, when function is scan then isspam value is not valid. =item msgid Generated message id of the message just learned. =item msgatime Received date of the current message or current time if received date could not be determined. In addition, if the receive date is more than 24 hrs into the future it will be reset to current datetime. =back =item $plugin->bayes_forget ( { options ... } ) Called at the end of a bayes forget operation. =over 4 =item toksref Reference to hash returned by call to tokenize. See bayes_learn documentation for additional information on the format. =item isspam Boolean value stating what flavor of message the tokens represent, if true then message was specified as spam, false is nonspam. Note, when function is scan then isspam value is not valid. =item msgid Generated message id of the message just forgotten. =back =item $plugin->bayes_scan ( { options ... } ) Called at the end of a bayes scan operation. NOTE: Will not be called in case of error or if the message is otherwise skipped. =over 4 =item toksref Reference to hash returned by call to tokenize. See bayes_learn documentation for additional information on the format. =item probsref Reference to hash of calculated probabilities for tokens found in the database. { 'SHA1 Hash Value' => { 'prob' => 'calculated probability', 'spam_count' => 'Total number of spam msgs w/ token', 'ham_count' => 'Total number of ham msgs w/ token', 'atime' => 'Atime value for token in database' } } =item score Score calculated for this particular message. =item msgatime Calculated atime of the message just learned, note it may have been adjusted if it was determined to be too far into the future. =item significant_tokens Array ref of the tokens found to be significant in determining the score for this message. =back =item $plugin->plugin_report ( { options ... } ) Called if the message is to be reported as spam. If the reporting system is available, the variable C<$options-E<gt>{report}-E<gt>report_available}> should be set to C<1>; if the reporting system successfully reported the message, the variable C<$options-E<gt>{report}-E<gt>report_return}> should be set to C<1>. =over 4 =item report Reference to the Reporter object (C<$options-E<gt>{report}> in the paragraph above.) =item text Reference to a markup removed copy of the message in scalar string format. =item msg Reference to the original message object. =back =item $plugin->plugin_revoke ( { options ... } ) Called if the message is to be reported as ham (revokes a spam report). If the reporting system is available, the variable C<$options-E<gt>{revoke}-E<gt>revoke_available}> should be set to C<1>; if the reporting system successfully revoked the message, the variable C<$options-E<gt>{revoke}-E<gt>revoke_return}> should be set to C<1>. =over 4 =item revoke Reference to the Reporter object (C<$options-E<gt>{revoke}> in the paragraph above.) =item text Reference to a markup removed copy of the message in scalar string format. =item msg Reference to the original message object. =back =item $plugin->whitelist_address( { options ... } ) Called when a request is made to add an address to a persistent address list. =over 4 =item address Address you wish to add. =item cli_p Indicate if the call is being made from a command line interface. =back =item $plugin->blacklist_address( { options ... } ) Called when a request is made to add an address to a persistent address list. =over 4 =item address Address you wish to add. =item cli_p Indicate if the call is being made from a command line interface. =back =item $plugin->remove_address( { options ... } ) Called when a request is made to remove an address to a persistent address list. =over 4 =item address Address you wish to remove. =item cli_p Indicate if the call is being made from a command line interface. =back =item $plugin->spamd_child_init () Called in each new child process when it starts up under spamd. =item $plugin->log_scan_result ( { options ... } ) Called when spamd has completed scanning a message. Currently, only spamd calls this API. =over 4 =item result The C<'result: ...'> line for this scan. Format is as described at B<http://wiki.apache.org/spamassassin/SpamdSyslogFormat>. =back =item $plugin->spamd_child_post_connection_close () Called when child returns from handling a connection. If there was an accept failure, the child will die and this code will not be called. =item $plugin->finish () Called when the C<Mail::SpamAssassin> object is destroyed. =cut sub finish { my ($self) = @_; %{$self} = (); } =item $plugin->learner_new () Used to support human-trained probabilistic classifiers like the BAYES_* ruleset. Called when a new C<Mail::SpamAssassin::Bayes> object has been created; typically when a new user's scan is about to start. =item $plugin->learn_message () Train the classifier with a training message. =over 4 =item isspam 1 if the message is spam, 0 if it's non-spam. =item msg The message's C<Mail::SpamAssassin::Message> object. =item id An optional message-identification string, used internally to tag the message. If it is C<undef>, one will be generated. It should be unique to that message. =back =item $plugin->forget_message () Tell the classifier to 'forget' its training about a specific message. =over 4 =item msg The message's C<Mail::SpamAssassin::Message> object. =item id An optional message-identification string, used internally to tag the message. If it is C<undef>, one will be generated. It should be unique to that message. =back =item $plugin->learner_sync () Tell the classifier to 'sync' any pending changes against the current user's training database. This is called by C<sa-learn --sync>. If you do not need to implement these for your classifier, create an implementation that just contains C<return 1>. =item $plugin->learner_expire_old_training () Tell the classifier to perform infrequent, time-consuming cleanup of the current user's training database. This is called by C<sa-learn --force-expire>. If you do not need to implement these for your classifier, create an implementation that just contains C<return 1>. =item $plugin->learner_is_scan_available () Should return 1 if it is possible to use the current user's training data for a message-scan operation, or 0 otherwise. =item $plugin->learner_dump_database () Dump information about the current user's training data to C<stdout>. This is called by C<sa-learn --dump>. =over 4 =item magic Set to 1 if "magic" name-value metadata should be dumped. =item toks Set to 1 if the database of tokens should be dumped. =item regex Either C<undef> to dump all tokens, or a value which specifies a regular expression subset of the tokens to dump. =back =item $plugin->learner_close () Close any open databases. =over 4 =item quiet Set to 1 if warning messages should be suppressed. =back =back =head1 HELPER APIS These methods provide an API for plugins to register themselves to receive specific events, or control the callback chain behaviour. =over 4 =item $plugin->register_eval_rule ($nameofevalsub, $ruletype) Plugins that implement an eval test will need to call this, so that SpamAssassin calls into the object when that eval test is encountered. See the B<REGISTERING EVAL RULES> section for full details. Since 4.0, optional $ruletype can be specified to enforce that eval function cannot be called with wrong ruletype from configuration, for example user using "header FOO eval:foobar()" instead of "body FOO eval:foobar()". Mismatch will result in lint failure. $ruletype can be one of: $Mail::SpamAssassin::Conf::TYPE_HEAD_EVALS $Mail::SpamAssassin::Conf::TYPE_BODY_EVALS (allows both body and rawbody) $Mail::SpamAssassin::Conf::TYPE_RAWBODY_EVALS $Mail::SpamAssassin::Conf::TYPE_FULL_EVALS =cut sub register_eval_rule { my ($self, $nameofsub, $ruletype) = @_; $self->{main}->{conf}->register_eval_rule ($self, $nameofsub, $ruletype); } =item $plugin->register_generated_rule_method ($nameofsub) In certain circumstances, plugins may find it useful to compile perl functions from the ruleset, on the fly. It is important to remove these once the C<Mail::SpamAssassin> object is deleted, however, and this API allows this. Once the method C<$nameofsub> has been generated, call this API with the name of the method (including full package scope). This indicates that it's a temporary piece of generated code, built from the SpamAssassin ruleset, and when C<Mail::SpamAssassin::finish()> is called, the method will be destroyed. This API was added in SpamAssassin 3.2.0. =cut sub register_generated_rule_method { my ($self, $nameofsub) = @_; push @Mail::SpamAssassin::PerMsgStatus::TEMPORARY_METHODS, $nameofsub; } =item $plugin->register_method_priority($methodname, $priority) Indicate that the method named C<$methodname> on the current object has a callback priority of C<$priority>. This is used by the plugin handler to determine the relative order of callbacks; plugins with lower-numbered priorities are called before plugins with higher-numbered priorities. Each method can have a different priority value. The default value is C<0>. The ordering of callbacks to methods with equal priority is undefined. Typically, you only need to worry about this if you need to ensure your plugin's method is called before another plugin's implementation of that method. It should be called from your plugin's constructor. This API was added in SpamAssassin 3.2.0. =cut sub register_method_priority { my ($self, $methname, $pri) = @_; $self->{method_priority}->{$methname} = $pri; } =item $plugin->inhibit_further_callbacks() Tells the plugin handler to inhibit calling into other plugins in the plugin chain for the current callback. Frequently used when parsing configuration settings using C<parse_config()>. =back =cut sub inhibit_further_callbacks { my ($self) = @_; $self->{_inhibit_further_callbacks} = 1; } 1; __END__ =head1 LOGGING =over 4 =item Mail::SpamAssassin::Plugin::dbg($message) Output a debugging message C<$message>, if the SpamAssassin object is running with debugging turned on. I<NOTE:> This function is not available in the package namespace of general plugins and can't be called via $self->dbg(). If a plugin wishes to output debug information, it should call C<Mail::SpamAssassin::Plugin::dbg($msg)>. =item Mail::SpamAssassin::Plugin::info($message) Output an informational message C<$message>, if the SpamAssassin object is running with informational messages turned on. I<NOTE:> This function is not available in the package namespace of general plugins and can't be called via $self->info(). If a plugin wishes to output debug information, it should call C<Mail::SpamAssassin::Plugin::info($msg)>. In general, it is better for plugins to use the C<Mail::SpamAssassin::Logger> module to import C<dbg> and C<info> directly, like so: use Mail::SpamAssassin::Logger; dbg("some message"); info("some other message"); =back =head1 REGISTERING EVAL RULES Plugins that implement an eval test must register the methods that can be called from rules in the configuration files, in the plugin class' constructor. For example, $plugin->register_eval_rule ('check_for_foo', $Mail::SpamAssassin::Conf::TYPE_HEAD_EVALS) will cause C<$plugin-E<gt>check_for_foo()> to be called for this SpamAssassin rule: header FOO_RULE eval:check_for_foo() Note that eval rules are passed the following arguments: =over 4 =item - The plugin object itself =item - The C<Mail::SpamAssassin::PerMsgStatus> object calling the rule =item - standard arguments for the rule type in use =item - any and all arguments as specified in the configuration file =back In other words, the eval test method should look something like this: sub check_for_foo { my ($self, $permsgstatus, ...arguments...) = @_; ...code returning 0 or 1 } Note that the headers can be accessed using the C<get()> method on the C<Mail::SpamAssassin::PerMsgStatus> object, and the body by C<get_decoded_stripped_body_text_array()> and other similar methods. Similarly, the C<Mail::SpamAssassin::Conf> object holding the current configuration may be accessed through C<$permsgstatus-E<gt>{main}-E<gt>{conf}>. The eval rule should return C<1> for a hit, or C<0> if the rule is not hit. State for a single message being scanned should be stored on the C<$permsgstatus> object, not on the C<$self> object, since C<$self> persists between scan operations. See the 'lifecycle note' on the C<check_start()> method above. =head1 STANDARD ARGUMENTS FOR RULE TYPES Plugins will be called with the same arguments as a standard EvalTest. Different rule types receive different information by default: =over 4 =item - header tests: no extra arguments =item - body tests: fully rendered message as array reference =item - rawbody tests: fully decoded message as array reference =item - full tests: pristine message as scalar reference =back The configuration file arguments will be passed in after the standard arguments. =head1 BACKWARD COMPATIBILITY Note that if you write a plugin and need to determine if a particular helper method is supported on C<Mail::SpamAssassin::Plugin>, you can do this: if ($self->can("name_of_method")) { eval { $self->name_of_method(); # etc. } } else { # take fallback action } The same applies for the public APIs on objects of other types, such as C<Mail::SpamAssassin::PerMsgStatus>. =head1 SEE ALSO Mail::SpamAssassin(3) Mail::SpamAssassin::PerMsgStatus(3) http://wiki.apache.org/spamassassin/PluginWritingTips http://issues.apache.org/SpamAssassin/show_bug.cgi?id=2163 =cut
apache/spamassassin
lib/Mail/SpamAssassin/Plugin.pm
Perl
apache-2.0
32,946
package Paws::IAM::CreateLoginProfileResponse; use Moose; has LoginProfile => (is => 'ro', isa => 'Paws::IAM::LoginProfile', required => 1); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::IAM::CreateLoginProfileResponse =head1 ATTRIBUTES =head2 B<REQUIRED> LoginProfile => L<Paws::IAM::LoginProfile> A structure containing the user name and password create date. =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/IAM/CreateLoginProfileResponse.pm
Perl
apache-2.0
472
package Google::Ads::AdWords::v201406::CampaignService::mutateLabelResponse; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' } __PACKAGE__->__set_name('mutateLabelResponse'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %rval_of :ATTR(:get<rval>); __PACKAGE__->_factory( [ qw( rval ) ], { 'rval' => \%rval_of, }, { 'rval' => 'Google::Ads::AdWords::v201406::CampaignLabelReturnValue', }, { 'rval' => 'rval', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::CampaignService::mutateLabelResponse =head1 DESCRIPTION Perl data type class for the XML Schema defined element mutateLabelResponse from the namespace https://adwords.google.com/api/adwords/cm/v201406. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * rval $element->set_rval($data); $element->get_rval(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201406::CampaignService::mutateLabelResponse->new($data); Constructor. The following data structure may be passed to new(): { rval => $a_reference_to, # see Google::Ads::AdWords::v201406::CampaignLabelReturnValue }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/CampaignService/mutateLabelResponse.pm
Perl
apache-2.0
1,822
package # Date::Manip::Offset::off427; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:46 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-11:22:48'; %Offset = ( 0 => [ 'pacific/pago_pago', ], ); 1;
nriley/Pester
Source/Manip/Offset/off427.pm
Perl
bsd-2-clause
855
package # Date::Manip::TZ::amport01; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 10:41:42 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.org/tz use strict; use warnings; require 5.010000; our (%Dates,%LastRule); END { undef %Dates; undef %LastRule; } our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } %Dates = ( 1 => [ [ [1,1,2,0,0,0],[1,1,1,19,53,56],'-04:06:04',[-4,-6,-4], 'LMT',0,[1912,3,2,4,6,3],[1912,3,1,23,59,59], '0001010200:00:00','0001010119:53:56','1912030204:06:03','1912030123:59:59' ], ], 1912 => [ [ [1912,3,2,4,6,4],[1912,3,2,0,6,4],'-04:00:00',[-4,0,0], 'AST',0,[9999,12,31,0,0,0],[9999,12,30,20,0,0], '1912030204:06:04','1912030200:06:04','9999123100:00:00','9999123020:00:00' ], ], ); %LastRule = ( ); 1;
nriley/Pester
Source/Manip/TZ/amport01.pm
Perl
bsd-2-clause
1,277
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 1B00 1B4B 1B50 1B7C END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/Sc/Bali.pl
Perl
mit
443
package TAP::Parser::Result::Bailout; use strict; use vars qw($VERSION @ISA); use TAP::Parser::Result; @ISA = 'TAP::Parser::Result'; =head1 NAME TAP::Parser::Result::Bailout - Bailout result token. =head1 VERSION Version 3.28 =cut $VERSION = '3.28'; =head1 DESCRIPTION This is a subclass of L<TAP::Parser::Result>. A token of this class will be returned if a bail out line is encountered. 1..5 ok 1 - woo hooo! Bail out! Well, so much for "woo hooo!" =head1 OVERRIDDEN METHODS Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night. =over 4 =item * C<as_string> =back =cut ############################################################################## =head2 Instance Methods =head3 C<explanation> if ( $result->is_bailout ) { my $explanation = $result->explanation; print "We bailed out because ($explanation)"; } If, and only if, a token is a bailout token, you can get an "explanation" via this method. The explanation is the text after the mystical "Bail out!" words which appear in the tap output. =cut sub explanation { shift->{bailout} } sub as_string { shift->{bailout} } 1;
dj31416/JSX
extlib/lib/perl5/TAP/Parser/Result/Bailout.pm
Perl
mit
1,181
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter; =pod =head1 NAME Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter =head1 SYNOPSIS use Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter; my $string_handle = IO::String->new(); my $w = Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter->new( -SOURCE => 'Ensembl', -ALIGNED => 1, -HANDLE => $string_handle ); my $pt = $dba->get_GeneTreeAdaptor()->fetch_by_dbID(3); $w->write_trees($pt); $w->finish(); #YOU MUST CALL THIS TO WRITE THE FINAL TAG my $xml_scalar_ref = $string_handle->string_ref(); #Or to write to a file via IO::File my $file_handle = IO::File->new('output.xml', 'w'); $w = Bio::EnsEMBL::Compara::Graph::PhyloXMLWriter->new( -SOURCE => 'Ensembl', -ALIGNED => 1, -HANDLE => $file_handle ); $w->write_trees($pt); $w->finish(); #YOU MUST CALL THIS TO WRITE THE FINAL TAG $file_handle->close(); #Or letting this deal with it $w = Bio::EnsEMBL::Compara::Graph::PhyloXMLWriter->new( -SOURCE => 'Ensembl', -ALIGNED => 1, -FILE => 'loc.xml' ); $w->write_trees($pt); $w->finish(); #YOU MUST CALL THIS TO WRITE THE FINAL TAG $w->handle()->close(); =head1 DESCRIPTION Used as a way of emitting Compara GeneTrees in a format which conforms to L<PhyloXML|http://www.phyloxml.org/>. The code is built to work with instances of L<Bio::EnsEMBL::Compara::GeneTree> but can be extended to operate on any tree structure provided by the Compara Graph infrastructure. The code provides a number of property extensions to the existing PhyloXML standard: =over 8 =item B<Compara:genome_db_name> Used to show the name of the GenomeDB of the species found. Useful when taxonomy is not exact =item B<Compara:dubious_duplication> Indicates locations of potential duplications we are unsure about =back The same document is persistent between write_trees() calls so to create a new XML document create a new instance of this object. =head1 SUBROUTINES/METHODS See inline =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut use strict; use warnings; use Bio::EnsEMBL::Utils::Argument qw(rearrange); use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::Scalar qw(check_ref wrap_array); use base qw/Bio::EnsEMBL::Compara::Graph::PhyloXMLWriter/; =pod =head2 new() Arg[CDNA] : Boolean; indicates if we want CDNA emitted or peptide. Defaults to B<false>. Arg[ALIGNED] : Boolean; indicates if we want to emit aligned sequence. Defaults to B<false>. Arg[NO_SEQUENCES] : Boolean; indicates we want to ignore sequence dumping. Defaults to B<false>. Description : Creates a new tree writer object. Returntype : Instance of the writer Exceptions : None Example : my $w = Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter->new( -SOURCE => 'Ensembl', -ALIGNED => 1, -HANDLE => $handle ); Status : Stable =cut sub new { my ($class, @args) = @_; $class = ref($class) || $class; my $self = $class->SUPER::new(@args); my ($cdna, $aligned, $no_sequences) = rearrange([qw(cdna aligned no_sequences)], @args); $cdna ||= 0; if( ($cdna || $aligned) && $no_sequences) { warning "-CDNA or -ALIGNED was specified but so was -NO_SEQUENCES. Will ignore sequences"; } $self->cdna($cdna); $self->aligned($aligned); $self->no_sequences($no_sequences); return $self; } =pod =head2 cdna() Arg[0] : The value to set this to Description : Indicates if we want CDNA sequence in the XML. If false the code will dump peptide data Returntype : Boolean Exceptions : None Status : Stable =cut sub cdna { my ($self, $cdna) = @_; $self->{cdna} = $cdna if defined $cdna; return $self->{cdna}; } =pod =head2 no_sequences() Arg[0] : The value to set this to Description : Indicates if we do not want to perform sequence dumping Returntype : Boolean Exceptions : None Status : Stable =cut sub no_sequences { my ($self, $no_sequences) = @_; $self->{no_sequences} = $no_sequences if defined $no_sequences; return $self->{no_sequences}; } =pod =head2 aligned() Arg[0] : The value to set this to Description : Indicates if we want to push aligned sequences into the XML Returntype : Boolean Exceptions : None Status : Stable =cut sub aligned { my ($self, $aligned) = @_; $self->{aligned} = $aligned if defined $aligned; return $self->{aligned}; } sub tree_elements { my ($self, $tree) = @_; my $w = $self->_writer; $w->dataElement('property', $tree->stable_id(), 'datatype' => 'xsd:string', 'ref' => 'Compara:gene_tree_stable_id', 'applies_to' => 'phylogeny'); } sub dispatch_tag { my ($self, $node) = @_; if(check_ref($node, 'Bio::EnsEMBL::Compara::GeneTreeMember')) { return $self->_member_tag($node); } elsif(check_ref($node, 'Bio::EnsEMBL::Compara::GeneTreeNode')) { return $self->_node_tag($node); } my $ref = ref($node); throw("Cannot process type $ref"); } sub dispatch_body { my ($self, $node) = @_; if(check_ref($node, 'Bio::EnsEMBL::Compara::GeneTreeMember')) { $self->_node_body($node , 1); #Used to defer taxonomy writing $self->_write_seq_member($node); return; } elsif(check_ref($node, 'Bio::EnsEMBL::Compara::GeneTreeNode')) { $self->_node_body($node); return; } my $ref = ref($node); throw("Cannot process type $ref"); return; } ###### PROCESSORS #tags return [ 'tag', {attributes} ] sub _node_tag { my ($self, $node) = @_; return ['clade', {branch_length => $node->distance_to_parent()}]; } #body writes data sub _node_body { my ($self, $node, $defer_taxonomy) = @_; my $type = $node->node_type(); my $is_dup = ((defined $type) and ($type eq "duplication" || $type eq "dubious")) ? 1 : 0; my $boot = $node->bootstrap(); my $stn = $node->species_tree_node(); my $w = $self->_writer(); # The elements must be in the same order as in the .xsd !! if($boot) { $w->dataElement('confidence', $boot, 'type' => 'bootstrap'); } if ($is_dup) { $w->dataElement('confidence', $node->duplication_confidence_score(), 'type' => 'duplication_confidence_score'); } if(!$defer_taxonomy && $stn) { $self->_write_species_tree_node($stn); } if ($is_dup) { $w->startTag('events'); $w->dataElement('type', 'speciation_or_duplication'); $w->dataElement('duplications', 1); $w->endTag(); } if((defined $type) and ($type eq "dubious")) { $w->dataElement('property', 'dubious_duplication', 'datatype' => 'xsd:int', 'ref' => 'Compara:dubious_duplication', 'applies_to' => 'clade' ); } return; } sub _member_tag { my ($self, $node) = @_; return $self->_node_tag($node); } sub tree_type { return "gene tree"; } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/Graph/GeneTreePhyloXMLWriter.pm
Perl
apache-2.0
7,751
#------------------------------------------------------------------------------ # File: MPF.pm # # Description: Read Multi-Picture Format information # # Revisions: 06/12/2009 - P. Harvey Created # # References: 1) http://www.cipa.jp/std/documents/e/DC-007_E.pdf #------------------------------------------------------------------------------ package Image::ExifTool::MPF; use strict; use vars qw($VERSION); use Image::ExifTool qw(:DataAccess :Utils); use Image::ExifTool::Exif; $VERSION = '1.14'; sub ProcessMPImageList($$$); # Tags found in APP2 MPF segment in JPEG images %Image::ExifTool::MPF::Main = ( GROUPS => { 0 => 'MPF', 1 => 'MPF0', 2 => 'Image'}, NOTES => q{ These tags are part of the CIPA Multi-Picture Format specification, and are found in the APP2 "MPF" segment of JPEG images. MPImage data referenced from this segment is stored as a JPEG trailer. The MPF tags are not writable, however the MPF segment may be deleted as a group (with "MPF:All") but then the JPEG trailer should also be deleted (with "Trailer:All"). See L<http://www.cipa.jp/std/documents/e/DC-007_E.pdf> for the official specification. }, 0xb000 => 'MPFVersion', 0xb001 => 'NumberOfImages', 0xb002 => { Name => 'MPImageList', SubDirectory => { TagTable => 'Image::ExifTool::MPF::MPImage', ProcessProc => \&ProcessMPImageList, }, }, 0xb003 => { Name => 'ImageUIDList', Binary => 1, }, 0xb004 => 'TotalFrames', 0xb101 => 'MPIndividualNum', 0xb201 => { Name => 'PanOrientation', PrintHex => 1, Notes => 'long integer is split into 4 bytes', ValueConv => 'join(" ",unpack("C*",pack("N",$val)))', PrintConv => [ '"$val rows"', '"$val columns"', { 0 => '[unused]', 1 => 'Start at top right', 2 => 'Start at top left', 3 => 'Start at bottom left', 4 => 'Start at bottom right', }, { 0x01 => 'Left to right', 0x02 => 'Right to left', 0x03 => 'Top to bottom', 0x04 => 'Bottom to top', 0x10 => 'Clockwise', 0x20 => 'Counter clockwise', 0x30 => 'Zigzag (row start)', 0x40 => 'Zigzag (column start)', }, ], }, 0xb202 => 'PanOverlapH', 0xb203 => 'PanOverlapV', 0xb204 => 'BaseViewpointNum', 0xb205 => 'ConvergenceAngle', 0xb206 => 'BaselineLength', 0xb207 => 'VerticalDivergence', 0xb208 => 'AxisDistanceX', 0xb209 => 'AxisDistanceY', 0xb20a => 'AxisDistanceZ', 0xb20b => 'YawAngle', 0xb20c => 'PitchAngle', 0xb20d => 'RollAngle', ); # Tags found in MPImage structure %Image::ExifTool::MPF::MPImage = ( PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData, #WRITE_PROC => \&Image::ExifTool::WriteBinaryData, #CHECK_PROC => \&Image::ExifTool::CheckBinaryData, #WRITABLE => 1, GROUPS => { 0 => 'MPF', 1 => 'MPImage', 2 => 'Image'}, NOTES => q{ The first MPF "Large Thumbnail" image is extracted as PreviewImage, and the rest of the embedded MPF images are extracted as MPImage#. The L<ExtractEmbedded|../ExifTool.html#ExtractEmbedded> (-ee) option may be used to extract information from these embedded images. }, 0.1 => { Name => 'MPImageFlags', Format => 'int32u', Mask => 0xf8000000, PrintConv => { BITMASK => { 2 => 'Representative image', 3 => 'Dependent child image', 4 => 'Dependent parent image', }}, }, 0.2 => { Name => 'MPImageFormat', Format => 'int32u', Mask => 0x07000000, PrintConv => { 0 => 'JPEG', }, }, 0.3 => { Name => 'MPImageType', Format => 'int32u', Mask => 0x00ffffff, PrintHex => 1, PrintConv => { 0x000000 => 'Undefined', 0x010001 => 'Large Thumbnail (VGA equivalent)', 0x010002 => 'Large Thumbnail (full HD equivalent)', 0x020001 => 'Multi-frame Panorama', 0x020002 => 'Multi-frame Disparity', 0x020003 => 'Multi-angle', 0x030000 => 'Baseline MP Primary Image', }, }, 4 => { Name => 'MPImageLength', Format => 'int32u', }, 8 => { Name => 'MPImageStart', Format => 'int32u', IsOffset => '$val', }, 12 => { Name => 'DependentImage1EntryNumber', Format => 'int16u', }, 14 => { Name => 'DependentImage2EntryNumber', Format => 'int16u', }, ); # extract MP Images as composite tags %Image::ExifTool::MPF::Composite = ( GROUPS => { 2 => 'Preview' }, MPImage => { Require => { 0 => 'MPImageStart', 1 => 'MPImageLength', 2 => 'MPImageType', }, Notes => q{ the first MPF "Large Thumbnail" is extracted as PreviewImage, and the rest of the embedded MPF images are extracted as MPImage#. The L<ExtractEmbedded|../ExifTool.html#ExtractEmbedded> option may be used to extract information from these embedded images. }, # extract all MPF images (not just one) RawConv => q{ require Image::ExifTool::MPF; @grps = $self->GetGroup($$val{0}); # set groups from input tag Image::ExifTool::MPF::ExtractMPImages($self); }, }, ); # add our composite tags Image::ExifTool::AddCompositeTags('Image::ExifTool::MPF'); #------------------------------------------------------------------------------ # Extract all MP images # Inputs: 0) ExifTool object ref # Returns: undef sub ExtractMPImages($) { my $et = shift; my $ee = $et->Options('ExtractEmbedded'); my $saveBinary = $et->Options('Binary'); my ($i, $didPreview, $xtra); for ($i=1; $xtra or not defined $xtra; ++$i) { # run through MP images in the same order they were extracted $xtra = defined $$et{VALUE}{"MPImageStart ($i)"} ? " ($i)" : ''; my $off = $et->GetValue("MPImageStart$xtra", 'ValueConv'); my $len = $et->GetValue("MPImageLength$xtra", 'ValueConv'); if ($off and $len) { my $type = $et->GetValue("MPImageType$xtra", 'ValueConv'); my $tag = "MPImage$i"; # store first "Large Thumbnail" as a PreviewImage if (not $didPreview and $type and ($type & 0x0f0000) == 0x010000) { $tag = 'PreviewImage'; $didPreview = 1; } $et->Options('Binary', 1) if $ee; my $val = Image::ExifTool::Exif::ExtractImage($et, $off, $len, $tag); $et->Options('Binary', $saveBinary) if $ee; next unless defined $val; unless ($Image::ExifTool::Extra{$tag}) { AddTagToTable(\%Image::ExifTool::Extra, $tag, { Name => $tag, Groups => { 0 => 'Composite', 1 => 'Composite', 2 => 'Preview'}, }); } my $key = $et->FoundTag($tag, $val, $et->GetGroup("MPImageStart$xtra")); # extract information from MP images if ExtractEmbedded option used if ($ee) { my $oldBase = $$et{BASE}; $$et{BASE} = $off; $$et{DOC_NUM} = $i; $et->ExtractInfo($val, { ReEntry => 1 }); delete $$et{DOC_NUM}; $$et{BASE} = $oldBase; } } } return undef; } #------------------------------------------------------------------------------ # Process MP Entry list # Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref # Returns: 1 on success sub ProcessMPImageList($$$) { my ($et, $dirInfo, $tagTablePtr) = @_; my $num = int($$dirInfo{DirLen} / 16); # (16 bytes per MP Entry) $$dirInfo{DirLen} = 16; my ($i, $success); my $oldG1 = $$et{SET_GROUP1}; for ($i=0; $i<$num; ++$i) { $$et{SET_GROUP1} = '+' . ($i + 1); $success = $et->ProcessBinaryData($dirInfo, $tagTablePtr); $$dirInfo{DirStart} += 16; } $$et{SET_GROUP1} = $oldG1; return $success; } 1; # end __END__ =head1 NAME Image::ExifTool::MPF - Read Multi-Picture Format information =head1 SYNOPSIS This module is used by Image::ExifTool =head1 DESCRIPTION This module contains tag definitions and routines to read Multi-Picture Format (MPF) information from JPEG images. =head1 AUTHOR Copyright 2003-2020, Phil Harvey (philharvey66 at gmail.com) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 REFERENCES =over 4 =item L<http://www.cipa.jp/std/documents/e/DC-007_E.pdf> =back =head1 SEE ALSO L<Image::ExifTool::TagNames/MPF Tags>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
musselwhizzle/Focus-Points
focuspoints.lrdevplugin/bin/exiftool/lib/Image/ExifTool/MPF.pm
Perl
apache-2.0
9,115
package Moose::Meta::Method::Accessor::Native::Array::clear; BEGIN { $Moose::Meta::Method::Accessor::Native::Array::clear::AUTHORITY = 'cpan:STEVAN'; } { $Moose::Meta::Method::Accessor::Native::Array::clear::VERSION = '2.0602'; } use strict; use warnings; use Moose::Role; with 'Moose::Meta::Method::Accessor::Native::Array::Writer' => { -excludes => [ qw( _maximum_arguments _inline_optimized_set_new_value _return_value ) ] }; sub _maximum_arguments { 0 } sub _adds_members { 0 } sub _potential_value { '[]' } sub _inline_optimized_set_new_value { my $self = shift; my ($inv, $new, $slot_access) = @_; return $slot_access . ' = [];'; } sub _return_value { '' } no Moose::Role; 1;
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/Moose/Meta/Method/Accessor/Native/Array/clear.pm
Perl
bsd-3-clause
773
package Moose::Meta::Role::Composite; BEGIN { $Moose::Meta::Role::Composite::AUTHORITY = 'cpan:STEVAN'; } { $Moose::Meta::Role::Composite::VERSION = '2.0602'; } use strict; use warnings; use metaclass; use Class::Load qw(load_class); use Scalar::Util 'blessed'; use base 'Moose::Meta::Role'; # NOTE: # we need to override the ->name # method from Class::MOP::Package # since we don't have an actual # package for this. # - SL __PACKAGE__->meta->add_attribute('name' => ( reader => 'name', Class::MOP::_definition_context(), )); # NOTE: # Again, since we don't have a real # package to store our methods in, # we use a HASH ref instead. # - SL __PACKAGE__->meta->add_attribute('_methods' => ( reader => '_method_map', default => sub { {} }, Class::MOP::_definition_context(), )); __PACKAGE__->meta->add_attribute( 'application_role_summation_class', reader => 'application_role_summation_class', default => 'Moose::Meta::Role::Application::RoleSummation', Class::MOP::_definition_context(), ); sub new { my ($class, %params) = @_; # the roles param is required ... foreach ( @{$params{roles}} ) { unless ( $_->isa('Moose::Meta::Role') ) { require Moose; Moose->throw_error("The list of roles must be instances of Moose::Meta::Role, not $_"); } } my @composition_roles = map { $_->composition_class_roles } @{ $params{roles} }; if (@composition_roles) { my $meta = Moose::Meta::Class->create_anon_class( superclasses => [ $class ], roles => [ @composition_roles ], cache => 1, ); $class = $meta->name; } # and the name is created from the # roles if one has not been provided $params{name} ||= (join "|" => map { $_->name } @{$params{roles}}); $class->_new(\%params); } # This is largely a copy of what's in Moose::Meta::Role (itself # largely a copy of Class::MOP::Class). However, we can't actually # call add_package_symbol, because there's no package to which which # add the symbol. sub add_method { my ($self, $method_name, $method) = @_; unless ( defined $method_name && $method_name ) { Moose->throw_error("You must define a method name"); } my $body; if (blessed($method)) { $body = $method->body; if ($method->package_name ne $self->name) { $method = $method->clone( package_name => $self->name, name => $method_name ) if $method->can('clone'); } } else { $body = $method; $method = $self->wrap_method_body( body => $body, name => $method_name ); } $self->_method_map->{$method_name} = $method; } sub get_method_list { my $self = shift; return keys %{ $self->_method_map }; } sub _get_local_methods { my $self = shift; return values %{ $self->_method_map }; } sub has_method { my ($self, $method_name) = @_; return exists $self->_method_map->{$method_name}; } sub get_method { my ($self, $method_name) = @_; return $self->_method_map->{$method_name}; } sub apply_params { my ($self, $role_params) = @_; load_class($self->application_role_summation_class); $self->application_role_summation_class->new( role_params => $role_params, )->apply($self); return $self; } sub reinitialize { my ( $class, $old_meta, @args ) = @_; Moose->throw_error( 'Moose::Meta::Role::Composite instances can only be reinitialized from an existing metaclass instance' ) if !blessed $old_meta || !$old_meta->isa('Moose::Meta::Role::Composite'); my %existing_classes = map { $_ => $old_meta->$_() } qw( application_role_summation_class ); return $old_meta->meta->clone_object( $old_meta, %existing_classes, @args ); } 1; # ABSTRACT: An object to represent the set of roles =pod =head1 NAME Moose::Meta::Role::Composite - An object to represent the set of roles =head1 VERSION version 2.0602 =head1 DESCRIPTION A composite is a role that consists of a set of two or more roles. The API of a composite role is almost identical to that of a regular role. =head1 INHERITANCE C<Moose::Meta::Role::Composite> is a subclass of L<Moose::Meta::Role>. =head2 METHODS =over 4 =item B<< Moose::Meta::Role::Composite->new(%options) >> This returns a new composite role object. It accepts the same options as its parent class, with a few changes: =over 8 =item * roles This option is an array reference containing a list of L<Moose::Meta::Role> object. This is a required option. =item * name If a name is not given, one is generated from the roles provided. =item * apply_params(\%role_params) Creates a new RoleSummation role application with C<%role_params> and applies the composite role to it. The RoleSummation role application class used is determined by the composite role's C<application_role_summation_class> attribute. =item * reinitialize($metaclass) Like C<< Class::MOP::Package->reinitialize >>, but doesn't allow passing a string with the package name, as there is no real package for composite roles. =back =back =head1 BUGS See L<Moose/BUGS> for details on reporting bugs. =head1 AUTHOR Moose is maintained by the Moose Cabal, along with the help of many contributors. See L<Moose/CABAL> and L<Moose/CONTRIBUTORS> for details. =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2012 by Infinity Interactive, Inc.. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut __END__
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/Moose/Meta/Role/Composite.pm
Perl
bsd-3-clause
5,708
package File::Copy::Recursive; use strict; BEGIN { # Keep older versions of Perl from trying to use lexical warnings $INC{'warnings.pm'} = "fake warnings entry for < 5.6 perl ($])" if $] < 5.006; } use warnings; use Carp; use File::Copy; use File::Spec; #not really needed because File::Copy already gets it, but for good measure :) use vars qw( @ISA @EXPORT_OK $VERSION $MaxDepth $KeepMode $CPRFComp $CopyLink $PFSCheck $RemvBase $NoFtlPth $ForcePth $CopyLoop $RMTrgFil $RMTrgDir $CondCopy $BdTrgWrn $SkipFlop ); require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw(fcopy rcopy dircopy fmove rmove dirmove pathmk pathrm pathempty pathrmdir); $VERSION = '0.36'; $MaxDepth = 0; $KeepMode = 1; $CPRFComp = 0; $CopyLink = eval { local $SIG{'__DIE__'};symlink '',''; 1 } || 0; $PFSCheck = 1; $RemvBase = 0; $NoFtlPth = 0; $ForcePth = 0; $CopyLoop = 0; $RMTrgFil = 0; $RMTrgDir = 0; $CondCopy = {}; $BdTrgWrn = 0; $SkipFlop = 0; my $samecheck = sub { return 1 if $^O eq 'MSWin32'; # need better way to check for this on winders... return if @_ != 2 || !defined $_[0] || !defined $_[1]; return if $_[0] eq $_[1]; my $one = ''; if($PFSCheck) { $one = join( '-', ( stat $_[0] )[0,1] ) || ''; my $two = join( '-', ( stat $_[1] )[0,1] ) || ''; if ( $one eq $two && $one ) { carp "$_[0] and $_[1] are identical"; return; } } if(-d $_[0] && !$CopyLoop) { $one = join( '-', ( stat $_[0] )[0,1] ) if !$one; my $abs = File::Spec->rel2abs($_[1]); my @pth = File::Spec->splitdir( $abs ); while(@pth) { my $cur = File::Spec->catdir(@pth); last if !$cur; # probably not necessary, but nice to have just in case :) my $two = join( '-', ( stat $cur )[0,1] ) || ''; if ( $one eq $two && $one ) { # $! = 62; # Too many levels of symbolic links carp "Caught Deep Recursion Condition: $_[0] contains $_[1]"; return; } pop @pth; } } return 1; }; my $move = sub { my $fl = shift; my @x; if($fl) { @x = fcopy(@_) or return; } else { @x = dircopy(@_) or return; } if(@x) { if($fl) { unlink $_[0] or return; } else { pathrmdir($_[0]) or return; } if($RemvBase) { my ($volm, $path) = File::Spec->splitpath($_[0]); pathrm(File::Spec->catpath($volm,$path,''), $ForcePth, $NoFtlPth) or return; } } return wantarray ? @x : $x[0]; }; my $ok_todo_asper_condcopy = sub { my $org = shift; my $copy = 1; if(exists $CondCopy->{$org}) { if($CondCopy->{$org}{'md5'}) { } if($copy) { } } return $copy; }; sub fcopy { $samecheck->(@_) or return; if($RMTrgFil && (-d $_[1] || -e $_[1]) ) { my $trg = $_[1]; if( -d $trg ) { my @trgx = File::Spec->splitpath( $_[0] ); $trg = File::Spec->catfile( $_[1], $trgx[ $#trgx ] ); } $samecheck->($_[0], $trg) or return; if(-e $trg) { if($RMTrgFil == 1) { unlink $trg or carp "\$RMTrgFil failed: $!"; } else { unlink $trg or return; } } } my ($volm, $path) = File::Spec->splitpath($_[1]); if($path && !-d $path) { pathmk(File::Spec->catpath($volm,$path,''), $NoFtlPth); } if( -l $_[0] && $CopyLink ) { carp "Copying a symlink ($_[0]) whose target does not exist" if !-e readlink($_[0]) && $BdTrgWrn; symlink readlink(shift()), shift() or return; } else { copy(@_) or return; my @base_file = File::Spec->splitpath($_[0]); my $mode_trg = -d $_[1] ? File::Spec->catfile($_[1], $base_file[ $#base_file ]) : $_[1]; chmod scalar((stat($_[0]))[2]), $mode_trg if $KeepMode; } return wantarray ? (1,0,0) : 1; # use 0's incase they do math on them and in case rcopy() is called in list context = no uninit val warnings } sub rcopy { -d $_[0] || substr( $_[0], ( 1 * -1), 1) eq '*' ? dircopy(@_) : fcopy(@_); } sub dircopy { if($RMTrgDir && -d $_[1]) { if($RMTrgDir == 1) { pathrmdir($_[1]) or carp "\$RMTrgDir failed: $!"; } else { pathrmdir($_[1]) or return; } } my $globstar = 0; my $_zero = $_[0]; my $_one = $_[1]; if ( substr( $_zero, ( 1 * -1 ), 1 ) eq '*') { $globstar = 1; $_zero = substr( $_zero, 0, ( length( $_zero ) - 1 ) ); } $samecheck->( $_zero, $_[1] ) or return; if ( !-d $_zero || ( -e $_[1] && !-d $_[1] ) ) { $! = 20; return; } if(!-d $_[1]) { pathmk($_[1], $NoFtlPth) or return; } else { if($CPRFComp && !$globstar) { my @parts = File::Spec->splitdir($_zero); while($parts[ $#parts ] eq '') { pop @parts; } $_one = File::Spec->catdir($_[1], $parts[$#parts]); } } my $baseend = $_one; my $level = 0; my $filen = 0; my $dirn = 0; my $recurs; #must be my()ed before sub {} since it calls itself $recurs = sub { my ($str,$end,$buf) = @_; $filen++ if $end eq $baseend; $dirn++ if $end eq $baseend; mkdir $end or return if !-d $end; chmod scalar((stat($str))[2]), $end if $KeepMode; if($MaxDepth && $MaxDepth =~ m/^\d+$/ && $level >= $MaxDepth) { return ($filen,$dirn,$level) if wantarray; return $filen; } $level++; my @files; if ( $] < 5.006 ) { opendir(STR_DH, $str) or return; @files = grep( $_ ne '.' && $_ ne '..', readdir(STR_DH)); closedir STR_DH; } else { opendir(my $str_dh, $str) or return; @files = grep( $_ ne '.' && $_ ne '..', readdir($str_dh)); closedir $str_dh; } for my $file (@files) { my ($file_ut) = $file =~ m{ (.*) }xms; my $org = File::Spec->catfile($str, $file_ut); my $new = File::Spec->catfile($end, $file_ut); if( -l $org && $CopyLink ) { carp "Copying a symlink ($org) whose target does not exist" if !-e readlink($org) && $BdTrgWrn; symlink readlink($org), $new or return; } elsif(-d $org) { $recurs->($org,$new,$buf) if defined $buf; $recurs->($org,$new) if !defined $buf; $filen++; $dirn++; } else { if($ok_todo_asper_condcopy->($org)) { if($SkipFlop) { fcopy($org,$new,$buf) or next if defined $buf; fcopy($org,$new) or next if !defined $buf; } else { fcopy($org,$new,$buf) or return if defined $buf; fcopy($org,$new) or return if !defined $buf; } chmod scalar((stat($org))[2]), $new if $KeepMode; $filen++; } } } 1; }; $recurs->($_zero, $_one, $_[2]) or return; return wantarray ? ($filen,$dirn,$level) : $filen; } sub fmove { $move->(1, @_) } sub rmove { my $_zero = shift; $_zero = substr( $_zero, 0, ( length( $_zero ) - 1 ) ) if substr( $_[0], ( 1 * -1), 1) eq '*'; -d $_zero ? dirmove($_zero, @_) : fmove($_zero, @_); } sub dirmove { $move->(0, @_) } sub pathmk { my @parts = File::Spec->splitdir( shift() ); my $nofatal = shift; my $pth = $parts[0]; my $zer = 0; if(!$pth) { $pth = File::Spec->catdir($parts[0],$parts[1]); $zer = 1; } for($zer..$#parts) { mkdir $pth or return if !-d $pth && !$nofatal; mkdir $pth if !-d $pth && $nofatal; $pth = File::Spec->catdir($pth, $parts[$_ + 1]) unless $_ == $#parts; } 1; } sub pathempty { my $pth = shift; return 2 if !-d $pth; my @names; my $pth_dh; if ( $] < 5.006 ) { opendir(PTH_DH, $pth) or return; @names = grep !/^\.+$/, readdir(PTH_DH); } else { opendir($pth_dh, $pth) or return; @names = grep !/^\.+$/, readdir($pth_dh); } for my $name (@names) { my ($name_ut) = $name =~ m{ (.*) }xms; my $flpth = File::Spec->catdir($pth, $name_ut); if( -l $flpth ) { unlink $flpth or return; } elsif(-d $flpth) { pathrmdir($flpth) or return; } else { unlink $flpth or return; } } if ( $] < 5.006 ) { closedir PTH_DH; } else { closedir $pth_dh; } 1; } sub pathrm { my $path = shift; return 2 if !-d $path; my @pth = File::Spec->splitdir( $path ); my $force = shift; while(@pth) { my $cur = File::Spec->catdir(@pth); last if !$cur; # necessary ??? if(!shift()) { pathempty($cur) or return if $force; rmdir $cur or return; } else { pathempty($cur) if $force; rmdir $cur; } pop @pth; } 1; } sub pathrmdir { my $dir = shift; if( -e $dir ) { return if !-d $dir; } else { return 2; } pathempty($dir) or return; rmdir $dir or return; } 1; __END__ =head1 NAME File::Copy::Recursive - Perl extension for recursively copying files and directories =head1 SYNOPSIS use File::Copy::Recursive qw(fcopy rcopy dircopy fmove rmove dirmove); fcopy($orig,$new[,$buf]) or die $!; rcopy($orig,$new[,$buf]) or die $!; dircopy($orig,$new[,$buf]) or die $!; fmove($orig,$new[,$buf]) or die $!; rmove($orig,$new[,$buf]) or die $!; dirmove($orig,$new[,$buf]) or die $!; =head1 DESCRIPTION This module copies and moves directories recursively (or single files, well... singley) to an optional depth and attempts to preserve each file or directory's mode. =head1 EXPORT None by default. But you can export all the functions as in the example above and the path* functions if you wish. =head2 fcopy() This function uses File::Copy's copy() function to copy a file but not a directory. Any directories are recursively created if need be. One difference to File::Copy::copy() is that fcopy attempts to preserve the mode (see Preserving Mode below) The optional $buf in the synopsis if the same as File::Copy::copy()'s 3rd argument returns the same as File::Copy::copy() in scalar context and 1,0,0 in list context to accomidate rcopy()'s list context on regular files. (See below for more info) =head2 dircopy() This function recursively traverses the $orig directory's structure and recursively copies it to the $new directory. $new is created if necessary (multiple non existant directories is ok (IE foo/bar/baz). The script logically and portably creates all of them if necessary). It attempts to preserve the mode (see Preserving Mode below) and by default it copies all the way down into the directory, (see Managing Depth) below. If a directory is not specified it croaks just like fcopy croaks if its not a file that is specified. returns true or false, for true in scalar context it returns the number of files and directories copied, In list context it returns the number of files and directories, number of directories only, depth level traversed. my $num_of_files_and_dirs = dircopy($orig,$new); my($num_of_files_and_dirs,$num_of_dirs,$depth_traversed) = dircopy($orig,$new); Normally it stops and return's if a copy fails, to continue on regardless set $File::Copy::Recursive::SkipFlop to true. local $File::Copy::Recursive::SkipFlop = 1; That way it will copy everythgingit can ina directory and won't stop because of permissions, etc... =head2 rcopy() This function will allow you to specify a file *or* directory. It calls fcopy() if its a file and dircopy() if its a directory. If you call rcopy() (or fcopy() for that matter) on a file in list context, the values will be 1,0,0 since no directories and no depth are used. This is important becasue if its a directory in list context and there is only the initial directory the return value is 1,1,1. =head2 fmove() Copies the file then removes the original. You can manage the path the original file is in according to $RemvBase. =head2 dirmove() Uses dircopy() to copy the directory then removes the original. You can manage the path the original directory is in according to $RemvBase. =head2 rmove() Like rcopy() but calls fmove() or dirmove() instead. =head3 $RemvBase Default is false. When set to true the *move() functions will not only attempt to remove the original file or directory but will remove the given path it is in. So if you: rmove('foo/bar/baz', '/etc/'); # "baz" is removed from foo/bar after it is successfully copied to /etc/ local $File::Copy::Recursive::Remvbase = 1; rmove('foo/bar/baz','/etc/'); # if baz is successfully copied to /etc/ : # first "baz" is removed from foo/bar # then "foo/bar is removed via pathrm() =head4 $ForcePth Default is false. When set to true it calls pathempty() before any directories are removed to empty the directory so it can be rmdir()'ed when $RemvBase is in effect. =head2 Creating and Removing Paths =head3 $NoFtlPth Default is false. If set to true rmdir(), mkdir(), and pathempty() calls in pathrm() and pathmk() do not return() on failure. If its set to true they just silently go about their business regardless. This isn't a good idea but its there if you want it. =head3 Path functions These functions exist soley because they were necessary for the move and copy functions to have the features they do and not because they are of themselves the purpose of this module. That being said, here is how they work so you can understand how the copy and move funtions work and use them by themselves if you wish. =head4 pathrm() Removes a given path recursively. It removes the *entire* path so be carefull!!! Returns 2 if the given path is not a directory. File::Copy::Recursive::pathrm('foo/bar/baz') or die $!; # foo no longer exists Same as: rmdir 'foo/bar/baz' or die $!; rmdir 'foo/bar' or die $!; rmdir 'foo' or die $!; An optional second argument makes it call pathempty() before any rmdir()'s when set to true. File::Copy::Recursive::pathrm('foo/bar/baz', 1) or die $!; # foo no longer exists Same as: File::Copy::Recursive::pathempty('foo/bar/baz') or die $!; rmdir 'foo/bar/baz' or die $!; File::Copy::Recursive::pathempty('foo/bar/') or die $!; rmdir 'foo/bar' or die $!; File::Copy::Recursive::pathempty('foo/') or die $!; rmdir 'foo' or die $!; An optional third argument acts like $File::Copy::Recursive::NoFtlPth, again probably not a good idea. =head4 pathempty() Recursively removes the given directory's contents so it is empty. returns 2 if argument is not a directory, 1 on successfully emptying the directory. File::Copy::Recursive::pathempty($pth) or die $!; # $pth is now an empty directory =head4 pathmk() Creates a given path recursively. Creates foo/bar/baz even if foo does not exist. File::Copy::Recursive::pathmk('foo/bar/baz') or die $!; An optional second argument if true acts just like $File::Copy::Recursive::NoFtlPth, which means you'd never get your die() if something went wrong. Again, probably a *bad* idea. =head4 pathrmdir() Same as rmdir() but it calls pathempty() first to recursively empty it first since rmdir can not remove a directory with contents. Just removes the top directory the path given insetad of the entire path like pathrm(). Return 2 if the given argument is not a directory. =head2 Preserving Mode By default a quiet attempt is made to change the new file or directory to the mode of the old one. To turn this behavior off set $File::Copy::Recursive::KeepMode to false; =head2 Managing Depth You can set the maximum depth a directory structure is recursed by setting: $File::Copy::Recursive::MaxDepth to a whole number greater than 0. =head2 SymLinks If your system supports symlinks then symlinks will be copied as symlinks instead of as the target file. Perl's symlink() is used instead of File::Copy's copy() You can customize this behavior by setting $File::Copy::Recursive::CopyLink to a true or false value. It is already set to true or false dending on your system's support of symlinks so you can check it with an if statement to see how it will behave: if($File::Copy::Recursive::CopyLink) { print "Symlinks will be preserved\n"; } else { print "Symlinks will not be preserved because your system does not support it\n"; } If symlinks are being copied you can set $File::Copy::Recursive::BdTrgWrn to true to make it carp when it copies a link whose target does not exist. Its false by default. local $File::Copy::Recursive::BdTrgWrn = 1; =head2 Removing existing target file or directory before copying. This can be done by setting $File::Copy::Recursive::RMTrgFil or $File::Copy::Recursive::RMTrgDir for file or directory behavior respectively. 0 = off (This is the default) 1 = carp() $! if removal fails 2 = return if removal fails local $File::Copy::Recursive::RMTrgFil = 1; fcopy($orig, $target) or die $!; # if it fails it does warn() and keeps going local $File::Copy::Recursive::RMTrgDir = 2; dircopy($orig, $target) or die $!; # if it fails it does your "or die" This should be unnecessary most of the time but its there if you need it :) =head2 Turning off stat() check By default the files or directories are checked to see if they are the same (IE linked, or two paths (absolute/relative or different relative paths) to the same file) by comparing the file's stat() info. It's a very efficient check that croaks if they are and shouldn't be turned off but if you must for some weird reason just set $File::Copy::Recursive::PFSCheck to a false value. ("PFS" stands for "Physical File System") =head2 Emulating cp -rf dir1/ dir2/ By default dircopy($dir1,$dir2) will put $dir1's contents right into $dir2 whether $dir2 exists or not. You can make dircopy() emulate cp -rf by setting $File::Copy::Recursive::CPRFComp to true. NOTE: This only emulates -f in the sense that it does not prompt. It does not remove the target file or directory if it exists. If you need to do that then use the variables $RMTrgFil and $RMTrgDir described in "Removing existing target file or directory before copying" above. That means that if $dir2 exists it puts the contents into $dir2/$dir1 instead of $dir2 just like cp -rf. If $dir2 does not exist then the contents go into $dir2 like normal (also like cp -rf) So assuming 'foo/file': dircopy('foo', 'bar') or die $!; # if bar does not exist the result is bar/file # if bar does exist the result is bar/file $File::Copy::Recursive::CPRFComp = 1; dircopy('foo', 'bar') or die $!; # if bar does not exist the result is bar/file # if bar does exist the result is bar/foo/file You can also specify a star for cp -rf glob type behavior: dircopy('foo/*', 'bar') or die $!; # if bar does not exist the result is bar/file # if bar does exist the result is bar/file $File::Copy::Recursive::CPRFComp = 1; dircopy('foo/*', 'bar') or die $!; # if bar does not exist the result is bar/file # if bar does exist the result is bar/file NOTE: The '*' is only like cp -rf foo/* and *DOES NOT EXPAND PARTIAL DIRECTORY NAMES LIKE YOUR SHELL DOES* (IE not like cp -rf fo* to copy foo/*) =head2 Allowing Copy Loops If you want to allow: cp -rf . foo/ type behavior set $File::Copy::Recursive::CopyLoop to true. This is false by default so that a check is done to see if the source directory will contain the target directory and croaks to avoid this problem. If you ever find a situation where $CopyLoop = 1 is desirable let me know (IE its a bad bad idea but is there if you want it) (Note: On Windows this was necessary since it uses stat() to detemine samedness and stat() is essencially useless for this on Windows. The test is now simply skipped on Windows but I'd rather have an actual reliable check if anyone in Microsoft land would care to share) =head1 SEE ALSO L<File::Copy> L<File::Spec> =head1 TO DO Add OO interface so you can have different behavior with different objects instead of relying on global variables. This will give better control in environments where behavior based on global variables is not very desireable. I'll add this after the latest verision has been out for a while with no new features or issues found :) =head1 AUTHOR Daniel Muey, L<http://drmuey.com/cpan_contact.pl> =head1 COPYRIGHT AND LICENSE Copyright 2004 by Daniel Muey This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
leighpauls/k2cro4
third_party/cygwin/lib/perl5/vendor_perl/5.10/File/Copy/Recursive.pm
Perl
bsd-3-clause
20,871
/* Part of ClioPatria Author: Jan Wielemaker E-mail: J.Wielemaker@vu.nl WWW: http://cliopatria.swi-prolog.org Copyright (C): 2004-2016, 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 Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA As a special exception, if you link this library with other files, compiled with a Free Software compiler, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ :- module(cp_server, [ cp_server/0, cp_server/1, % +Options cp_welcome/0, cp_after_load/1 % :Goal ]). /** <module> ClioPatria main module This module loads the ClioPatria server as a library, providing the public predicates defined in the header. Before loading this file, the user should set up a the search path =cliopatria=. For example: == :- dynamic user:file_search_path/2. :- multifile user:file_search_path/2. user:file_search_path(cliopatria, '/usr/local/cliopatria'). :- use_module(cliopatria(cliopatria)). == @see http://cliopatria.swi-prolog.org */ :- dynamic user:file_search_path/2. :- multifile user:file_search_path/2. :- ( user:file_search_path(cliopatria, _) -> true ; prolog_load_context(directory, Dir), assert(user:file_search_path(cliopatria, Dir)) ). user:file_search_path(library, cliopatria(lib)). :- load_files(library(version), [silent(true), if(not_loaded)]). :- check_prolog_version(or(60200,60300)). % Demand >= 6.2.x, 6.3.x :- register_git_module('ClioPatria', [ home_url('http://cliopatria.swi-prolog.org/') ]). :- load_files([ parms, skin(cliopatria), % HTML Page layout library(option), library(bundle), library(debug), library(lists), library(settings), library(error), library(broadcast), library(thread_pool), library(apply), library(semweb/rdf_db), library(semweb/rdf_persistency), library(semweb/rdf_litindex), library(http/http_session), library(http/http_server_files), library(http/http_dispatch), library(http/thread_httpd), user(user_db), user(openid), user(preferences), api(sesame), api(journal), % export journal information api(sparql), api(export), api(void), applications(admin), applications(user), applications(browse), applications(yasgui), library(conf_d), user:library(cpack/cpack) ], [ silent(true), if(not_loaded) ]). :- if(exists_source(library(semweb/rdf_ntriples))). :- load_files([ library(semweb/rdf_ntriples) ], [ silent(true), if(not_loaded) ]). :- endif. :- http_handler(web(.), serve_files_in_directory(web), [prefix]). :- dynamic after_load_goal/1. %% cp_server is det. %% cp_server(:Options) is det. % % Start the HTTP server. This predicate preforms the following % steps: % % 1. Load application settings from =|settings.db|= % 2. Load user-data from =|users.db|= % 3. Start the HTTP server % 4. Load the RDF persistent database from =|RDF-store|= % 5. Execute `after load' options registered using % cp_after_load/1. % % Defined options are: % % * port(Port) % Attach to Port instead of the port specified in the % configuration file settings.db. % * workers(+Count) % Number of worker threads to use. Default is the setting % =|http:workers|= % * prefix(+Prefix) % Rebase the server. See also the setting =|http:prefix|=. % * store(+Store) % Directory to use as persistent store. See also the % setting =|cliopatria:persistent_store|=. % * settings(+Settings) % Settings file. Default is =settings.db=. :- meta_predicate cp_server(:). cp_server :- argv(_ProgName, [cpack|Argv]), !, load_conf_d([ 'config-enabled' ], []), catch(cpack_control(Argv), E, ( print_message(error, E), halt(1) )), halt. :- if(current_predicate(http_unix_daemon:http_daemon/0)). cp_server :- http_unix_daemon:http_daemon. :- else. cp_server :- process_argv(Options), catch(cp_server(Options), E, true), ( var(E) -> true ; print_message(error, E), ( E = error(socket_error('Address already in use'), _) -> print_message(error, cliopatria(use_port_option)) ; true ) ). :- endif. % cp_server(M:List):- \+ member(prefix(_),List), !, cp_server(M:[prefix('/swish')|List]),!. cp_server(_Options) :- setting(http:port, DefPort), http_server_property(DefPort, goal(cp_server:http_dispatch)), !, print_message(informational, cliopatria(server_already_running(DefPort))). cp_server(Options) :- meta_options(is_meta, Options, QOptions), load_application(QOptions), option(settings(SettingsFile), QOptions, 'settings.db'), load_settings(SettingsFile), set_prefix(QOptions), attach_account_info, set_session_options, create_log_directory, setting(http:port, DefPort), setting(http:workers, DefWorkers), setting(http:worker_options, Settings), https_options(HTTPSOptions), merge_options(QOptions, Settings, HTTPOptions0), merge_options(HTTPOptions0, HTTPSOptions, HTTPOptions), option(port(Port), QOptions, DefPort), update_public_port(Port, DefPort), option(workers(Workers), QOptions, DefWorkers), http_server(http_dispatch, [ port(Port), workers(Workers) | HTTPOptions ]), option(after_load(AfterLoad), QOptions, true), print_message(informational, cliopatria(server_started(Port))), setup_call_cleanup( http_handler(root(.), busy_loading, [ priority(1000), hide_children(true), id(busy_loading), prefix ]), rdf_attach_store(QOptions, AfterLoad), http_delete_handler(id(busy_loading))). is_meta(after_load). set_prefix(Options) :- option(prefix(Prefix), Options), \+ setting(http:prefix, Prefix), !, set_setting_default(http:prefix, Prefix). set_prefix(_). %% update_public_port(+Port, +DefPort) % % Update http:public_port if port is changed using --port=Port. % Without this hack it is no longer to login after using the port % option. update_public_port(Port, Port) :- !. update_public_port(Port, DefPort) :- setting(http:public_port, DefPort), !, set_setting_default(http:public_port, Port), assertion(setting(http:public_port, Port)). update_public_port(_, _). %% load_application(+Options) % % Load cpack and local configuration. load_application(Options) :- current_prolog_flag(verbose, Verbose), setup_call_cleanup( set_prolog_flag(verbose, silent), load_application2(Options), set_prolog_flag(verbose, Verbose)). load_application2(_Options) :- load_conf_d([ 'config-enabled' ], []), ( exists_source(local) -> ensure_loaded(local) ; true ). %% rdf_attach_store(+Options, :AfterLoad) is det. % % Attach the RDF store using the setting % cliopatria:persistent_store and call the `after-load' goals. % % @see cp_after_load/1 for registering after-load goals. :- meta_predicate rdf_attach_store(+, 0), call_warn(0). rdf_attach_store(Options, AfterLoad) :- ( option(store(Directory), Options) -> true ; setting(cliopatria:persistent_store, Directory) ), setup_indices, ( Directory \== '' -> rdf_attach_db(Directory, Options) ; true ), forall(after_load_goal(Goal), call_warn(Goal)), call_warn(AfterLoad). call_warn(Goal) :- ( catch(Goal, E, true) -> ( var(E) -> true ; print_message(warning, E) ) ; print_message(warning, goal_failed(Goal)) ). %% setup_indices is det. % % Initialize maintenance of the full-text indices. These indices % are created on first call and maintained dynamically as the RDF % store changes. By initializing them before there is any RDF % loaded, they will be built while the data is (re-)loaded, which % avoids long delays on the first query. Note that most of the % work is done in a separate thread. setup_indices :- setting(cliopatria:pre_index_tokens, true), rdf_find_literals(not_a_token, _), fail. setup_indices :- setting(cliopatria:pre_index_stems, true), rdf_find_literals(stem(not_a_stem), _), fail. setup_indices. %% cp_after_load(:Goal) is det. % % Register Goal to be executed after reloading the RDF persistent % DB. Note that already registered goals are not duplicated. % Running a goal after loading the database is commonly used to % ensure presence of relevant schemas or build additional indices. % Note that it is possible to start a thread for time-consuming % tasks (see thread_create/3). :- meta_predicate cp_after_load(0). cp_after_load(Goal) :- ( after_load_goal(Goal) -> true ; assert(after_load_goal(Goal)) ). %% busy_loading(+Request) % % This HTTP handler is pushed to overrule all actions of the % server while the server is restoring its persistent state. It % replies with the 503 (unavailable) response, indicating the % progress of restoring the repository. :- dynamic loading_done/2. busy_loading(_Request) :- rdf_statistics(triples(Triples)), ( loading_done(Nth, Total) -> Extra = [ '; ~D of ~D graphs.'-[Nth, Total] ] ; Extra = [ '.' ] ), HTML = p([ 'This service is currently restoring its ', 'persistent database.', br([]), 'Loaded ~D triples'-[Triples] | Extra ]), throw(http_reply(unavailable(HTML))). %% attach_account_info % % Set the registered user-database from the setting % cliopatria:user_data. attach_account_info :- setting(cliopatria:user_data, File), set_user_database(File). %% set_session_options % % Initialise session timeout from =|http:max_idle_time|=. set_session_options :- setting(http:max_idle_time, Idle), http_set_session_options([timeout(Idle)]). %% create_log_directory % % Create the directory in which the log files reside. create_log_directory :- current_setting(http:logfile), setting(http:logfile, File), File \== '', file_directory_name(File, DirName), DirName \== '.', !, catch(make_directory_path(DirName), E, print_message(warning, E)). create_log_directory. /******************************* * UPDATE SETTINGS * *******************************/ update_workers(New) :- setting(http:port, Port), http_current_worker(Port, _), http_workers(Port, New). :- listen(settings(changed(http:max_idle_time, _, New)), http_set_session_options([timeout(New)])). :- listen(settings(changed(http:workers, _, New)), update_workers(New)). /******************************* * ARGV * *******************************/ %% process_argv(-Options) % % Processes the ClioPatria commandline options. % % @tbd Move most of this to the Prolog library process_argv(Options) :- argv(Program, Argv), ( Argv == ['--help'] -> usage(Program) ; catch(( parse_options(Argv, Options, Rest), maplist(process_argument, Rest) ), E, ( print_message(error, E), fail )) -> true ; usage(Program) ). process_argument(URL) :- ( sub_atom('http://', 0, _, _, URL) ; sub_atom('https://', 0, _, _, URL) ), !, rdf_load(URL). process_argument(File) :- file_name_extension(_Base, Ext, File), process_argument(Ext, File). process_argument(Ext, File) :- user:prolog_file_type(Ext, prolog), !, ensure_loaded(user:File). process_argument(gz, File) :- file_name_extension(Plain, gz, File), file_name_extension(_, RDF, Plain), rdf_extension(RDF), rdf_load(File). process_argument(RDF, File) :- rdf_extension(RDF), rdf_load(File). rdf_extension(rdf). rdf_extension(owl). rdf_extension(ttl). rdf_extension(nt). rdf_extension(ntriples). cmd_option(-, help, -, 'Print command usage'). cmd_option(p, port, positive_integer, 'Port to connect to'). cmd_option(w, workers, positive_integer, 'Number of workers to start'). cmd_option(-, after_load, term, 'Goal to run after loading'). cmd_option(-, prefix, atom, 'Rebase the server to prefix/'). cmd_option(-, store, atom, 'Directory for persistent store'). % dummy to stop list_trivial_fail from warning about long_option/2. cmd_option(-, -, boolean, 'Dummy') :- fail. usage(Program) :- format(user_error, 'Run ClioPatria for interactive usage.~n~n', []), ansi_format([bold], 'Usage: ~w [options] arguments', [Program]), nl, nl, flush_output, forall(cmd_option(Short, Long, Type, Comment), describe_option(Short, Long, Type, Comment)), cpack_usage(Program), describe_argv, ( current_prolog_flag(hwnd, _) % swipl-win.exe console -> ansi_format([bold,hfg(red)], '~nPress \'b\' for break, any other key to exit > ', []), get_single_char(Key), ( Key == 0'b -> nl, nl, break ; true ), halt ; halt(1) ). describe_option(-, Long, -, Comment) :- !, format(user_error, ' --~w~t~40|~w~n', [Long, Comment]). describe_option(-, Long, _, Comment) :- !, format(user_error, ' --~w=~w~t~40|~w~n', [Long, Long, Comment]). describe_option(Short, Long, -, Comment) :- !, format(user_error, ' -~w, --~w~t~40|~w~n', [Short, Long, Comment]). describe_option(Short, Long, _, Comment) :- !, format(user_error, ' -~w ~w, --~w=~w~t~40|~w~n', [Short, Long, Long, Long, Comment]). describe_argv :- current_prolog_flag(argv, Argv), ( Argv == ['--help'] -> true ; ansi_format([fg(red)], 'Program argv: ~q~n', [Argv]) ). cpack_usage(Program) :- nl, ansi_format([bold], 'CPACK commands', []), nl, nl, flush_output, format(user_error, ' ~w cpack install pack ...~n', [Program]), format(user_error, ' ~w cpack upgrade pack ...~n', [Program]). parse_options([], [], []). parse_options([--|Rest], [], Rest) :- !. parse_options([H|T], [Opt|OT], Rest) :- sub_atom(H, 0, _, _, --), !, ( sub_atom(H, B, _, A, =) -> B2 is B - 2, sub_atom(H, 2, B2, _, Name), sub_atom(H, _, A, 0, Value), long_option(Name, Value, Opt) ; sub_atom(H, 2, _, 0, Name), long_option(Name, Opt) ), parse_options(T, OT, Rest). parse_options([H|T], Opts, Rest) :- atom_chars(H, [-|Opts]), !, short_options(Opts, T, Opts, Rest). parse_options(Rest, [], Rest). short_options([], Av, Opts, Rest) :- parse_options(Av, Opts, Rest). short_options([H|T], Av, [Opt|OptT], Rest) :- cmd_option(H, Name, Type, _), ( Type == (-) -> Opt =.. [Name,true], short_options(T, Av, OptT, Rest) ; Av = [Av0|AvT], text_to_value(Type, Av0, Value), Opt =.. [Name,Value], short_options(T, AvT, OptT, Rest) ). long_option(Name, Text, Opt) :- cmd_option(_, Name, Type, _), text_to_value(Type, Text, Value), Opt =.. [Name,Value]. long_option(Name, Opt) :- atom_concat('no-', OptName, Name), cmd_option(_, OptName, boolean, _), !, Opt =.. [Name,false]. long_option(Name, Opt) :- cmd_option(_, Name, boolean, _), Opt =.. [Name,true]. text_to_value(boolean, Text, Value) :- downcase_atom(Text, Lwr), boolean(Lwr, Value). text_to_value(atom, Text, Text). text_to_value(oneof(L), Text, Text) :- memberchk(Text, L). text_to_value(integer, Text, Int) :- atom_number(Text, Int), integer(Int). text_to_value(nonneg, Text, Int) :- atom_number(Text, Int), integer(Int), Int >= 0. text_to_value(positive_integer, Text, Int) :- atom_number(Text, Int), integer(Int), Int > 0. text_to_value(negative_integer, Text, Int) :- atom_number(Text, Int), integer(Int), Int < 0. text_to_value(float, Text, Float) :- atom_number(Text, Number), Float = float(Number). text_to_value(term, Text, Term) :- atom_to_term(Text, Term, _). boolean(true, true). boolean(yes, true). boolean(on, true). boolean(false, false). boolean(no, false). boolean(off, false). %% argv(-ProgramBaseName, -UserArgs) argv(ProgName, Argv) :- current_prolog_flag(os_argv, [_Swipl,ProgName|_]), !, user_argv(Argv). argv(ProgName, Argv) :- current_prolog_flag(os_argv, [ProgName|_]), user_argv(Argv). :- if(current_prolog_flag(os_argv,_)). user_argv(Argv) :- current_prolog_flag(argv, Argv). :- else. user_argv(Av) :- current_prolog_flag(argv, [_Prog|Argv]), ( append(_, [--|Av], Argv) -> true ; current_prolog_flag(windows, true) -> Av = Argv ; Av = [] ). :- endif. /******************************* * CPACK * *******************************/ %% cpack_control(+Commands:list) % % Execute a CPACK configuration instruction. For example: % % ./run.pl cpack install swish cpack_control([install|Packs]) :- !, maplist(cpack_install, Packs). cpack_control([upgrade|Packs]) :- !, ( Packs == [] -> cpack_upgrade ; maplist(cpack_upgrade, Packs) ). cpack_control(Command) :- domain_error(cpack_command, Command). /******************************* * BANNER * *******************************/ %% cp_welcome % % Print welcome banner. cp_welcome :- setting(http:port, Port), print_message(informational, cliopatria(welcome(Port))). /******************************* * POOLS * *******************************/ :- multifile http:create_pool/1. :- setting(cliopatria:max_clients, integer, 50, 'Max number of concurrent requests in ClioPatria pool'). :- if(current_prolog_flag(address_bits, 32)). :- setting(cliopatria:stack_size, integer, 128, 'Stack limit in MB for ClioPatria pool'). :- else. :- setting(cliopatria:stack_size, integer, 1024, 'Stack limit in MB for ClioPatria pool'). :- endif. %% http:create_pool(+Pool) is semidet. % % Create a thread-pool on-demand. http:create_pool(sparql_query) :- debug(http(pool), 'Demand-creating pool ~q', [sparql_query]), setting(sparql:max_clients, Count), setting(sparql:stack_size, MB), Global is MB * 1024, Trail is MB * 1024, thread_pool_create(sparql_query, Count, [ global(Global), trail(Trail) ]). http:create_pool(cliopatria) :- setting(cliopatria:max_clients, Count), setting(cliopatria:stack_size, MB), Global is MB * 1024, Trail is MB * 1024, thread_pool_create(cliopatria, Count, [ global(Global), trail(Trail) ]). /******************************* * HTTPS * *******************************/ %% https_options(-Options) is det. % % Fetch options for running an HTTPS server. HTTP is started if % there is a directory =https= with these files: % % $ =|server-cert.pem|= : % Contains the server certificate. This may be omitted, in % which case the =|server-key.pem|= is also passed using the % key_file(+File) option. % $ =|server-key.pem|= : % Contains the private key for the server. % % =|passwd|= : % Needs to hold the password if the private key is protected % with a password. https_options(Options) :- https_file('server-key.pem', KeyFile), !, ( https_file('server-cert.pem', CertFile) -> true ; CertFile = KeyFile ), Options = [ ssl([ certificate_file(CertFile), key_file(KeyFile) | PasswdOption ]) ], ( https_file(passwd, PasswordFile) -> read_file_to_string(PasswordFile, Content, []), split_string(Content, "", " \n\r", [Passwd]), PasswdOption = [password(Passwd)] ; PasswdOption = [] ). https_options([]). https_file(Base, File) :- absolute_file_name(config_https(Base), File, [ access(read), file_errors(fail) ]). /******************************* * MESSAGES * *******************************/ :- multifile prolog:message//1. prolog:message(cliopatria(server_started(Port))) --> { cp_host(Port, Host), cp_port(Port, PublicPort), http_location_by_id(root, Root) }, [ 'Started ClioPatria server at port ~w'-[Port], nl, 'You may access the server at http://~w:~w~w'-[Host, PublicPort, Root] ]. prolog:message(cliopatria(welcome(DefaultPort))) --> [ nl, 'Use one of the calls below to start the ClioPatria server:', nl, nl, ' ?- cp_server. % start at port ~w'-[DefaultPort], nl, ' ?- cp_server([port(Port)]). % start at Port' ]. prolog:message(cliopatria(use_port_option)) --> [ ' Could not start the HTTP server!', nl, ' Choose a different port using ./run.pl --port=<port> or', nl, ' use the network plugin to change the default port.' ]. prolog:message(cliopatria(server_already_running(Port))) --> { cp_host(Port, Host), cp_port(Port, PublicPort), http_location_by_id(root, Root) }, [ 'CliopPatria server is already running at http://~w:~w~w'- [Host, PublicPort, Root] ]. cp_host(_, Host) :- setting(http:public_host, Host), Host \== '', !. cp_host(Host:_, Host) :- !. cp_host(_,Host) :- gethostname(Host). cp_port(_ServerPort, PublicPort) :- setting(http:public_host, Host), Host \== '', Host \== localhost, setting(http:public_port, PublicPort), !. cp_port(_Host:Port, Port) :- !. cp_port(ServerPort, ServerPort). /******************************* * HOOKS * *******************************/ :- multifile user:message_hook/3. user:message_hook(rdf(restore(_, done(_DB, _T, _Count, Nth, Total))), _Kind, _Lines) :- retractall(loading_done(_,_)), assert(loading_done(Nth, Total)), fail. :- multifile http_unix_daemon:http_server_hook/1. % +Options http_unix_daemon:http_server_hook(Options) :- cp_server(Options).
TeamSPoon/logicmoo_workspace
packs_web/ClioPatria/cliopatria.pl
Perl
mit
21,949
package Parse::Template::Arguments; use strict; use Perl::Module; use Error::Programatic; use Parse::Template::CallbackArgument; sub new { my $classname = ref($_[0]) ? ref(shift) : shift; my $self = bless [], $classname; @_ and $self->parse(shift); $self; } # All '(' must have a closing ')' sub parse ($) { my $self = shift; my $str = shift; ref($str) and throw Error::Programatic; my $parents = []; # pointers to arrays as we nest groups my $ptr = $self; # start at the top (note we do not clear ourselves) my $arg = undef; # the current argument to which characters are appended my $quoted = undef; # character which begins a quoted section my $depth = 0; # nested group depth my $slurp = 0; # slurping is on my $curly = 0; # scope is within curlys by matching '{' with '}' my @chars = split //, $str; while (@chars) { my $chr = shift @chars; if ($chr eq '\\') { # Literal character follows, eat the escape character $chr .= shift @chars; } elsif ($chr eq ')') { # Close the currently open group if ($depth-- == @$parents) { # track closes defined $arg and push @$ptr, $$arg; undef $arg; $ptr = pop @$parents; next; } else { $slurp--; } } elsif ($chr eq '(') { $depth++; # track opens my $group = undef; if (defined $arg && !$curly && !$quoted) { # callback argument $group = Parse::Template::CallbackArgument->new($$arg); undef $arg; } elsif (!defined($arg)) { # begins a segment # open a group, must be the beginning of a segment $group = []; } if ($group) { push @$ptr, $group; push @$parents, $ptr; $ptr = $group; next; } else { $slurp++; } } elsif ($slurp) { # continue to append character } elsif (!$quoted && ($chr eq ' ' || $chr eq ',' || $chr eq "\r" || $chr eq "\n")) { defined $arg and push @$ptr, $$arg; undef $arg; next; } elsif (!$quoted && ($chr eq '=')) { # assignment is the same as a separator, however must not be a logical # operator '==|=~' if ((!defined($arg) || ($$arg ne '!' && $$arg ne '<' && $$arg ne '>' && $$arg ne '=')) && $chars[0] ne '=' && $chars[0] ne '~') { defined $arg and push @$ptr, $$arg; undef $arg; $chars[0] eq '>' and shift @chars; # => is treated as = next; } } elsif (!$quoted && $chr eq '!' && !defined($arg) && $chars[0] ne '=' && $chars[0] ne '~') { # unary not operator push @$ptr, $chr; next; } elsif (!$quoted && $chr eq '{') { $curly++; } elsif (!$quoted && $chr eq '}') { $curly--; } elsif ($chr eq '"' || $chr eq '\'' || $chr eq '`') { # quotes must begin a segment if ($quoted) { undef $quoted if $quoted eq $chr; } else { !defined $arg and $quoted = $chr; } } !defined $arg and $arg = str_ref(); # bareword begins a segment $$arg .= $chr; # append current character } defined $arg and push @$ptr, $$arg; return $self; } sub clear { my $self = shift; @$self = (); } 1;
ryangies/lsn-data-hub
src/lib/Parse/Template/Arguments.pm
Perl
mit
3,205
package CGI::OptimalQuery::InteractiveQuery2; use strict; use warnings; no warnings qw( uninitialized ); use base 'CGI::OptimalQuery::AbstractQuery'; use CGI(); sub escapeHTML { return defined $_[0] ? CGI::escapeHTML($_[0]) : ''; } sub output { my $o = shift; my %opts; if (exists $$o{schema}{options}{__PACKAGE__}) { %opts = %{$$o{schema}{options}{__PACKAGE__}}; } elsif (exists $$o{schema}{options}{'CGI::OptimalQuery::InteractiveQuery'}) { %opts = %{$$o{schema}{options}{'CGI::OptimalQuery::InteractiveQuery'}}; } # evalulate code refs for (qw(httpHeader htmlFooter htmlHeader OQdocTop OQdocBottom OQformTop OQformBottom )) { $opts{$_} = $opts{$_}->($o) if ref($opts{$_}) eq 'CODE'; } # define defaults $opts{OQdocTop} ||= ''; $opts{OQdocBottom} ||= ''; $opts{OQformTop} ||= ''; $opts{OQformBottom} ||= ''; $opts{editButtonLabel}||= 'edit'; $opts{disable_sort} ||= 0; $opts{disable_filter} ||= 0; $opts{disable_select} ||= 0; $opts{mutateRecord} ||= undef; $opts{noEscapeCol} ||= []; $opts{editLink} ||= undef; $opts{htmlExtraHead} ||= ""; if (! exists $opts{usePopups}) { $opts{usePopups}=1; } else { $opts{usePopups}=($opts{usePopups}) ? 1 : 0; } if (! exists $opts{useAjax}) { $opts{useAjax} = $opts{usePopups}; } else { $opts{useAjax}=($opts{useAjax}) ? 1 : 0; } $opts{httpHeader} = $$o{q}->header(-type=>'text/html',-expires=>'now') unless exists $opts{httpHeader}; $opts{htmlFooter} = "</body>\n</html>\n" unless exists $opts{htmlFooter}; my $newBut; if ($opts{NewButton}) { $newBut = (ref($opts{NewButton}) eq 'CODE') ? $opts{NewButton}->($o, \%opts) : $opts{NewButton}; } elsif (ref($opts{buildNewLink}) eq 'CODE') { my $link = $opts{buildNewLink}->($o, \%opts); if ($link ne '') { my $target = uc($link); $target =~ s/\W//g; $newBut = "<button type=button title=new class=OQnewBut data-href='".escapeHTML($link)."'>new</button>"; } } elsif (exists $opts{buildNewLink} && $opts{buildNewLink} eq '') {} elsif ($opts{editLink} ne '') { my $target = uc($opts{editLink}); $target =~ s/\W//g; my $link = $opts{editLink}.(($opts{editLink} =~ /\?/)?'&':'?')."on_update=OQrefresh&act=new"; if ($link ne '') { $newBut = "<button type=button title=new class=OQnewBut data-href='".escapeHTML($link)."' data-target=$target>new</button>"; } } my $ver = "ver=$CGI::OptimalQuery::VERSION"; my $buf; my $dataonly = $$o{q}->param('dataonly'); if ($dataonly) { $buf = $opts{httpHeader}."<!DOCTYPE html>\n<html><body>"; } else { my $script; $script .= "window.OQWindowHeight=$opts{WindowHeight};\n" if $opts{WindowHeight}; $script .= "window.OQWindowWidth=$opts{WindowWidth};\n" if $opts{WindowWidth}; $script .= "window.OQuseAjax=$opts{useAjax};\n"; $script .= "window.OQusePopups=$opts{usePopups};\n"; if (! exists $opts{htmlHeader}) { $opts{htmlHeader} = "<!DOCTYPE html> <html> <head> <title>".escapeHTML($o->get_title)."</title> <link id=OQIQ2CSS rel=stylesheet type=text/css href='$$o{schema}{resourceURI}/InteractiveQuery2.css?$ver'> <meta name=viewport content='width=device-width, initial-scale=1.0, user-scalable=no'> ".$opts{htmlExtraHead}."</head> <body id=OQbody>"; } else { $script .= " if (! document.getElementById('OQIQ2CSS')) { var a = document.createElement('link'); a.setAttribute('rel','stylesheet'); a.setAttribute('type','text/css'); a.setAttribute('id','OQIQ2CSS'); a.setAttribute('href','$$o{schema}{resourceURI}/InteractiveQuery2.css?1'); document.getElementsByTagName('head')[0].appendChild(a); }\n"; } if ($opts{color}) { $script .= " var d = document.createElement('style'); var r = document.createTextNode('.OQhead { background-color: $opts{color}; }'); d.type = 'text/css'; if (d.styleSheet) d.styleSheet.cssText = r.nodeValue; else d.appendChild(r); document.getElementsByTagName('head')[0].appendChild(d);\n"; } $buf = $opts{httpHeader}.$opts{htmlHeader}; $buf .= "<script src=$$o{schema}{resourceURI}/jquery.js?$ver></script><noscript>Javascript is required when viewing this page.</noscript>" unless $opts{jquery_already_sent}; $buf .= " <script src=$$o{schema}{resourceURI}/InteractiveQuery2.js?$ver></script><noscript>Javascript is required when viewing this page.</noscript> <script> (function(){ $script })(); </script><noscript>Javascript is required when viewing this page.</noscript>"; $buf .= " <div class=OQdocTop>$opts{OQdocTop}</div>"; # ouput tools panel my @tools = sort keys %{$$o{schema}{tools}}; if ($#tools > -1) { $buf .= "<div class=OQToolsPanel-pos-div><div class=OQToolsPanel-align-div><div class=OQToolsPanel><ul>"; my $opened_tool_key = $$o{q}->param('tool'); foreach my $key (sort keys %{$$o{schema}{tools}}) { my $tool = $$o{schema}{tools}{$key}; my $openedClass = ''; my $toolContent = ''; if ($opened_tool_key eq $key) { $openedClass = ' opened'; $toolContent = "<div class=OQToolContent>".$$tool{handler}->($o)."</div>"; } $buf .= "<li data-toolkey='$key' class='OQToolExpander $openedClass'><h3>".escapeHTML($$tool{title})."</h3>$toolContent</li>"; } $buf .= "</ul><button class=OQToolsCancelBut type=button>&#10005;</button></div></div></div>"; } } $buf .= " <form class=OQform name=OQform action='".escapeHTML($$o{schema}{URI_standalone}||$$o{schema}{URI})."' method=get> <input type=hidden name=show value='".escapeHTML(join(',',@{$$o{show}}))."'> <input type=hidden name=filter value='".escapeHTML($$o{filter})."'> <input type=hidden name=hiddenFilter value='".escapeHTML($$o{hiddenFilter})."'> <input type=hidden name=queryDescr value='".escapeHTML($$o{queryDescr})."'> <input type=hidden name=sort value='".escapeHTML($$o{'sort'})."'> <input type=hidden name=module value='".escapeHTML($$o{module})."'> <input type=hidden name=on_select value='".escapeHTML($$o{q}->param('on_select'))."'>\n"; if (ref($$o{schema}{state_params}) eq 'ARRAY') { $buf .= "<input type=hidden name='".escapeHTML($_)."' value='" .escapeHTML($$o{q}->param($_))."'>\n" for @{$$o{schema}{state_params}}; } $buf .= "<a name=OQtop></a> <div class=OQformTop>$opts{OQformTop}</div> <div class=OQhead> <div class=OQtitle>".escapeHTML($o->get_title)."</div> <div class=OQsummary>Result(s) (".$o->commify($o->get_lo_rec)." - " .$o->commify($o->get_hi_rec).") of ".$o->commify($o->get_count)."</div> <div class=OQcmds> $newBut <button type=button title='refresh data' class=OQrefreshBut>refresh</button> <button type=button title='tools' class=OQToolsBut>tools</button> <button type=button title='help' class=OQhelpBut>help</button> </div> </div> <table class=OQinfo>"; $buf .= "<tr class=OQQueryDescr><td class=OQlabel>Query:</td><td>".escapeHTML($$o{queryDescr})."</td></tr>" if $$o{queryDescr}; my $filter = $o->get_filter(); if ($filter) { $buf .= "<tr class=OQFilterDescr title='click to edit filter'"; $buf .= " data-nofilter" if $opts{disable_filter}; $buf .= "><td class=OQlabel>Filter:</td><td>".escapeHTML($filter)."</td></tr>"; } my @sort = $o->{sth}->sort_descr; if ($#sort > -1) { $buf .= "<tr class=OQSortDescr><td class=OQlabel>Sort:</td><td>"; my $comma = ''; foreach my $c (@sort) { $buf .= $comma; $comma = ', '; $buf .= "<a title=remove class=OQRemoveSortBut>" unless $opts{disable_sort}; $buf .= escapeHTML($c); $buf .= "</a>" unless $opts{disable_sort}; } $buf .= "</tr>"; } $buf .= "</table> <table class=OQdata> <thead title='click to hide, sort, filter, or add columns'> <tr> <td class=OQdataLHead></td>"; foreach my $colAlias (@{ $o->get_usersel_cols }) { my $colOpts = $$o{schema}{select}{$colAlias}[3]; $buf .= "<td data-col='".escapeHTML($colAlias)."'"; $buf .= " data-noselect" if $$colOpts{disable_select} || $opts{disable_select}; $buf .= " data-nosort" if $$colOpts{disable_sort} || $opts{disable_sort}; $buf .= " data-nofilter" if $$colOpts{disable_filter} || $opts{disable_filter}; $buf .= ">".escapeHTML($o->get_nice_name($colAlias))."</td>"; } $buf .= " <td class=OQdataRHead></td> </tr> </thead> <tbody>\n"; my $recs_in_buffer = 0; my $typeMap = $o->{oq}->get_col_types('select'); my %noEsc = map { $_ => 1 } @{ $opts{noEscapeCol} }; my $odd = 1; while (my $r = $o->{sth}->fetchrow_hashref()) { $opts{mutateRecord}->($r) if ref($opts{mutateRecord}) eq 'CODE'; my @class; if ($odd) { push @class, 'odd'; $odd=0; } else { $odd=1; } $buf .= "<tr"; $buf .= " class='".join(' ', @class)."'" if $#class > -1; $buf .= " data-uid='".escapeHTML($$r{U_ID})."'><td class=OQdataLCol>"; if (ref($opts{OQdataLCol}) eq 'CODE') { $buf .= $opts{OQdataLCol}->($r); } elsif (ref($opts{buildEditLink}) eq 'CODE') { my $link = $opts{buildEditLink}->($o, $r, \%opts); if ($link ne '') { $buf .= "<a href='".escapeHTML($link)."' title='open record' class=OQeditBut>".$opts{editButtonLabel}."</a>"; } } elsif ($opts{editLink} ne '' && $$r{U_ID} ne '') { my $link = $opts{editLink}.(($opts{editLink} =~ /\?/)?'&':'?')."on_update=OQrefresh&act=load&id=$$r{U_ID}"; $buf .= "<a href='".escapeHTML($link)."' title='open record' class=OQeditBut>".$opts{editButtonLabel}."</a>"; } $buf .= "</td>"; foreach my $col (@{ $o->get_usersel_cols }) { my $val; if (exists $noEsc{$col}) { if (ref($$r{$col}) eq 'ARRAY') { $val = join(' ', @{ $$r{$col} }); } else { $val = $$r{$col}; } } elsif (ref($$r{$col}) eq 'ARRAY') { $val = join(', ', map { escapeHTML($_) } @{ $$r{$col} }); } else { $val = escapeHTML($$r{$col}); } my $type = $$typeMap{$col} || 'char'; $buf .= "<td".(($type ne 'char')?" class=$type":"").">$val</td>"; } $buf .= "<td class=OQdataRCol>"; if (ref($opts{OQdataRCol}) eq 'CODE') { $buf .= $opts{OQdataRCol}->($r); } elsif ($o->{q}->param('on_select') ne '') { my $on_select = $o->{q}->param('on_select'); $on_select =~ s/\~.*//; my ($func,@argfields) = split /\,/, $on_select; $argfields[0] = 'U_ID' if $#argfields==-1; my @argvals = map { my $v=$$r{$_}; $v = join(', ', @$v) if ref($v) eq 'ARRAY'; $v =~ s/\~\~\~//g; $v; } @argfields; $buf .= "<button type=button title='select record' class=OQselectBut data-rv='" .escapeHTML(join('~~~',@argvals))."'>select</button>"; } $buf .= "</td></tr>\n"; if (++$recs_in_buffer == 10000) { $$o{output_handler}->($buf); $buf = ''; $recs_in_buffer = 0; } } $o->{sth}->finish(); $buf .= "</tbody></table>\n"; my $numpages = $o->get_num_pages(); $buf .= "<div class=OQPager>\n"; if ($numpages != 1) { $buf .= "<button type=button title='previous page' class=OQPrevBut"; $buf .= " disabled" if $$o{page}==1; $buf .= ">&lt;</button>"; } $buf .= " <select name=rows_page>"; foreach my $p (@{ $$o{schema}{results_per_page_picker_nums} }) { $buf .= "<option value=$p".(($p eq $$o{rows_page})?" selected":"").">view $p results per page"; } $buf .= "</select>"; if ($numpages != 1) { $buf .= " <label>Page <input type=number min=1 max=$numpages step=1 name=page value='" .escapeHTML($$o{page})."'> of $numpages</label> <button type=button title='next page' class=OQNextBut>&gt;</button>" } $buf .= " </div> <div class=OQformBottom>$opts{OQformBottom}</div> <div class=OQBlocker></div> <div class=OQColumnCmdPanel> <button type=button class=OQLeftBut title='move column left'>move left</button> <button type=button class=OQRightBut title='move column right'>move right</button> <button type=button class=OQSortBut title='sort column A-Z'>sort</button> <button type=button class=OQReverseSortBut title='reverse sort column Z-A'>sort reverse</button> <button type=button class=OQFilterBut title='filter column'>filter</button> <button type=button class=OQAddColumnsBut title='add columns'>add columns</button> <button type=button class=OQCloseBut title='hide column'>hide column</button> </div> </form>"; if ($dataonly) { $buf .= "</body></html>"; } else { $buf .= "<div class=OQdocBottom>$opts{OQdocBottom}</div>"; $buf .= $opts{htmlFooter}; } $$o{output_handler}->($buf); return undef; } 1;
gitpan/CGI-OptimalQuery
lib/CGI/OptimalQuery/InteractiveQuery2.pm
Perl
mit
12,640
# # Copyright (C) 2008-2013 Sebastien Helleu <flashcode@flashtux.org> # Copyright (C) 2010-2012 Nils Görs <weechatter@arcor.de> # # 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 3 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 program. If not, see <http://www.gnu.org/licenses/>. # # Set WeeChat and plugins options interactively. # # History: # # 2013-08-03, Sebastien Helleu <flashcode@flashtux.org>: # version 3.2: allow "q" as input in iset buffer to close it # 2013-07-14, Sebastien Helleu <flashcode@flashtux.org>: # version 3.1: remove unneeded calls to iset_refresh() in mouse callback # (faster mouse actions when lot of options are displayed), # fix bug when clicking on a line after the last option displayed # 2013-04-30, arza <arza@arza.us>: # version 3.0: simpler title, fix refresh on unset # 2012-12-16, nils_2 <weechatter@arcor.de>: # version 2.9: fix focus window with iset buffer on mouse click # 2012-08-25, nils_2 <weechatter@arcor.de>: # version 2.8: most important key and mouse bindings for iset buffer added to title-bar (idea The-Compiler) # 2012-07-31, nils_2 <weechatter@arcor.de>: # version 2.7: add combined option and value search (see /help iset) # : add exact value search (see /help iset) # : fix problem with metacharacter in value search # : fix use of uninitialized value for unset option and reset value of option # 2012-07-25, nils_2 <weechatter@arcor.de>: # version 2.6: switch to iset buffer (if existing) when command /iset is called with arguments # 2012-03-17, Sebastien Helleu <flashcode@flashtux.org>: # version 2.5: fix check of sections when creating config file # 2012-03-09, Sebastien Helleu <flashcode@flashtux.org>: # version 2.4: fix reload of config file # 2012-02-02, nils_2 <weechatter@arcor.de>: # version 2.3: fixed: refresh problem with new search results and cursor was outside window. # : add: new option "current_line" in title bar # version 2.2: fixed: refresh error when toggling plugins description # 2011-11-05, nils_2 <weechatter@arcor.de>: # version 2.1: use own config file (iset.conf), fix own help color (used immediately) # 2011-10-16, nils_2 <weechatter@arcor.de>: # version 2.0: add support for left-mouse-button and more sensitive mouse gesture (for integer/color options) # add help text for mouse support # 2011-09-20, Sebastien Helleu <flashcode@flashtux.org>: # version 1.9: add mouse support, fix iset buffer, fix errors on first load under FreeBSD # 2011-07-21, nils_2 <weechatter@arcor.de>: # version 1.8: added: option "show_plugin_description" (alt+p) # fixed: typos in /help iset (lower case for alt+'x' keys) # 2011-05-29, nils_2 <weechatter@arcor.de>: # version 1.7: added: version check for future needs # added: new option (scroll_horiz) and usage of scroll_horiz function (weechat >= 0.3.6 required) # fixed: help_bar did not pop up immediately using key-shortcut # 2011-02-19, nils_2 <weechatter@arcor.de>: # version 1.6: added: display of all possible values in help bar (show_help_extra_info) # fixed: external user options never loaded when starting iset first time # 2011-02-13, Sebastien Helleu <flashcode@flashtux.org>: # version 1.5: use new help format for command arguments # 2011-02-03, nils_2 <weechatter@arcor.de>: # version 1.4: fixed: restore value filter after /upgrade using buffer local variable. # 2011-01-14, nils_2 <weechatter@arcor.de>: # version 1.3: added function to search for values (option value_search_char). # code optimization. # 2010-12-26, Sebastien Helleu <flashcode@flashtux.org>: # version 1.2: improve speed of /upgrade when iset buffer is open, # restore filter used after /upgrade using buffer local variable, # use /iset filter argument if buffer is open. # 2010-11-21, drubin <drubin+weechat@smartcube.co.za>: # version 1.1.1: fix bugs with cursor position # 2010-11-20, nils_2 <weechatter@arcor.de>: # version 1.1: cursor position set to value # 2010-08-03, Sebastien Helleu <flashcode@flashtux.org>: # version 1.0: move misplaced call to infolist_free() # 2010-02-02, rettub <rettub@gmx.net>: # version 0.9: turn all the help stuff off if option 'show_help_bar' is 'off', # new key binding <alt>-<v> to toggle help_bar and help stuff on/off # 2010-01-30, nils_2 <weechatter@arcor.de>: # version 0.8: fix error when option does not exist # 2010-01-24, Sebastien Helleu <flashcode@flashtux.org>: # version 0.7: display iset bar only on iset buffer # 2010-01-22, nils_2 <weechatter@arcor.de> and drubin: # version 0.6: add description in a bar, fix singular/plural bug in title bar, # fix selected line when switching buffer # 2009-06-21, Sebastien Helleu <flashcode@flashtux.org>: # version 0.5: fix bug with iset buffer after /upgrade # 2009-05-02, Sebastien Helleu <flashcode@flashtux.org>: # version 0.4: sync with last API changes # 2009-01-04, Sebastien Helleu <flashcode@flashtux.org>: # version 0.3: open iset buffer when /iset command is executed # 2009-01-04, Sebastien Helleu <flashcode@flashtux.org>: # version 0.2: use null values for options, add colors, fix refresh bugs, # use new keys to reset/unset options, sort options by name, # display number of options in buffer's title # 2008-11-05, Sebastien Helleu <flashcode@flashtux.org>: # version 0.1: first official version # 2008-04-19, Sebastien Helleu <flashcode@flashtux.org>: # script creation use strict; my $PRGNAME = "iset"; my $VERSION = "3.2"; my $DESCR = "Interactive Set for configuration options"; my $AUTHOR = "Sebastien Helleu <flashcode\@flashtux.org>"; my $LICENSE = "GPL3"; my $LANG = "perl"; my $ISET_CONFIG_FILE_NAME = "iset"; my $iset_config_file; my $iset_buffer = ""; my $wee_version_number = 0; my @iset_focus = (); my @options_names = (); my @options_types = (); my @options_values = (); my @options_is_null = (); my $option_max_length = 0; my $current_line = 0; my $filter = "*"; my $description = ""; my $options_name_copy = ""; my $iset_filter_title = ""; # search modes: 0 = index() on value, 1 = grep() on value, 2 = grep() on option, 3 = grep on option & value my $search_mode = 2; my $search_value = ""; my $help_text_keys = "alt + space: toggle, +/-: increase/decrease, enter: change, ir: reset, iu: unset, v: toggle help bar"; my $help_text_mouse = "Mouse: left: select, right: toggle/set, right + drag left/right: increase/decrease"; my %options_iset; my %mouse_keys = ("\@chat(perl.$PRGNAME):button1" => "hsignal:iset_mouse", "\@chat(perl.$PRGNAME):button2*" => "hsignal:iset_mouse", "\@chat(perl.$PRGNAME):wheelup" => "/repeat 5 /iset **up", "\@chat(perl.$PRGNAME):wheeldown" => "/repeat 5 /iset **down"); sub iset_title { if ($iset_buffer ne "") { my $current_line_counter = ""; $current_line_counter = ($current_line + 1) . "/" if (weechat::config_boolean($options_iset{"show_current_line"}) == 1); my $show_filter = ""; if ($search_mode eq 0) { $iset_filter_title = "(value) "; $show_filter = $search_value; if ( substr($show_filter,0,1) eq weechat::config_string($options_iset{"value_search_char"}) ) { $show_filter = substr($show_filter,1,length($show_filter)); } } elsif ($search_mode eq 1) { $iset_filter_title = "(value) "; $show_filter = "*".$search_value."*"; } elsif ($search_mode eq 2) { $iset_filter_title = ""; $filter = "*" if ($filter eq ""); $show_filter = $filter; } elsif ($search_mode eq 3) { $iset_filter_title = "(option) "; $show_filter = $filter .weechat::color("default") ." / (value) " .weechat::color("yellow") ."*".$search_value."*"; } weechat::buffer_set($iset_buffer, "title", $iset_filter_title .weechat::color("yellow") .$show_filter .weechat::color("default")." | " .$current_line_counter .@options_names ." | " .$help_text_keys ." | " .$help_text_mouse); } } sub iset_create_filter { $filter = $_[0]; if ( $search_mode == 3 ) { my @cmd_array = split(/ /,$filter); my $array_count = @cmd_array; $filter = $cmd_array[0]; $filter = $cmd_array[0] . " " . $cmd_array[1] if ( $array_count >2 ); } $filter = "$1.*" if ($filter =~ /f (.*)/); # search file $filter = "*.$1.*" if ($filter =~ /s (.*)/); # search section if ((substr($filter, 0, 1) ne "*") && (substr($filter, -1, 1) ne "*")) { $filter = "*".$filter."*"; } if ($iset_buffer ne "") { weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); } } sub iset_buffer_input { my ($data, $buffer, $string) = ($_[0], $_[1], $_[2]); if ($string eq "q") { weechat::buffer_close($buffer); return weechat::WEECHAT_RC_OK; } $search_value = ""; my @cmd_array = split(/ /,$string); my $array_count = @cmd_array; my $string2 = substr($string, 0, 1); if ($string2 eq weechat::config_string($options_iset{"value_search_char"}) or (defined $cmd_array[0] and $cmd_array[0] eq weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})) ) { $search_mode = 1; $search_value = substr($string, 1); iset_get_values($search_value); if ($iset_buffer ne "") { weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); } } else { $search_mode = 2; if ( $array_count >= 2 and $cmd_array[0] ne "f" or $cmd_array[0] ne "s") { if ( defined $cmd_array[1] and substr($cmd_array[1], 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) or defined $cmd_array[2] and substr($cmd_array[2], 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) ) { $search_mode = 3; $search_value = substr($cmd_array[1], 1); # cut value_search_char $search_value = substr($cmd_array[2], 1) if ( $array_count > 2); # cut value_search_char } } if ( $search_mode == 3) { iset_create_filter($string); iset_get_options($search_value); }else { iset_create_filter($string); iset_get_options(""); } } weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); weechat::buffer_clear($buffer); $current_line = 0; iset_refresh(); return weechat::WEECHAT_RC_OK; } sub iset_buffer_close { $iset_buffer = ""; return weechat::WEECHAT_RC_OK; } sub iset_init { $current_line = 0; $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); if ($iset_buffer eq "") { $iset_buffer = weechat::buffer_new($PRGNAME, "iset_buffer_input", "", "iset_buffer_close", ""); } else { my $new_filter = weechat::buffer_get_string($iset_buffer, "localvar_iset_filter"); $search_mode = weechat::buffer_get_string($iset_buffer, "localvar_iset_search_mode"); $search_value = weechat::buffer_get_string($iset_buffer, "localvar_iset_search_value"); $filter = $new_filter if ($new_filter ne ""); } if ($iset_buffer ne "") { weechat::buffer_set($iset_buffer, "type", "free"); iset_title(); weechat::buffer_set($iset_buffer, "key_bind_ctrl-L", "/iset **refresh"); weechat::buffer_set($iset_buffer, "key_bind_meta2-A", "/iset **up"); weechat::buffer_set($iset_buffer, "key_bind_meta2-B", "/iset **down"); weechat::buffer_set($iset_buffer, "key_bind_meta2-23~", "/iset **left"); weechat::buffer_set($iset_buffer, "key_bind_meta2-24~" , "/iset **right"); weechat::buffer_set($iset_buffer, "key_bind_meta- ", "/iset **toggle"); weechat::buffer_set($iset_buffer, "key_bind_meta-+", "/iset **incr"); weechat::buffer_set($iset_buffer, "key_bind_meta--", "/iset **decr"); weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-r", "/iset **reset"); weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-u", "/iset **unset"); weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-J", "/iset **set"); weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-M", "/iset **set"); weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-1~", "/iset **scroll_top"); weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-4~", "/iset **scroll_bottom"); weechat::buffer_set($iset_buffer, "key_bind_meta-v", "/iset **toggle_help"); weechat::buffer_set($iset_buffer, "key_bind_meta-p", "/iset **toggle_show_plugin_desc"); weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); } } sub iset_get_options { my $var_value = $_[0]; $var_value = "" if (not defined $var_value); $var_value = lc($var_value); $search_value = $var_value; @iset_focus = (); @options_names = (); @options_types = (); @options_values = (); @options_is_null = (); $option_max_length = 0; my %options_internal = (); my $i = 0; my $key; my $iset_struct; my %iset_struct; weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $var_value) if ($search_mode == 3); my $infolist = weechat::infolist_get("option", "", $filter); while (weechat::infolist_next($infolist)) { $key = sprintf("%08d", $i); my $name = weechat::infolist_string($infolist, "full_name"); next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1); my $type = weechat::infolist_string($infolist, "type"); my $value = weechat::infolist_string($infolist, "value"); my $is_null = weechat::infolist_integer($infolist, "value_is_null"); if ($search_mode == 3) { my $value = weechat::infolist_string($infolist, "value"); if ( grep /\Q$var_value/,lc($value) ) { $options_internal{$name}{"type"} = $type; $options_internal{$name}{"value"} = $value; $options_internal{$name}{"is_null"} = $is_null; $option_max_length = length($name) if (length($name) > $option_max_length); $iset_struct{$key} = $options_internal{$name}; push(@iset_focus, $iset_struct{$key}); } } else { $options_internal{$name}{"type"} = $type; $options_internal{$name}{"value"} = $value; $options_internal{$name}{"is_null"} = $is_null; $option_max_length = length($name) if (length($name) > $option_max_length); $iset_struct{$key} = $options_internal{$name}; push(@iset_focus, $iset_struct{$key}); } $i++; } weechat::infolist_free($infolist); foreach my $name (sort keys %options_internal) { push(@options_names, $name); push(@options_types, $options_internal{$name}{"type"}); push(@options_values, $options_internal{$name}{"value"}); push(@options_is_null, $options_internal{$name}{"is_null"}); } } sub iset_get_values { my $var_value = $_[0]; $var_value = lc($var_value); if (substr($var_value,0,1) eq weechat::config_string($options_iset{"value_search_char"}) and $var_value ne weechat::config_string($options_iset{"value_search_char"})) { $var_value = substr($var_value,1,length($var_value)); $search_mode = 0; } iset_search_values($var_value,$search_mode); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $var_value); $search_value = $var_value; } sub iset_search_values { my ($var_value,$search_mode) = ($_[0],$_[1]); @options_names = (); @options_types = (); @options_values = (); @options_is_null = (); $option_max_length = 0; my %options_internal = (); my $i = 0; my $infolist = weechat::infolist_get("option", "", "*"); while (weechat::infolist_next($infolist)) { my $name = weechat::infolist_string($infolist, "full_name"); next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1); my $type = weechat::infolist_string($infolist, "type"); my $is_null = weechat::infolist_integer($infolist, "value_is_null"); my $value = weechat::infolist_string($infolist, "value"); if ($search_mode) { if ( grep /\Q$var_value/,lc($value) ) { $options_internal{$name}{"type"} = $type; $options_internal{$name}{"value"} = $value; $options_internal{$name}{"is_null"} = $is_null; $option_max_length = length($name) if (length($name) > $option_max_length); } } else { # if ($value =~ /\Q$var_value/si) if (lc($value) eq $var_value) { $options_internal{$name}{"type"} = $type; $options_internal{$name}{"value"} = $value; $options_internal{$name}{"is_null"} = $is_null; $option_max_length = length($name) if (length($name) > $option_max_length); } } $i++; } weechat::infolist_free($infolist); foreach my $name (sort keys %options_internal) { push(@options_names, $name); push(@options_types, $options_internal{$name}{"type"}); push(@options_values, $options_internal{$name}{"value"}); push(@options_is_null, $options_internal{$name}{"is_null"}); } } sub iset_refresh_line { if ($iset_buffer ne "") { my $y = $_[0]; if ($y <= $#options_names) { return if (! defined($options_types[$y])); my $format = sprintf("%%s%%-%ds %%s %%-7s %%s %%s%%s%%s", $option_max_length); my $around = ""; $around = "\"" if ((!$options_is_null[$y]) && ($options_types[$y] eq "string")); my $color1 = weechat::color(weechat::config_color($options_iset{"color_option"})); my $color2 = weechat::color(weechat::config_color($options_iset{"color_type"})); my $color3 = ""; if ($options_is_null[$y]) { $color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef"})); } else { $color3 = weechat::color(weechat::config_color($options_iset{"color_value"})); } if ($y == $current_line) { $color1 = weechat::color(weechat::config_color($options_iset{"color_option_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); $color2 = weechat::color(weechat::config_color($options_iset{"color_type_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); if ($options_is_null[$y]) { $color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); } else { $color3 = weechat::color(weechat::config_color($options_iset{"color_value_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); } } my $value = $options_values[$y]; $value = "(undef)" if ($options_is_null[$y]); my $strline = sprintf($format, $color1, $options_names[$y], $color2, $options_types[$y], $color3, $around, $value, $around); weechat::print_y($iset_buffer, $y, $strline); } } } sub iset_refresh { iset_title(); if (($iset_buffer ne "") && ($#options_names >= 0)) { foreach my $y (0 .. $#options_names) { iset_refresh_line($y); } } weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); } sub iset_full_refresh { $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); if ($iset_buffer ne "") { weechat::buffer_clear($iset_buffer) unless defined $_[0]; # iset_full_refresh(1) does a full refresh without clearing buffer # search for "*" in $filter. if ($filter =~ m/\*/ and $search_mode == 2) { iset_get_options(""); } else { if ($search_mode == 0) { $search_value = "=" . $search_value; iset_get_values($search_value); } elsif ($search_mode == 1) { iset_get_values($search_value); } elsif ($search_mode == 3) { iset_create_filter($filter); iset_get_options($search_value); } } if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) { iset_set_current_line($current_line); }else { $current_line = $#options_names if ($current_line > $#options_names); } iset_refresh(); weechat::command($iset_buffer, "/window refresh"); } } sub iset_set_current_line { my $new_current_line = $_[0]; if ($new_current_line >= 0) { my $old_current_line = $current_line; $current_line = $new_current_line; $current_line = $#options_names if ($current_line > $#options_names); if ($old_current_line != $current_line) { iset_refresh_line($old_current_line); iset_refresh_line($current_line); weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); } } } sub iset_signal_window_scrolled_cb { my ($data, $signal, $signal_data) = ($_[0], $_[1], $_[2]); if ($iset_buffer ne "") { my $infolist = weechat::infolist_get("window", $signal_data, ""); if (weechat::infolist_next($infolist)) { if (weechat::infolist_pointer($infolist, "buffer") eq $iset_buffer) { my $old_current_line = $current_line; my $new_current_line = $current_line; my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); my $chat_height = weechat::infolist_integer($infolist, "chat_height"); $new_current_line += $chat_height if ($new_current_line < $start_line_y); $new_current_line -= $chat_height if ($new_current_line >= $start_line_y + $chat_height); $new_current_line = $start_line_y if ($new_current_line < $start_line_y); $new_current_line = $start_line_y + $chat_height - 1 if ($new_current_line >= $start_line_y + $chat_height); iset_set_current_line($new_current_line); } } weechat::infolist_free($infolist); } return weechat::WEECHAT_RC_OK; } sub iset_get_window_number { if ($iset_buffer ne "") { my $window = weechat::window_search_with_buffer($iset_buffer); return "-window ".weechat::window_get_integer ($window, "number")." " if ($window ne ""); } return ""; } sub iset_check_line_outside_window { if ($iset_buffer ne "") { undef my $infolist; if ($wee_version_number >= 0x00030500) { my $window = weechat::window_search_with_buffer($iset_buffer); $infolist = weechat::infolist_get("window", $window, "") if $window; } else { $infolist = weechat::infolist_get("window", "", "current"); } if ($infolist) { if (weechat::infolist_next($infolist)) { my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); my $chat_height = weechat::infolist_integer($infolist, "chat_height"); my $window_number = ""; if ($wee_version_number >= 0x00030500) { $window_number = "-window ".weechat::infolist_integer($infolist, "number")." "; } if ($start_line_y > $current_line) { weechat::command($iset_buffer, "/window scroll ".$window_number."-".($start_line_y - $current_line)); } else { if ($start_line_y <= $current_line - $chat_height) { weechat::command($iset_buffer, "/window scroll ".$window_number."+".($current_line - $start_line_y - $chat_height + 1)); } } } weechat::infolist_free($infolist); } } } sub iset_get_option_name_index { my $option_name = $_[0]; my $index = 0; while ($index <= $#options_names) { return -1 if ($options_names[$index] gt $option_name); return $index if ($options_names[$index] eq $option_name); $index++; } return -1; } sub iset_config_cb { my ($data, $option_name, $value) = ($_[0], $_[1], $_[2]); if ($iset_buffer ne "") { return weechat::WEECHAT_RC_OK if (weechat::info_get("weechat_upgrading", "") eq "1"); my $index = iset_get_option_name_index($option_name); if ($index >= 0) { # refresh info about changed option my $infolist = weechat::infolist_get("option", "", $option_name); if ($infolist) { weechat::infolist_next($infolist); if (weechat::infolist_fields($infolist)) { $options_types[$index] = weechat::infolist_string($infolist, "type"); $options_values[$index] = weechat::infolist_string($infolist, "value"); $options_is_null[$index] = weechat::infolist_integer($infolist, "value_is_null"); iset_refresh_line($index); iset_title() if ($option_name eq "iset.look.show_current_line"); } else { iset_full_refresh(1); # if not found, refresh fully without clearing buffer weechat::print_y($iset_buffer, $#options_names + 1, ""); } weechat::infolist_free($infolist); } } else { iset_full_refresh() if ($option_name ne "weechat.bar.isetbar.hidden"); } } return weechat::WEECHAT_RC_OK; } sub iset_set_option { my ($option, $value) = ($_[0],$_[1]); if (defined $option and defined $value) { $option = weechat::config_get($option); weechat::config_option_set($option, $value, 1) if ($option ne ""); } } sub iset_reset_option { my $option = $_[0]; if (defined $option) { $option = weechat::config_get($option); weechat::config_option_reset($option, 1) if ($option ne ""); } } sub iset_unset_option { my $option = $_[0]; if (defined $option) { $option = weechat::config_get($option); weechat::config_option_unset($option) if ($option ne ""); } } sub iset_cmd_cb { my ($data, $buffer, $args) = ($_[0], $_[1], $_[2]); my $filter_set = 0; # $search_value = ""; if (($args ne "") && (substr($args, 0, 2) ne "**")) { my @cmd_array = split(/ /,$args); my $array_count = @cmd_array; if (substr($args, 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) or (defined $cmd_array[0] and $cmd_array[0] eq weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})) ) { $search_mode = 1; my $search_value = substr($args, 1); # cut value_search_char if ($iset_buffer ne "") { weechat::buffer_clear($iset_buffer); weechat::command($iset_buffer, "/window refresh"); } weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); iset_init(); iset_get_values($search_value); iset_refresh(); weechat::buffer_set($iset_buffer, "display", "1"); # $filter = $var_value; return weechat::WEECHAT_RC_OK; } else { # f/s option =value # option =value $search_mode = 2; if ( $array_count >= 2 and $cmd_array[0] ne "f" or $cmd_array[0] ne "s") { if ( defined $cmd_array[1] and substr($cmd_array[1], 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) or defined $cmd_array[2] and substr($cmd_array[2], 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) ) { $search_mode = 3; $search_value = substr($cmd_array[1], 1); # cut value_search_char $search_value = substr($cmd_array[2], 1) if ( $array_count > 2); # cut value_search_char } } iset_create_filter($args); $filter_set = 1; my $ptrbuf = weechat::buffer_search($LANG, $PRGNAME); if ($ptrbuf eq "") { iset_init(); iset_get_options($search_value); iset_full_refresh(); weechat::buffer_set(weechat::buffer_search($LANG, $PRGNAME), "display", "1"); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); return weechat::WEECHAT_RC_OK; } else { iset_get_options($search_value); iset_full_refresh(); weechat::buffer_set($ptrbuf, "display", "1"); } } weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); } if ($iset_buffer eq "") { iset_init(); iset_get_options(""); iset_refresh(); } else { # iset_get_options($search_value); iset_full_refresh() if ($filter_set); } if ($args eq "") { weechat::buffer_set($iset_buffer, "display", "1"); } else { if ($args eq "**refresh") { iset_full_refresh(); } if ($args eq "**up") { if ($current_line > 0) { $current_line--; iset_refresh_line($current_line + 1); iset_refresh_line($current_line); iset_check_line_outside_window(); } } if ($args eq "**down") { if ($current_line < $#options_names) { $current_line++; iset_refresh_line($current_line - 1); iset_refresh_line($current_line); iset_check_line_outside_window(); } } if ($args eq "**left" && $wee_version_number >= 0x00030600) { weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number()."-".weechat::config_integer($options_iset{"scroll_horiz"})."%"); } if ($args eq "**right" && $wee_version_number >= 0x00030600) { weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number().weechat::config_integer($options_iset{"scroll_horiz"})."%"); } if ($args eq "**scroll_top") { my $old_current_line = $current_line; $current_line = 0; iset_refresh_line ($old_current_line); iset_refresh_line ($current_line); iset_title(); weechat::command($iset_buffer, "/window scroll_top ".iset_get_window_number()); } if ($args eq "**scroll_bottom") { my $old_current_line = $current_line; $current_line = $#options_names; iset_refresh_line ($old_current_line); iset_refresh_line ($current_line); iset_title(); weechat::command($iset_buffer, "/window scroll_bottom ".iset_get_window_number()); } if ($args eq "**toggle") { if ($options_types[$current_line] eq "boolean") { iset_set_option($options_names[$current_line], "toggle"); } } if ($args eq "**incr") { if (($options_types[$current_line] eq "integer") || ($options_types[$current_line] eq "color")) { iset_set_option($options_names[$current_line], "++1"); } } if ($args eq "**decr") { if (($options_types[$current_line] eq "integer") || ($options_types[$current_line] eq "color")) { iset_set_option($options_names[$current_line], "--1"); } } if ($args eq "**reset") { iset_reset_option($options_names[$current_line]); } if ($args eq "**unset") { iset_unset_option($options_names[$current_line]); } if ($args eq "**toggle_help") { if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) { weechat::config_option_set($options_iset{"show_help_bar"},0,1); iset_show_bar(0); } else { weechat::config_option_set($options_iset{"show_help_bar"},1,1); iset_show_bar(1); } } if ($args eq "**toggle_show_plugin_desc") { if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) { weechat::config_option_set($options_iset{"show_plugin_description"},0,1); iset_full_refresh(); iset_check_line_outside_window(); iset_title(); } else { weechat::config_option_set($options_iset{"show_plugin_description"},1,1); iset_full_refresh(); iset_check_line_outside_window(); iset_title(); } } if ($args eq "**set") { my $quote = ""; my $value = $options_values[$current_line]; if ($options_is_null[$current_line]) { $value = "null"; } else { $quote = "\"" if ($options_types[$current_line] eq "string"); } weechat::buffer_set($iset_buffer, "input", "/set ".$options_names[$current_line]." ".$quote.$value.$quote); weechat::command($iset_buffer, "/input move_beginning_of_line"); weechat::command($iset_buffer, "/input move_next_word"); weechat::command($iset_buffer, "/input move_next_word"); weechat::command($iset_buffer, "/input move_next_char"); weechat::command($iset_buffer, "/input move_next_char") if ($quote ne ""); } } weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); return weechat::WEECHAT_RC_OK; } sub iset_get_help { my ($redraw) = ($_[0]); return '' if (weechat::config_boolean($options_iset{"show_help_bar"}) == 0); if (not defined $options_names[$current_line]) { return "No option selected. Set a new filter using command line (use '*' to see all options)"; } if ($options_name_copy eq $options_names[$current_line] and not defined $redraw) { return $description; } $options_name_copy = $options_names[$current_line]; my $optionlist =""; $optionlist = weechat::infolist_get("option", "", $options_names[$current_line]); weechat::infolist_next($optionlist); my $full_name = weechat::infolist_string($optionlist,"full_name"); my $option_desc = ""; my $option_default_value = ""; my $option_range = ""; my $possible_values = ""; my $re = qq(\Q$full_name); if (grep (/^$re$/,$options_names[$current_line])) { $option_desc = weechat::infolist_string($optionlist, "description_nls"); $option_desc = weechat::infolist_string($optionlist, "description") if ($option_desc eq ""); $option_desc = "No help found" if ($option_desc eq ""); $option_default_value = weechat::infolist_string($optionlist, "default_value"); $possible_values = weechat::infolist_string($optionlist, "string_values") if (weechat::infolist_string($optionlist, "string_values") ne ""); if ((weechat::infolist_string($optionlist, "type") eq "integer") && ($possible_values eq "")) { $option_range = weechat::infolist_integer($optionlist, "min") ." .. ".weechat::infolist_integer($optionlist, "max"); } } weechat::infolist_free($optionlist); iset_title(); $description = weechat::color(weechat::config_color($options_iset{"color_help_option_name"})).$options_names[$current_line] .weechat::color("bar_fg").": " .weechat::color(weechat::config_color($options_iset{"color_help_text"})).$option_desc; # show additional infos like default value and possible values if (weechat::config_boolean($options_iset{"show_help_extra_info"}) == 1) { $description .= weechat::color("bar_delim")." [" .weechat::color("bar_fg")."default: " .weechat::color("bar_delim")."\"" .weechat::color(weechat::config_color($options_iset{"color_help_default_value"})).$option_default_value .weechat::color("bar_delim")."\""; if ($option_range ne "") { $description .= weechat::color("bar_fg").", values: ".$option_range; } if ($possible_values ne "") { $possible_values =~ s/\|/", "/g; # replace '|' to '", "' $description .= weechat::color("bar_fg").", values: ". "\"" . $possible_values . "\""; } $description .= weechat::color("bar_delim")."]"; } return $description; } sub iset_check_condition_isetbar_cb { my ($data, $modifier, $modifier_data, $string) = ($_[0], $_[1], $_[2], $_[3]); my $buffer = weechat::window_get_pointer($modifier_data, "buffer"); if ($buffer ne "") { if ((weechat::buffer_get_string($buffer, "plugin") eq $LANG) && (weechat::buffer_get_string($buffer, "name") eq $PRGNAME)) { return "1"; } } return "0"; } sub iset_show_bar { my $show = $_[0]; my $barhidden = weechat::config_get("weechat.bar.isetbar.hidden"); if ($barhidden) { if ($show) { if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) { if (weechat::config_boolean($barhidden)) { weechat::config_option_set($barhidden, 0, 1); } } } else { if (!weechat::config_boolean($barhidden)) { weechat::config_option_set($barhidden, 1, 1); } } } } sub iset_signal_buffer_switch_cb { my $buffer_pointer = $_[2]; my $show_bar = 0; $show_bar = 1 if (weechat::buffer_get_integer($iset_buffer, "num_displayed") > 0); iset_show_bar($show_bar); iset_check_line_outside_window() if ($buffer_pointer eq $iset_buffer); return weechat::WEECHAT_RC_OK; } sub iset_item_cb { return iset_get_help(); } sub iset_upgrade_ended { iset_full_refresh(); } sub iset_end { # when script is unloaded, we hide bar iset_show_bar(0); } # -------------------------------[ mouse support ]------------------------------------- sub hook_focus_iset_cb { my %info = %{$_[1]}; my $bar_item_line = int($info{"_bar_item_line"}); undef my $hash; if (($info{"_buffer_name"} eq $PRGNAME) && $info{"_buffer_plugin"} eq $LANG && ($bar_item_line >= 0) && ($bar_item_line <= $#iset_focus)) { $hash = $iset_focus[$bar_item_line]; } else { $hash = {}; my $hash_focus = $iset_focus[0]; foreach my $key (keys %$hash_focus) { $hash->{$key} = "?"; } } return $hash; } # _chat_line_y contains selected line sub iset_hsignal_mouse_cb { my ($data, $signal, %hash) = ($_[0], $_[1], %{$_[2]}); if ($hash{"_buffer_name"} eq $PRGNAME && ($hash{"_buffer_plugin"} eq $LANG)) { if ($hash{"_key"} eq "button1") { iset_set_current_line($hash{"_chat_line_y"}); } elsif ($hash{"_key"} eq "button2") { if ($options_types[$hash{"_chat_line_y"}] eq "boolean") { iset_set_option($options_names[$hash{"_chat_line_y"}], "toggle"); iset_set_current_line($hash{"_chat_line_y"}); } elsif ($options_types[$hash{"_chat_line_y"}] eq "string") { iset_set_current_line($hash{"_chat_line_y"}); weechat::command("", "/$PRGNAME **set"); } } elsif ($hash{"_key"} eq "button2-gesture-left" or $hash{"_key"} eq "button2-gesture-left-long") { if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) { iset_set_current_line($hash{"_chat_line_y"}); my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); weechat::command("", "/repeat $distance /$PRGNAME **decr"); } } elsif ($hash{"_key"} eq "button2-gesture-right" or $hash{"_key"} eq "button2-gesture-right-long") { if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) { iset_set_current_line($hash{"_chat_line_y"}); my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); weechat::command("", "/repeat $distance /$PRGNAME **incr"); } } } window_switch(); } sub window_switch { my $current_window = weechat::current_window(); my $dest_window = weechat::window_search_with_buffer(weechat::buffer_search("perl","iset")); return 0 if ($dest_window eq "" or $current_window eq $dest_window); my $infolist = weechat::infolist_get("window", $dest_window, ""); weechat::infolist_next($infolist); my $number = weechat::infolist_integer($infolist, "number"); weechat::infolist_free($infolist); weechat::command("","/window " . $number); } sub distance { my ($x1,$x2) = ($_[0], $_[1]); my $distance; $distance = $x1 - $x2; $distance = abs($distance); if ($distance > 0) { use integer; $distance = $distance / 3; $distance = 1 if ($distance == 0); } elsif ($distance == 0) { $distance = 1; } return $distance; } # -----------------------------------[ config ]--------------------------------------- sub iset_config_init { $iset_config_file = weechat::config_new($ISET_CONFIG_FILE_NAME,"iset_config_reload_cb",""); return if ($iset_config_file eq ""); # section "color" my $section_color = weechat::config_new_section($iset_config_file,"color", 0, 0, "", "", "", "", "", "", "", "", "", ""); if ($section_color eq "") { weechat::config_free($iset_config_file); return; } $options_iset{"color_option"} = weechat::config_new_option( $iset_config_file, $section_color, "option", "color", "Color for option name in iset buffer", "", 0, 0, "default", "default", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_option_selected"} = weechat::config_new_option( $iset_config_file, $section_color, "option_selected", "color", "Color for selected option name in iset buffer", "", 0, 0, "white", "white", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_type"} = weechat::config_new_option( $iset_config_file, $section_color, "type", "color", "Color for option type (integer, boolean, string)", "", 0, 0, "brown", "brown", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_type_selected"} = weechat::config_new_option( $iset_config_file, $section_color, "type_selected", "color", "Color for selected option type (integer, boolean, string)", "", 0, 0, "yellow", "yellow", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_value"} = weechat::config_new_option( $iset_config_file, $section_color, "value", "color", "Color for option value", "", 0, 0, "cyan", "cyan", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_value_selected"} = weechat::config_new_option( $iset_config_file, $section_color, "value_selected", "color", "Color for selected option value", "", 0, 0, "lightcyan", "lightcyan", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_value_undef"} = weechat::config_new_option( $iset_config_file, $section_color, "value_undef", "color", "Color for option value undef", "", 0, 0, "green", "green", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_value_undef_selected"} = weechat::config_new_option( $iset_config_file, $section_color, "value_undef_selected", "color", "Color for selected option value undef", "", 0, 0, "lightgreen", "lightgreen", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_bg_selected"} = weechat::config_new_option( $iset_config_file, $section_color, "bg_selected", "color", "Background color for current selected option", "", 0, 0, "red", "red", 0, "", "", "full_refresh_cb", "", "", ""); $options_iset{"color_help_option_name"} = weechat::config_new_option( $iset_config_file, $section_color, "help_option_name", "color", "Color for option name in help-bar", "", 0, 0, "white", "white", 0, "", "", "bar_refresh", "", "", ""); $options_iset{"color_help_text"} = weechat::config_new_option( $iset_config_file, $section_color, "help_text", "color", "Color for option description in help-bar", "", 0, 0, "default", "default", 0, "", "", "bar_refresh", "", "", ""); $options_iset{"color_help_default_value"} = weechat::config_new_option( $iset_config_file, $section_color, "help_default_value", "color", "Color for default option value in help-bar", "", 0, 0, "green", "green", 0, "", "", "bar_refresh", "", "", ""); # section "help" my $section_help = weechat::config_new_section($iset_config_file,"help", 0, 0, "", "", "", "", "", "", "", "", "", ""); if ($section_help eq "") { weechat::config_free($iset_config_file); return; } $options_iset{"show_help_bar"} = weechat::config_new_option( $iset_config_file, $section_help, "show_help_bar", "boolean", "Show help bar", "", 0, 0, "on", "on", 0, "", "", "toggle_help_cb", "", "", ""); $options_iset{"show_help_extra_info"} = weechat::config_new_option( $iset_config_file, $section_help, "show_help_extra_info", "boolean", "Show additional information in help bar (default value, max./min. value) ", "", 0, 0, "on", "on", 0, "", "", "", "", "", ""); $options_iset{"show_plugin_description"} = weechat::config_new_option( $iset_config_file, $section_help, "show_plugin_description", "boolean", "Show plugin description in iset buffer", "", 0, 0, "off", "off", 0, "", "", "full_refresh_cb", "", "", ""); # section "look" my $section_look = weechat::config_new_section($iset_config_file, "look", 0, 0, "", "", "", "", "", "", "", "", "", ""); if ($section_look eq "") { weechat::config_free($iset_config_file); return; } $options_iset{"value_search_char"} = weechat::config_new_option( $iset_config_file, $section_look, "value_search_char", "string", "Trigger char to tell iset to search for value instead of option (for example: =red)", "", 0, 0, "=", "=", 0, "", "", "", "", "", ""); $options_iset{"scroll_horiz"} = weechat::config_new_option( $iset_config_file, $section_look, "scroll_horiz", "integer", "scroll content of iset buffer n%", "", 1, 100, "10", "10", 0, "", "", "", "", "", ""); $options_iset{"show_current_line"} = weechat::config_new_option( $iset_config_file, $section_look, "show_current_line", "boolean", "show current line in title bar.", "", 0, 0, "on", "on", 0, "", "", "", "", "", ""); } sub iset_config_reload_cb { my ($data,$config_file) = ($_[0], $_[1]); return weechat::config_reload($config_file) } sub iset_config_read { return weechat::config_read($iset_config_file) if ($iset_config_file ne ""); } sub iset_config_write { return weechat::config_write($iset_config_file) if ($iset_config_file ne ""); } sub full_refresh_cb { iset_full_refresh(); return weechat::WEECHAT_RC_OK; } sub bar_refresh { iset_get_help(1); weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); return weechat::WEECHAT_RC_OK; } sub toggle_help_cb { my $value = weechat::config_boolean($options_iset{"show_help_bar"}); iset_show_bar($value); return weechat::WEECHAT_RC_OK; } # -----------------------------------[ main ]----------------------------------------- weechat::register($PRGNAME, $AUTHOR, $VERSION, $LICENSE, $DESCR, "iset_end", ""); $wee_version_number = weechat::info_get("version_number", "") || 0; iset_config_init(); iset_config_read(); weechat::hook_command($PRGNAME, "Interactive set", "f <file> || s <section> || [=][=]<text>", "f file : show options for a file\n". "s section: show options for a section\n". "text : show options with 'text' in name\n". weechat::config_string($options_iset{"value_search_char"})."text : show options with 'text' in value\n". weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})."text : show options with exact 'text' in value\n\n". "Keys for iset buffer:\n". "f11,f12 : move iset content left/right\n". "up,down : move one option up/down\n". "pgup,pdwn : move one page up/down\n". "home,end : move to first/last option\n". "ctrl+'L' : refresh options and screen\n". "alt+space : toggle boolean on/off\n". "alt+'+' : increase value (for integer or color)\n". "alt+'-' : decrease value (for integer or color)\n". "alt+'i',alt+'r': reset value of option\n". "alt+'i',alt+'u': unset option\n". "alt+enter : set new value for option (edit it with command line)\n". "text,enter : set a new filter using command line (use '*' to see all options)\n". "alt+'v' : toggle help bar on/off\n". "alt+'p' : toggle option \"show_plugin_description\" on/off\n". "\n". "Mouse actions:\n". "wheel up/down : move cursor up/down\n". "left button : select an option from list\n". "right button : toggle boolean (on/off) or set a new value for option (edit it with command line)\n". "right button + drag left/right: increase/decrease value (for integer or color)\n". "\n". "Examples:\n". " show options for file 'weechat'\n". " /iset f weechat\n". " show options for file 'irc'\n". " /iset f irc\n". " show options for section 'look'\n". " /iset s look\n". " show all options with text 'nicklist' in name\n". " /iset nicklist\n". " show all values which contain 'red'. ('" . weechat::config_string($options_iset{"value_search_char"}) . "' is a trigger char).\n". " /iset ". weechat::config_string($options_iset{"value_search_char"}) ."red\n". " show all values which hit 'off'. ('" . weechat::config_string($options_iset{"value_search_char"}) . weechat::config_string($options_iset{"value_search_char"}) . "' is a trigger char).\n". " /iset ". weechat::config_string($options_iset{"value_search_char"}) . weechat::config_string($options_iset{"value_search_char"}) ."off\n". " show options for file 'weechat' which contains value 'off'\n". " /iset f weechat ".weechat::config_string($options_iset{"value_search_char"})."off\n". "", "", "iset_cmd_cb", ""); weechat::hook_signal("upgrade_ended", "iset_upgrade_ended", ""); weechat::hook_signal("window_scrolled", "iset_signal_window_scrolled_cb", ""); weechat::hook_signal("buffer_switch", "iset_signal_buffer_switch_cb",""); weechat::bar_item_new("isetbar_help", "iset_item_cb", ""); weechat::bar_new("isetbar", "on", "0", "window", "", "top", "horizontal", "vertical", "3", "3", "default", "cyan", "default", "1", "isetbar_help"); weechat::hook_modifier("bar_condition_isetbar", "iset_check_condition_isetbar_cb", ""); weechat::hook_config("*", "iset_config_cb", ""); $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); iset_init() if ($iset_buffer ne ""); if ($wee_version_number >= 0x00030600) { weechat::hook_focus("chat", "hook_focus_iset_cb", ""); weechat::hook_hsignal($PRGNAME."_mouse", "iset_hsignal_mouse_cb", ""); weechat::key_bind("mouse", \%mouse_keys); }
LunaticFairy/configs
.weechat/perl/iset.pl
Perl
mit
56,829
#!/usr/bin/perl # # # # # Kim Brugger (17 May 2010), contact: kim.brugger@easih.ac.uk use strict; use warnings; use Data::Dumper; use Getopt::Std; my %opts; getopts('S:f:F', \%opts); my $sleep_time = shift || 10; my $fail_rate = $opts{f} || 5; srand; $sleep_time = int(rand( $sleep_time )); $sleep_time = $opts{'S'} if ($opts{'S'}); #print "Starting sleep for $sleep_time seconds\n"; sleep($sleep_time); if ($opts{'F'} || $fail_rate > int(rand(100))) { print "------- Failed -----------\n"; exit 1; } #print "Done sleeping.\n";
brugger/ctru-pipeline
dev/dummies/local.pl
Perl
mit
548
#!/usr/bin/perl my $version = "v1.1"; use strict; use warnings; # warn user (from perspective of caller) use Carp; # use nice English (or awk) names for ugly punctuation variables use English qw(-no_match_vars); # folder Mendeley exports .bib files to assumed to be "%HOME%/bib_files": #use File::HomeDir; use File::Spec; my ($tex_file, $mendeley_bib_base) = @ARGV; #to compare last modified dates use File::stat; # find used .bib file names open my $TEXFILE, $tex_file or croak "Cannot open $tex_file: $OS_ERROR"; my @bib_files; while (<$TEXFILE>) { if (/^[^%]*\\addbibresource\{([^\{\}]*)\}/) { push @bib_files, $1; } } close $TEXFILE or croak "Cannot close $tex_file: $OS_ERROR"; foreach my $out_file (@bib_files) { my $in_file = File::Spec->catfile($mendeley_bib_base, $out_file); # if Mendeley's .bib file is older than the previously patched one (the one in this folder), skip it my $sin_file = stat($in_file); my $sout_file = stat($out_file); if ($sin_file && $sout_file && $sin_file->mtime <= $sout_file->mtime) { print "skipping $out_file (already up to date)"; next; } print "importing and patching $in_file"; open my $INFILE, $in_file or warn "skipping $out_file (Could not open $in_file: $OS_ERROR)" and next; open my $OUTFILE, '>', $out_file or croak "Cannot open $out_file: $OS_ERROR"; print { $OUTFILE } "Do not edit! File automatically generated by patching $in_file using \"patch.bib.pl $version\". \n\n" and print { $OUTFILE } '@preamble{ " \providecommand{\noop}[1]{} " } % a do-nothing command that serves a purpose' and print { $OUTFILE } "\n\n" or croak "Cannot write to $out_file: $OS_ERROR"; while(<$INFILE>) { # remove double brackets around titles and add brackes around words that contain non primal upper case letters like FBI or iPhone or numbers like Cas9 and around single uppercase latters other than "A": if (/title ?= ?\{.*\},/) { s/^title ?= ?\{\{([^\n]*)\}\},$/title = \{$1\},/; s/((?:(?=\w+[A-Z]|[A-z]\w*[0-9])\w+|[B-Z](?=\W))|(?:".*"))/\{$1\}/g; } # Allow encoding "in press" articles in Medeley by using years 3000 to 3999 (can be used to order items): s/^year ?= ?\{(3[0-9]{3})\}/year = \{\\noop\{$1\}in press\}/; print { $OUTFILE } $_ or warn "Cannot write to $out_file: $OS_ERROR" and next; } close $INFILE or croak "Cannot close $in_file: $OS_ERROR"; close $OUTFILE or croak "Cannot close $out_file: $OS_ERROR"; }
jan-glx/patch.mendeley.bib.pl
patch.mendeley.bib.pl
Perl
mit
2,496
package RSP::Transaction::Mojo; use strict; use warnings; use Encode; use base 'RSP::Transaction'; use File::Basename; use RSP::Transaction::Mojo::HostMap; use Mojo::Asset::File; sub hostname { my $self = shift; if (!$self->{hostname}) { my $mapmeth = RSP->config->{mojo}->{hostmapper} || 'hostname'; $self->{hostname} = RSP::Transaction::Mojo::HostMap->$mapmeth( $self->request ); } return $self->{hostname}; } sub encode_body { my $self = shift; my $body = shift; ## ## if we have a simple body string, use that, otherwise ## we need to be a bit more clever ## if (!ref($body)) { $self->response->body( $body ); } else { if ( ref($body) eq 'JavaScript::Function' ) { ## it's a javascript function, call it and use the ## returned data my $content = $self->context->call( $body ); if ($@) { die $@ }; $self->response->body( $content ); } elsif ( ref($body) && $body->isa('RSP::JSObject') ) { if ( $body->isa('RSP::JSObject::File') ) { my $f = Mojo::Asset::File->new; $f->path( $body->fullpath ); $self->response->content->asset( $f ); } else { ## ## it's an object that exists in both JS and Perl, convert it ## to it's stringified form, with a hint for the content-type. ## $self->response->body( $body->as_string( type => $self->response->headers->content_type ) ); } } elsif ( ref($body) && $body->isa('JavaScript::Generator') ) { my $resp = $self->response; $resp->headers->transfer_encoding('chunked'); $resp->headers->trailer('X-Trailing'); my $chunked = Mojo::Filter::Chunked->new; my $bytecount = bytes::length( $resp->build() ) + bytes::length( $self->request->build ); $resp->body_cb(sub { my $content = shift; my $result = $body->next(); if (!$result) { my $header = Mojo::Headers->new; $header->header('X-Trailing', 'true'); $self->end( 1 ); ## cleanup the transaction here because we couldn't do it earlier $bytecount += bytes::length( $header->build ); my $bwreport = RSP::Consumption::Bandwidth->new(); $bwreport->count( $bytecount ); $bwreport->host( $self->hostname ); $bwreport->uri( $self->url ); $self->consumption_log( $bwreport ); return $chunked->build( $header ); } else { $bytecount += bytes::length( $result ); return $chunked->build( $result ); } }); } else { ## ## we don't know what to do with it. ## die "don't know what to do with " . ref($body) . " object"; } } } sub encode_array_response { my $self = shift; my $response = shift; my @resp = @$response; my ($code, $codestr, $headers, $body); if (@resp == 4) { ($code, $codestr, $headers, $body) = @resp; } elsif (@resp == 3) { ($code, $headers, $body) = @resp; } $self->response->code( $code ); my @headers = @$headers; while( my $key = shift @headers ) { my $value = shift @headers; ## why do we need to special case this? if ( $key eq 'Set-Cookie') { my $cookies = Mojo::Cookie::Response->new->parse( $value ); $self->response->cookies( $cookies->[0] ); } else { $self->response->headers->add( $key, $value ); } } $self->encode_body( $body ); } ## ## turns the response from the code into the Mojo::Message object ## that the web server needs. ## sub encode_response { my $self = shift; my $response = shift; if ( ref( $response ) && ref( $response ) eq 'ARRAY' ) { ## we're encoding a list... $self->encode_array_response( $response ); } else { ## we're encoding a single thing... $self->response->headers->content_type( 'text/html' ); $self->encode_body( $response ); } if ( $self->response->headers->transfer_encoding && $self->response->headers->transfer_encoding eq 'chunked' ) { $self->response->headers->remove('Content-Length'); } else { if ( !$self->response->headers->content_length) { $self->response->headers->content_length( $self->response->content->body_size ); } } } ## ## terminates the transaction ## sub end { my $self = shift; my $post_callback = shift; if ($post_callback || !($self->response->headers->transfer_encoding && $self->response->headers->transfer_encoding eq "chunked")) { $self->report_consumption; undef( $self->{cache} ); $self->cleanup_js_environment; } } sub process_transaction { my $self = shift; $self->url( $self->request->url->path->to_string ); $self->SUPER::process_transaction( @_ ); } ## ## return the HTTP request object translated into something that ## JavaScript can process ## sub build_entrypoint_arguments { my $self = shift; my $cookies; if ( $self->request->cookies ) { foreach my $cookie ( @{ $self->request->cookies } ) { my $name = $cookie->name; my $value = $cookie->value->to_string; $cookies->{$name} = "$value"; } } my %body = %{$self->request->body_params->to_hash}; foreach my $key (keys %body) { $body{$key} = Encode::decode("utf8", $body{$key}); } my %query = %{$self->request->query_params->to_hash}; my $request = {}; my $uploads = {}; eval { $request->{type} = 'HTTP'; $request->{uri} = $self->request->url->path->to_string; $request->{method} = $self->request->method; $request->{query} = \%query, $request->{body} = \%body, $request->{cookies} = $cookies; ## if we've got a multipart request, don't bother with ## the content. if ( $self->request->is_multipart ) { ## map the uploads to RSP file objects $uploads = { map { my $name = $_->name; my $file = $_->file; ( $name => RSP::JSObject::File->new( $file->path, basename( $_->filename ) ) ) } @{ $self->request->uploads } }; } else { $request->{content} = Encode::decode( 'utf8', $self->request->body ); } $request->{headers} = { map { ( $_ => $self->request->headers->header($_) ) } @{ $self->request->headers->names } }; $request->{queryString} = $self->request->url->query->to_string; }; $request->{uploads} = $uploads; return $request; } ## ## this is mojo specific ## sub bw_consumed { my $self = shift; my $ib = $self->inbound_bw_consumed; my $ob = $self->outbound_bw_consumed; return $ib + $ob; } sub outbound_bw_consumed { my $self = shift; bytes::length( $self->response->build() ); } sub inbound_bw_consumed { my $self = shift; bytes::length( $self->request->build() ); } 1;
konobi/smart-platform
lib/RSP/Transaction/Mojo.pm
Perl
mit
6,650
/**************************************************** % File Name: pronto_morph_irreg_verb.pl % Author: Jason Schlachter (ai@uga.edu)(www.arches.uga.edu/~ai) % Released: May 8th, 2003 % Artificial Intelligence Center (www.ai.uga.edu) % ***see pronto_morph.pdf for documentation % % This file is to be used as part of the morphological analyzer % that is a component of ProNTo (Prolog Natural Language % Toolkit), made at the Artificial Intelligence Center of % the University of Georgia (www.ai.uga.edu). % % Special thanks: % 1)To the wordnet project for their list words that are exceptions to the spelling rules. % 2)To Dr. Covington for his guidence on the project. ******************************************************/ :-multifile( irregular_form/3 ). % irregular_form(+Atom,-Tail,-List) % Interprets an irregular form (as an open list) irregular_form( ran, X, [run, -past | X ]). irregular_form( run, X, [run, -en | X ]). irregular_form( eaten, X, [eat, -en | X] ). irregular_form( has, X, [have, -sg3 | X] ). irregular_form( had, X, [have, -ed | X] ). % contractions minus the apostrophe % irregular_form( cant, X, [can, not | X] ). irregular_form( ill, X, [i, will | X] ). irregular_form( didnt, X, [did, not | X] ). irregular_form( doesnt, X, [do, -sg3, not | X ]). % this one has three irregular_form( wouldnt, X, [would, not | X] ). irregular_form( couldnt, X, [could, not | X] ). irregular_form( shouldnt, X, [should, not | X] ). irregular_form( wasnt, X, [is, -past, not | X] ). irregular_form( isnt, X, [is, not | X] ). irregular_form( mustnt, X, [must, not | X] ). irregular_form( youll, X, [you, will | X] ). % adapted from modified exception list from wordnet % irregular_form( abode,X,[abide,-past| X ]). irregular_form( arcked,X,[arc,-ed| X ]). irregular_form( arcking,X,[arc,-ing| X ]). irregular_form( arose,X,[arise,-past| X ]). irregular_form( ate,X,[eat,-past| X ]). irregular_form( awoke,X,[awake,-past| X ]). irregular_form( awoken,X,[awake,-en| X ]). irregular_form( backbit,X,[backbite,-past| X ]). irregular_form( backbitten,X,[backbite,-en| X ]). irregular_form( backslid,X,[backslide,-past| X ]). irregular_form( backslidden,X,[backslide,-en| X ]). irregular_form( bade,X,[bid,-past| X ]). irregular_form( beaten,X,[beat,-en| X ]). irregular_form( became,X,[become,-past| X ]). irregular_form( befallen,X,[befall,-en| X ]). irregular_form( befell,X,[befall,-past| X ]). irregular_form( began,X,[begin,-past| X ]). irregular_form( begat,X,[beget,-past| X ]). irregular_form( begot,X,[beget,-past| X ]). irregular_form( begotten,X,[beget,-en| X ]). irregular_form( begun,X,[begin,-en| X ]). irregular_form( beheld,X,[behold,-past| X ]). irregular_form( beholden,X,[behold,-en| X ]). irregular_form( belying,X,[belie,-ing| X ]). irregular_form( bent,X,[bend,-past| X ]). irregular_form( besought,X,[beseech,-past| X ]). irregular_form( bespoke,X,[bespeak,-past| X ]). irregular_form( bespoken,X,[bespeak,-en| X ]). irregular_form( bethought,X,[bethink,-past| X ]). irregular_form( betook,X,[betake,-past| X ]). irregular_form( bidden,X,[bid,-en| X ]). irregular_form( bit,X,[bite,-past| X ]). irregular_form( bitten,X,[bite,-en| X ]). irregular_form( bivouacked,X,[bivouac,-past| X ]). irregular_form( bivouacking,X,[bivouac,-ing| X ]). irregular_form( bled,X,[bleed,-past| X ]). irregular_form( blest,X,[bless,-past| X ]). irregular_form( blew,X,[blow,-past| X ]). irregular_form( blown,X,[blow,-en| X ]). irregular_form( bore,X,[bear,-past| X ]). irregular_form( born,X,[bear,-en| X ]). irregular_form( borne,X,[bear,-en| X ]). irregular_form( bought,X,[buy,-past| X ]). irregular_form( bound,X,[bind,-past| X ]). irregular_form( bred,X,[breed,-past| X ]). irregular_form( broke,X,[break,-past| X ]). irregular_form( broken,X,[break,-en| X ]). irregular_form( brought,X,[bring,-past| X ]). irregular_form( browbeaten,X,[browbeat,-en| X ]). irregular_form( built,X,[build,-past| X ]). irregular_form( burnt,X,[burn,-past| X ]). irregular_form( bypast,X,[bypass,-past| X ]). irregular_form( came,X,[come,-past| X ]). irregular_form( caught,X,[catch,-past| X ]). irregular_form( chevied,X,[chivy,-past| X ]). irregular_form( chevies,X,[chivy,-sg| X ]). irregular_form( chevying,X,[chivy,-ing| X ]). irregular_form( chose,X,[choose,-past| X ]). irregular_form( chosen,X,[choose,-en| X ]). irregular_form( clad,X,[clothe,-past| X ]). irregular_form( cleft,X,[cleave,-past| X ]). irregular_form( clept,X,[clepe,-past| X ]). irregular_form( clove,X,[cleave,-past| X ]). irregular_form( cloven,X,[cleave,-en| X ]). irregular_form( clung,X,[cling,-past| X ]). irregular_form( countersank,X,[countersink,-past| X ]). irregular_form( countersunk,X,[countersink,-past| X ]). irregular_form( crept,X,[creep,-past| X ]). irregular_form( crossbred,X,[crossbreed,-past| X ]). irregular_form( curst,X,[curse,-past| X ]). irregular_form( dealt,X,[deal,-past| X ]). irregular_form( did,X,[do,-past| X ]). irregular_form( disenthralls,X,[disenthral,-sg| X ]). irregular_form( done,X,[do,-past| X ]). irregular_form( dought,X,[dow,-past| X ]). irregular_form( dove,X,[dive,-past| X ]). irregular_form( drank,X,[drink,-past| X ]). irregular_form( drawn,X,[draw,-en| X ]). irregular_form( dreamt,X,[dream,-past| X ]). irregular_form( drew,X,[draw,-past| X ]). irregular_form( drove,X,[drive,-past| X ]). irregular_form( drunk,X,[drink,-past| X ]). irregular_form( dug,X,[dig,-past| X ]). irregular_form( dwelt,X,[dwell,-past| X ]). irregular_form( dying,X,[die,-ing| X ]). irregular_form( enwound,X,[enwind,-past| X ]). irregular_form( fallen,X,[fall,-en| X ]). irregular_form( fed,X,[feed,-past| X ]). irregular_form( fell,X,[fall,-past| X ]). irregular_form( fled,X,[flee,-past| X ]). irregular_form( flew,X,[fly,-past| X ]). irregular_form( floodlit,X,[floodlight,-past| X ]). irregular_form( flown,X,[fly,-en| X ]). irregular_form( flung,X,[fling,-past| X ]). irregular_form( forbad,X,[forbid,-past| X ]). irregular_form( forbade,X,[forbid,-past| X ]). irregular_form( forbidden,X,[forbid,-en| X ]). irregular_form( forbore,X,[forbear,-past| X ]). irregular_form( forborne,X,[forbear,-past| X ]). irregular_form( foregone,X,[forego,-past| X ]). irregular_form( foreknew,X,[foreknow,-past| X ]). irregular_form( foreknown,X,[foreknow,-en| X ]). irregular_form( foreran,X,[forerun,-past| X ]). irregular_form( foresaw,X,[foresee,-past| X ]). irregular_form( foreshown,X,[foreshow,-en| X ]). irregular_form( forespoke,X,[forespeak,-past| X ]). irregular_form( forespoken,X,[forespeak,-en| X ]). irregular_form( foretold,X,[foretell,-past| X ]). irregular_form( forewent,X,[forego,-past| X ]). irregular_form( forgave,X,[forgive,-past| X ]). irregular_form( forgone,X,[forgo,-past| X ]). irregular_form( forgot,X,[forget,-past| X ]). irregular_form( forgotten,X,[forget,-en| X ]). irregular_form( forsook,X,[forsake,-past| X ]). irregular_form( forspoke,X,[forspeak,-past| X ]). irregular_form( forspoken,X,[forspeak,-en| X ]). irregular_form( forswore,X,[forswear,-past| X ]). irregular_form( forsworn,X,[forswear,-en| X ]). irregular_form( forwent,X,[forgo,-past| X ]). irregular_form( fought,X,[fight,-past| X ]). irregular_form( found,X,[find,-past| X ]). irregular_form( frolicked,X,[frolic,-past| X ]). irregular_form( frolicking,X,[frolic,-ing| X ]). irregular_form( froze,X,[freeze,-past| X ]). irregular_form( frozen,X,[freeze,-en| X ]). irregular_form( gainsaid,X,[gainsay,-past| X ]). irregular_form( gan,X,[gin,-past| X ]). irregular_form( gave,X,[give,-past| X ]). irregular_form( gelt,X,[geld,-past| X ]). irregular_form( ghostwritten,X,[ghostwrite,-en| X ]). irregular_form( ghostwrote,X,[ghostwrite,-past| X ]). irregular_form( gilt,X,[gild,-past| X ]). irregular_form( girt,X,[gird,-past| X ]). irregular_form( gnawn,X,[gnaw,-en| X ]). irregular_form( gone,X,[go,-past| X ]). irregular_form( got,X,[get,-past| X ]). irregular_form( gotten,X,[get,-en| X ]). irregular_form( grew,X,[grow,-past| X ]). irregular_form( gript,X,[grip,-past| X ]). irregular_form( ground,X,[grind,-past| X ]). irregular_form( grown,X,[grow,-en| X ]). irregular_form( hacksawn,X,[hacksaw,-en| X ]). irregular_form( hamstrung,X,[hamstring,-past| X ]). irregular_form( handfed,X,[handfeed,-past| X ]). irregular_form( held,X,[hold,-past| X ]). irregular_form( hewn,X,[hew,-en| X ]). irregular_form( hid,X,[hide,-past| X ]). irregular_form( hidden,X,[hide,-en| X ]). irregular_form( hogtying,X,[hogtie,-ing| X ]). irregular_form( honied,X,[honey,-past| X ]). irregular_form( hove,X,[heave,-past| X ]). irregular_form( hung,X,[hang,-past| X ]). irregular_form( inbred,X,[inbreed,-past| X ]). irregular_form( indwelt,X,[indwell,-past| X ]). irregular_form( inlaid,X,[inlay,-past| X ]). irregular_form( interbred,X,[interbreed,-past| X ]). irregular_form( interlaid,X,[interlay,-past| X ]). irregular_form( interpled,X,[interplead,-past| X ]). irregular_form( interwove,X,[interweave,-past| X ]). irregular_form( interwoven,X,[interweave,-en| X ]). irregular_form( inwove,X,[inweave,-past| X ]). irregular_form( inwoven,X,[inweave,-en| X ]). irregular_form( kent,X,[ken,-past| X ]). irregular_form( kept,X,[keep,-past| X ]). irregular_form( knelt,X,[kneel,-past| X ]). irregular_form( knew,X,[know,-past| X ]). irregular_form( known,X,[know,-en| X ]). irregular_form( ladyfied,X,[ladify,-past| X ]). irregular_form( ladyfies,X,[ladify,-sg| X ]). irregular_form( ladyfying,X,[ladify,-ing| X ]). irregular_form( laid,X,[lay,-past| X ]). irregular_form( lain,X,[lie,-en| X ]). irregular_form( lay,X,[lie,-past| X ]). irregular_form( leant,X,[lean,-past| X ]). irregular_form( leapt,X,[leap,-past| X ]). irregular_form( learnt,X,[learn,-past| X ]). irregular_form( led,X,[lead,-past| X ]). irregular_form( left,X,[leave,-past| X ]). irregular_form( lent,X,[lend,-past| X ]). irregular_form( lit,X,[light,-past| X ]). irregular_form( lost,X,[lose,-past| X ]). irregular_form( lying,X,[lie,-ing| X ]). irregular_form( made,X,[make,-past| X ]). irregular_form( meant,X,[mean,-past| X ]). irregular_form( met,X,[meet,-past| X ]). irregular_form( mimicked,X,[mimic,-past| X ]). irregular_form( mimicking,X,[mimic,-ing| X ]). irregular_form( misbecame,X,[misbecome,-past| X ]). irregular_form( misdealt,X,[misdeal,-past| X ]). irregular_form( misgave,X,[misgive,-past| X ]). irregular_form( mislaid,X,[mislay,-past| X ]). irregular_form( misled,X,[mislead,-past| X ]). irregular_form( mispled,X,[misplead,-past| X ]). irregular_form( misspelt,X,[misspell,-past| X ]). irregular_form( misspent,X,[misspend,-past| X ]). irregular_form( mistook,X,[mistake,-past| X ]). irregular_form( misunderstood,X,[misunderstand,-past| X ]). irregular_form( molten,X,[melt,-en| X ]). irregular_form( mown,X,[mow,-en| X ]). irregular_form( outbidden,X,[outbid,-en| X ]). irregular_form( outbred,X,[outbreed,-past| X ]). irregular_form( outdid,X,[outdo,-past| X ]). irregular_form( outdone,X,[outdo,-en| X ]). irregular_form( outdrawn,X,[outdraw,-en| X ]). irregular_form( outdrew,X,[outdraw,-past| X ]). irregular_form( outfought,X,[outfight,-past| X ]). irregular_form( outgone,X,[outgo,-en| X ]). irregular_form( outgrew,X,[outgrow,-past| X ]). irregular_form( outgrown,X,[outgrow,-en| X ]). irregular_form( outlaid,X,[outlay,-past| X ]). irregular_form( outran,X,[outrun,-past| X ]). irregular_form( outridden,X,[outride,-en| X ]). irregular_form( outrode,X,[outride,-past| X ]). irregular_form( outshone,X,[outshine,-past| X ]). irregular_form( outshot,X,[outshoot,-past| X ]). irregular_form( outsold,X,[outsell,-past| X ]). irregular_form( outstood,X,[outstand,-past| X ]). irregular_form( outthought,X,[outthink,-past| X ]). irregular_form( outwent,X,[outgo,-past| X ]). irregular_form( outwore,X,[outwear,-past| X ]). irregular_form( outworn,X,[outwear,-en| X ]). irregular_form( overbidden,X,[overbid,-en| X ]). irregular_form( overblew,X,[overblow,-past| X ]). irregular_form( overblown,X,[overblow,-en| X ]). irregular_form( overbore,X,[overbear,-past| X ]). irregular_form( overborne,X,[overbear,-en| X ]). irregular_form( overbuilt,X,[overbuild,-past| X ]). irregular_form( overcame,X,[overcome,-past| X ]). irregular_form( overdid,X,[overdo,-past| X ]). irregular_form( overdone,X,[overdo,-past| X ]). irregular_form( overdrawn,X,[overdraw,-en| X ]). irregular_form( overdrew,X,[overdraw,-past| X ]). irregular_form( overdrove,X,[overdrive,-past| X ]). irregular_form( overflew,X,[overfly,-past| X ]). irregular_form( overflown,X,[overfly,-en| X ]). irregular_form( overgrew,X,[overgrow,-past| X ]). irregular_form( overgrown,X,[overgrow,-en| X ]). irregular_form( overhung,X,[overhang,-past| X ]). irregular_form( overlaid,X,[overlay,-past| X ]). irregular_form( overlain,X,[overlie,-en| X ]). irregular_form( overlay,X,[overlie,-past| X ]). irregular_form( overlying,X,[overlie,-ing| X ]). irregular_form( overpaid,X,[overpay,-past| X ]). irregular_form( overpast,X,[overpass,-past| X ]). irregular_form( overran,X,[overrun,-past| X ]). irregular_form( overridden,X,[override,-en| X ]). irregular_form( overrode,X,[override,-past| X ]). irregular_form( oversaw,X,[oversee,-past| X ]). irregular_form( oversewn,X,[oversew,-en| X ]). irregular_form( overshot,X,[overshoot,-past| X ]). irregular_form( overslept,X,[oversleep,-past| X ]). irregular_form( oversold,X,[oversell,-past| X ]). irregular_form( overspent,X,[overspend,-past| X ]). irregular_form( overspilt,X,[overspill,-past| X ]). irregular_form( overthrew,X,[overthrow,-past| X ]). irregular_form( overthrown,X,[overthrow,-past| X ]). irregular_form( overtook,X,[overtake,-past| X ]). irregular_form( overwound,X,[overwind,-past| X ]). irregular_form( overwritten,X,[overwrite,-en| X ]). irregular_form( overwrote,X,[overwrite,-past| X ]). irregular_form( paid,X,[pay,-past| X ]). irregular_form( panicked,X,[panic,-past| X ]). irregular_form( panicking,X,[panic,-ing| X ]). irregular_form( partook,X,[partake,-past| X ]). irregular_form( pasquilled,X,[pasquinade,-past| X ]). irregular_form( pasquilling,X,[pasquinade,-ing| X ]). irregular_form( pent,X,[pen,-past| X ]). irregular_form( physicked,X,[physic,-past| X ]). irregular_form( physicking,X,[physic,-ing| X ]). irregular_form( picnicked,X,[picnic,-past| X ]). irregular_form( picnicking,X,[picnic,-ing| X ]). irregular_form( pled,X,[plead,-past| X ]). irregular_form( prepaid,X,[prepay,-past| X ]). irregular_form( programmes,X,[program,-sg| X ]). irregular_form( prologed,X,[prologue,-past| X ]). irregular_form( prologing,X,[prologue,-ing| X ]). irregular_form( prologs,X,[prologue,-sg| X ]). irregular_form( quartersawn,X,[quartersaw,-en| X ]). irregular_form( rang,X,[ring,-past| X ]). irregular_form( rebuilt,X,[rebuild,-past| X ]). irregular_form( redid,X,[redo,-past| X ]). irregular_form( redone,X,[redo,-past| X ]). irregular_form( reft,X,[reave,-past| X ]). irregular_form( remade,X,[remake,-past| X ]). irregular_form( rent,X,[rend,-past| X ]). irregular_form( repaid,X,[repay,-past| X ]). irregular_form( reran,X,[rerun,-past| X ]). irregular_form( resat,X,[resit,-past| X ]). irregular_form( resewn,X,[resew,-en| X ]). irregular_form( rethought,X,[rethink,-past| X ]). irregular_form( retold,X,[retell,-past| X ]). irregular_form( retook,X,[retake,-past| X ]). irregular_form( rewound,X,[rewind,-past| X ]). irregular_form( rewritten,X,[rewrite,-en| X ]). irregular_form( rewrote,X,[rewrite,-past| X ]). irregular_form( ridden,X,[ride,-en| X ]). irregular_form( rode,X,[ride,-past| X ]). irregular_form( rose,X,[rise,-past| X ]). irregular_form( rove,X,[reeve,-past| X ]). irregular_form( rung,X,[ring,-past| X ]). irregular_form( said,X,[say,-past| X ]). irregular_form( sang,X,[sing,-past| X ]). irregular_form( sank,X,[sink,-past| X ]). irregular_form( sat,X,[sit,-past| X ]). irregular_form( saw,X,[see,-past| X ]). irregular_form( sawn,X,[saw,-en| X ]). irregular_form( sent,X,[send,-past| X ]). irregular_form( sewn,X,[sew,-en| X ]). irregular_form( shat,X,[shit,-past| X ]). irregular_form( shellacked,X,[shellac,-past| X ]). irregular_form( shellacking,X,[shellac,-ing| X ]). irregular_form( shent,X,[shend,-past| X ]). irregular_form( shewn,X,[shew,-en| X ]). irregular_form( shod,X,[shoe,-past| X ]). irregular_form( shone,X,[shine,-past| X ]). irregular_form( shook,X,[shake,-past| X ]). irregular_form( shot,X,[shoot,-past| X ]). irregular_form( shown,X,[show,-en| X ]). irregular_form( shrank,X,[shrink,-past| X ]). irregular_form( shrove,X,[shrive,-past| X ]). irregular_form( shrunk,X,[shrink,-past| X ]). irregular_form( shrunken,X,[shrink,-en| X ]). irregular_form( sicked,X,[sic,-past| X ]). irregular_form( sicking,X,[sic,-ing| X ]). irregular_form( sightsaw,X,[sightsee,-past| X ]). irregular_form( skydove,X,[skydive,-past| X ]). irregular_form( slain,X,[slay,-past| X ]). irregular_form( slept,X,[sleep,-past| X ]). irregular_form( slew,X,[slay,-past| X ]). irregular_form( slid,X,[slide,-past| X ]). irregular_form( slidden,X,[slide,-en| X ]). irregular_form( slung,X,[sling,-past| X ]). irregular_form( slunk,X,[slink,-past| X ]). irregular_form( smelt,X,[smell,-past| X ]). irregular_form( smit,X,[smite,-past| X ]). irregular_form( smitten,X,[smite,-en| X ]). irregular_form( smote,X,[smite,-sg| X ]). irregular_form( sold,X,[sell,-past| X ]). irregular_form( soothsaid,X,[soothsay,-past| X ]). irregular_form( sought,X,[seek,-past| X ]). irregular_form( sown,X,[sow,-en| X ]). irregular_form( spat,X,[spit,-past| X ]). irregular_form( sped,X,[speed,-past| X ]). irregular_form( spellbound,X,[spellbind,-past| X ]). irregular_form( spelt,X,[spell,-past| X ]). irregular_form( spent,X,[spend,-past| X ]). irregular_form( spilt,X,[spill,-past| X ]). irregular_form( spoilt,X,[spoil,-past| X ]). irregular_form( spoke,X,[speak,-past| X ]). irregular_form( spoken,X,[speak,-en| X ]). irregular_form( spotlit,X,[spotlight,-past| X ]). irregular_form( sprang,X,[spring,-past| X ]). irregular_form( sprung,X,[spring,-past| X ]). irregular_form( spun,X,[spin,-past| X ]). irregular_form( stank,X,[stink,-past| X ]). irregular_form( stilettoeing,X,[stiletto,-ing| X ]). irregular_form( stole,X,[steal,-past| X ]). irregular_form( stolen,X,[steal,-en| X ]). irregular_form( stood,X,[stand,-past| X ]). irregular_form( stove,X,[stave,-past| X ]). irregular_form( strewn,X,[strew,-en| X ]). irregular_form( stridden,X,[stride,-en| X ]). irregular_form( strode,X,[stride,-past| X ]). irregular_form( strove,X,[strive,-past| X ]). irregular_form( strown,X,[strow,-past| X ]). irregular_form( struck,X,[strike,-past| X ]). irregular_form( strung,X,[string,-past| X ]). irregular_form( stuck,X,[stick,-past| X ]). irregular_form( stung,X,[sting,-past| X ]). irregular_form( stunk,X,[stink,-past| X ]). irregular_form( stymying,X,[stymie,-ing| X ]). irregular_form( sung,X,[sing,-past| X ]). irregular_form( sunk,X,[sink,-past| X ]). irregular_form( sunken,X,[sink,-en| X ]). irregular_form( swam,X,[swim,-past| X ]). irregular_form( swept,X,[sweep,-past| X ]). irregular_form( swollen,X,[swell,-en| X ]). irregular_form( swore,X,[swear,-past| X ]). irregular_form( sworn,X,[swear,-past| X ]). irregular_form( swum,X,[swim,-past| X ]). irregular_form( swung,X,[swing,-past| X ]). irregular_form( talcked,X,[talc,-past| X ]). irregular_form( talcking,X,[talc,-ing| X ]). irregular_form( taught,X,[teach,-past| X ]). irregular_form( taxying,X,[taxi,-ing| X ]). irregular_form( thought,X,[think,-past| X ]). irregular_form( threw,X,[throw,-past| X ]). irregular_form( throve,X,[thrive,-past| X ]). irregular_form( thrown,X,[throw,-past| X ]). irregular_form( told,X,[tell,-past| X ]). irregular_form( took,X,[take,-past| X ]). irregular_form( tore,X,[tear,-past| X ]). irregular_form( torn,X,[tear,-past| X ]). irregular_form( torrify,X,[torrefy,-past| X ]). irregular_form( trafficked,X,[traffic,-past| X ]). irregular_form( trafficking,X,[traffic,-ing| X ]). irregular_form( trameled,X,[trammel,-past| X ]). irregular_form( trameling,X,[trammel,-ing| X ]). irregular_form( tramelled,X,[trammel,-past| X ]). irregular_form( tramelling,X,[trammel,-ing| X ]). irregular_form( transfixt,X,[transfix,-past| X ]). irregular_form( trod,X,[tread,-past| X ]). irregular_form( trodden,X,[tread,-en| X ]). irregular_form( tying,X,[tie,-ing| X ]). irregular_form( typewritten,X,[typewrite,-en| X ]). irregular_form( typewrote,X,[typewrite,-past| X ]). irregular_form( unbent,X,[unbend,-past| X ]). irregular_form( unbound,X,[unbind,-past| X ]). irregular_form( unclad,X,[unclothe,-past| X ]). irregular_form( underbought,X,[underbuy,-past| X ]). irregular_form( underfed,X,[underfeed,-past| X ]). irregular_form( undergirt,X,[undergird,-past| X ]). irregular_form( undergone,X,[undergo,-past| X ]). irregular_form( underlaid,X,[underlay,-past| X ]). irregular_form( underlain,X,[underlie,-past| X ]). irregular_form( underlay,X,[underlie,-past| X ]). irregular_form( underlying,X,[underlie,-ing| X ]). irregular_form( underpaid,X,[underpay,-past| X ]). irregular_form( undershot,X,[undershoot,-past| X ]). irregular_form( undersold,X,[undersell,-past| X ]). irregular_form( understood,X,[understand,-past| X ]). irregular_form( undertook,X,[undertake,-past| X ]). irregular_form( underwent,X,[undergo,-past| X ]). irregular_form( underwritten,X,[underwrite,-en| X ]). irregular_form( underwrote,X,[underwrite,-past| X ]). irregular_form( undid,X,[undo,-past| X ]). irregular_form( undone,X,[undo,-past| X ]). irregular_form( unfroze,X,[unfreeze,-past| X ]). irregular_form( unfrozen,X,[unfreeze,-en| X ]). irregular_form( unlaid,X,[unlay,-past| X ]). irregular_form( unlearnt,X,[unlearn,-past| X ]). irregular_form( unmade,X,[unmake,-past| X ]). irregular_form( unrove,X,[unreeve,-past| X ]). irregular_form( unsaid,X,[unsay,-past| X ]). irregular_form( unslung,X,[unsling,-past| X ]). irregular_form( unspoke,X,[unspeak,-past| X ]). irregular_form( unstrung,X,[unstring,-past| X ]). irregular_form( unstuck,X,[unstick,-past| X ]). irregular_form( unswore,X,[unswear,-past| X ]). irregular_form( unsworn,X,[unswear,-past| X ]). irregular_form( untaught,X,[unteach,-past| X ]). irregular_form( unthought,X,[unthink,-past| X ]). irregular_form( untrod,X,[untread,-past| X ]). irregular_form( untrodden,X,[untread,-en| X ]). irregular_form( untying,X,[untie,-ing| X ]). irregular_form( unwound,X,[unwind,-past| X ]). irregular_form( upbuilt,X,[upbuild,-past| X ]). irregular_form( upheld,X,[uphold,-past| X ]). irregular_form( uphove,X,[upheave,-past| X ]). irregular_form( uprose,X,[uprise,-past| X ]). irregular_form( upsprang,X,[upspring,-past| X ]). irregular_form( upsprung,X,[upspring,-past| X ]). irregular_form( upswept,X,[upsweep,-past| X ]). irregular_form( upswollen,X,[upswell,-en| X ]). irregular_form( upswung,X,[upswing,-past| X ]). irregular_form( vying,X,[vie,-ing| X ]). irregular_form( waylaid,X,[waylay,-past| X ]). irregular_form( went,X,[go,-past| X ]). irregular_form( wept,X,[weep,-past| X ]). irregular_form( winterfed,X,[winterfeed,-past| X ]). irregular_form( wiredrawn,X,[wiredraw,-en| X ]). irregular_form( wiredrew,X,[wiredraw,-past| X ]). irregular_form( withdrawn,X,[withdraw,-en| X ]). irregular_form( withdrew,X,[withdraw,-past| X ]). irregular_form( withheld,X,[withhold,-past| X ]). irregular_form( withstood,X,[withstand,-past| X ]). irregular_form( woke,X,[wake,-past| X ]). irregular_form( woken,X,[wake,-en| X ]). irregular_form( won,X,[win,-past| X ]). irregular_form( wore,X,[wear,-past| X ]). irregular_form( worn,X,[wear,-en| X ]). irregular_form( wound,X,[wind,-past| X ]). irregular_form( wove,X,[weave,-past| X ]). irregular_form( woven,X,[weave,-en| X ]). irregular_form( written,X,[write,-en| X ]). irregular_form( wrote,X,[write,-past| X ]). irregular_form( wrought,X,[work,-past| X ]). irregular_form( wrung,X,[wring,-past| X ]). irregular_form( ycleped,X,[clepe,-past| X ]). irregular_form( yclept,X,[clepe,-past| X ]).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/ProNTo/Schlachter/pronto_morph_irreg_verb.pl
Perl
mit
23,870
#!/usr/bin/perl use warnings; use strict; use Getopt::Long; ############################################################## # script: mfannot2gff3.pl # author: Jia-Xing Yue (GitHub ID: yjx1217) # last edited: 2018.09.01 # description: converting the mfannot output to the GFF3 format # example: perl mfannot2gff3.pl -i genome.mfannot.out -o genome.mfannot.gff3 -m lite ############################################################## my ($input, $output, $mode); $mode = "lite"; # use lite to filter out gene models annotated within introns GetOptions('input|i:s' => \$input, 'output|o:s' => \$output, 'mode|m:s' => \$mode); # "full" or "lite" my $input_fh = read_file($input); my %chr = (); my @chr = (); my %features = (); my @features = (); my $feature = ""; my %gene2exon_intron = (); while (<$input_fh>) { chomp; /^\s*$/ and next; /^#/ and next; /^;;/ and next; if (/^>(.*) gc=(\d+)/) { my $chr = $1; $chr{$chr}{'genetic_code'} = $2; print "chr=$chr, genetic_code=$chr{$chr}{'genetic_code'}\n"; push @chr, $chr; } elsif (/^;\s+G-(\S+)\s+(\S+)\s+(start|end)\s*(\S?\.*)/) { $feature = $1; my $feature_type; my $feature_strand = $2; my $feature_mark = $3; my $feature_note = $4; if ($feature =~ /(\S+)-E(\d+)$/) { $gene2exon_intron{$1}{'exon'}{$2} = $feature; $feature_type = "exon"; } elsif ($feature =~ /(\S+)-I(\d+)$/) { $gene2exon_intron{$1}{'intron'}{$2} = $feature; $feature_type = "intron"; } else { $feature_type = "gene"; } if ($feature_strand eq "==>") { $feature_strand = "+"; } else { $feature_strand = "-"; } print "feature=$feature, feature_type=$feature_type, strand=$feature_strand, mark=$feature_mark, note=$feature_note\n"; if (not exists $features{$feature}{'type'}) { $features{$feature}{'type'} = $feature_type; push @features, $feature; # print "add new feature: $feature\n"; } if (not exists $features{$feature}{'strand'}) { $features{$feature}{'strand'} = $feature_strand; } if (not exists $features{$feature}{'note'}) { @{$features{$feature}{'note'}} = ($feature_note); } else { push @{$features{$feature}{'note'}}, $feature_note; } if (not exists $features{$feature}{'seq'}) { $features{$feature}{'seq'} = ""; } if (not exists $features{$feature}{'start'}) { $features{$feature}{'start'} = ""; } if (not exists $features{$feature}{'end'}) { $features{$feature}{'end'} = ""; } $features{$feature}{'mark'} = $feature_mark; my $flag = 0; if (($features{$feature}{'mark'} eq "end" ) and ($features{$feature}{'strand'} eq "+")) { $flag = 1; } if (($features{$feature}{'mark'} eq "start" ) and ($features{$feature}{'strand'} eq "-")) { $flag = 1; } if ($flag == 1) { $feature = ""; } } elsif (/^\s+(\d+)\s+([ATCGatcgNn]+)/) { my ($pos_start, $seq) = ($1, $2); my $pos_end = length($seq) + $pos_start - 1; if ($feature ne "") { if (($features{$feature}{'mark'} eq "start") and ($features{$feature}{'strand'} eq "+")) { if ($features{$feature}{'start'} eq "") { $features{$feature}{'start'} = $pos_start; } $features{$feature}{'seq'} = $features{$feature}{'seq'} . $seq; $features{$feature}{'end'} = $pos_end; } if (($features{$feature}{'mark'} eq "end") and ($features{$feature}{'strand'} eq "-")) { if ($features{$feature}{'end'} eq "") { $features{$feature}{'end'} = $pos_start; } $features{$feature}{'seq'} = revcom($seq) . $features{$feature}{'seq'}; $features{$feature}{'start'} = $pos_end; } } } } my $output_fh = write_file($output); print $output_fh "##gff-version 3\n"; foreach my $chr (@chr) { print "output chr=$chr\n"; print $output_fh "##chr=$chr, genetic_code=$chr{$chr}{'genetic_code'}\n"; # adjustment before output foreach my $feature (@features) { my $feature_note = join ";", @{$features{$feature}{'note'}}; if ($features{$feature}{'strand'} eq "-") { ($features{$feature}{'start'}, $features{$feature}{'end'}) = ($features{$feature}{'end'}, $features{$feature}{'start'}); } } # begin to output foreach my $feature (@features) { print "output feature=$feature\n"; if ($features{$feature}{'type'} eq "gene") { if ($feature =~ /(rnl|rns|rps)/) { print $output_fh "$chr\tmfannot\trRNA\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${feature};Name=${feature}\n"; } else { if ($mode eq "lite") { if ($feature =~ /-I(\d+)-/) { next; } } if (not exists $gene2exon_intron{$feature}) { # single exon gene print $output_fh "$chr\tmfannot\tgene\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=$feature;Name=$feature\n"; print $output_fh "$chr\tmfannot\tmRNA\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${feature}.mRNA.1;Name=${feature}.mRNA.1;Parent=$feature\n"; # add back exon/CDS annotation my $gene_id = $feature; my $exon_index = 1; print $output_fh "$chr\tmfannot\texon\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${gene_id}.exon.$exon_index;Name=${gene_id}.exon.$exon_index;Parent=${gene_id}.mRNA.1\n"; print $output_fh "$chr\tmfannot\tCDS\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${gene_id}.CDS.$exon_index;Name=${gene_id}.CDS.$exon_index;Parent=${gene_id}.mRNA.1\n"; } else { # multi-exon gene # add back gene annotation my $gene_start; my $gene_end; my @exon_index = sort {$a <=> $b} keys %{$gene2exon_intron{$feature}{'exon'}}; my $last_exon_index = $exon_index[-1]; $gene_start = $features{"${feature}-E1"}{'start'}; $gene_end = $features{"${feature}-E${last_exon_index}"}{'end'}; if ($features{$feature}{'strand'} eq "+") { $features{$feature}{'start'} = $gene_start; $features{$feature}{'end'} = $gene_end; } else { $features{$feature}{'start'} = $gene_end; $features{$feature}{'end'} = $gene_start; } print $output_fh "$chr\tmfannot\tgene\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=$feature;Name=$feature\n"; print $output_fh "$chr\tmfannot\tmRNA\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${feature}.mRNA.1;Name=${feature}.mRNA.1;Parent=$feature\n"; } } } elsif ($features{$feature}{'type'} eq "exon") { my ($gene_id, $exon_index) = ($feature =~ /(\S+)-E(\d+)/); print $output_fh "$chr\tmfannot\texon\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${gene_id}.exon.$exon_index;Name=${gene_id}.exon.$exon_index;Parent=${gene_id}.mRNA.1\n"; print $output_fh "$chr\tmfannot\tCDS\t$features{$feature}{'start'}\t$features{$feature}{'end'}\t.\t$features{$feature}{'strand'}\t.\tID=${gene_id}.CDS.$exon_index;Name=${gene_id}.CDS.$exon_index;Parent=${gene_id}.mRNA.1\n"; } } } sub read_file { my $file = shift @_; my $fh; if ($file =~ /\.gz$/) { open($fh, "gunzip -c $file |") or die "can't open pipe to $file"; } else { open($fh, $file) or die "can't open $file"; } return $fh; } sub write_file { my $file = shift @_; my $fh; if ($file =~ /.gz$/) { open($fh, "| gzip -c >$file") or die "can't open $file\n"; } else { open($fh, ">$file") or die "can't open $file\n"; } return $fh; } sub revcom { my $seq = shift @_; my $seq_revcom = reverse $seq; $seq_revcom =~ tr/ATGCNatgcn/TACGNtacgn/; return $seq_revcom; }
yjx1217/LRSDAY
scripts/mfannot2gff3.pl
Perl
mit
7,855
# Time-stamp: "Sat Jul 14 00:27:39 2001 by Automatic Bizooty (__blocks2pm.plx)" $Text::\SEPA\Unicode\Unidecode::Char[0xb9] = [ 'ruk', 'rut', 'rup', 'ruh', 'rweo', 'rweog', 'rweogg', 'rweogs', 'rweon', 'rweonj', 'rweonh', 'rweod', 'rweol', 'rweolg', 'rweolm', 'rweolb', 'rweols', 'rweolt', 'rweolp', 'rweolh', 'rweom', 'rweob', 'rweobs', 'rweos', 'rweoss', 'rweong', 'rweoj', 'rweoc', 'rweok', 'rweot', 'rweop', 'rweoh', 'rwe', 'rweg', 'rwegg', 'rwegs', 'rwen', 'rwenj', 'rwenh', 'rwed', 'rwel', 'rwelg', 'rwelm', 'rwelb', 'rwels', 'rwelt', 'rwelp', 'rwelh', 'rwem', 'rweb', 'rwebs', 'rwes', 'rwess', 'rweng', 'rwej', 'rwec', 'rwek', 'rwet', 'rwep', 'rweh', 'rwi', 'rwig', 'rwigg', 'rwigs', 'rwin', 'rwinj', 'rwinh', 'rwid', 'rwil', 'rwilg', 'rwilm', 'rwilb', 'rwils', 'rwilt', 'rwilp', 'rwilh', 'rwim', 'rwib', 'rwibs', 'rwis', 'rwiss', 'rwing', 'rwij', 'rwic', 'rwik', 'rwit', 'rwip', 'rwih', 'ryu', 'ryug', 'ryugg', 'ryugs', 'ryun', 'ryunj', 'ryunh', 'ryud', 'ryul', 'ryulg', 'ryulm', 'ryulb', 'ryuls', 'ryult', 'ryulp', 'ryulh', 'ryum', 'ryub', 'ryubs', 'ryus', 'ryuss', 'ryung', 'ryuj', 'ryuc', 'ryuk', 'ryut', 'ryup', 'ryuh', 'reu', 'reug', 'reugg', 'reugs', 'reun', 'reunj', 'reunh', 'reud', 'reul', 'reulg', 'reulm', 'reulb', 'reuls', 'reult', 'reulp', 'reulh', 'reum', 'reub', 'reubs', 'reus', 'reuss', 'reung', 'reuj', 'reuc', 'reuk', 'reut', 'reup', 'reuh', 'ryi', 'ryig', 'ryigg', 'ryigs', 'ryin', 'ryinj', 'ryinh', 'ryid', 'ryil', 'ryilg', 'ryilm', 'ryilb', 'ryils', 'ryilt', 'ryilp', 'ryilh', 'ryim', 'ryib', 'ryibs', 'ryis', 'ryiss', 'rying', 'ryij', 'ryic', 'ryik', 'ryit', 'ryip', 'ryih', 'ri', 'rig', 'rigg', 'rigs', 'rin', 'rinj', 'rinh', 'rid', 'ril', 'rilg', 'rilm', 'rilb', 'rils', 'rilt', 'rilp', 'rilh', 'rim', 'rib', 'ribs', 'ris', 'riss', 'ring', 'rij', 'ric', 'rik', 'rit', 'rip', 'rih', 'ma', 'mag', 'magg', 'mags', 'man', 'manj', 'manh', 'mad', 'mal', 'malg', 'malm', 'malb', 'mals', 'malt', 'malp', 'malh', 'mam', 'mab', 'mabs', 'mas', 'mass', 'mang', 'maj', 'mac', 'mak', 'mat', 'map', 'mah', 'mae', 'maeg', 'maegg', 'maegs', 'maen', 'maenj', 'maenh', 'maed', 'mael', 'maelg', 'maelm', 'maelb', 'maels', 'maelt', 'maelp', 'maelh', 'maem', 'maeb', 'maebs', 'maes', 'maess', 'maeng', 'maej', 'maec', 'maek', 'maet', 'maep', 'maeh', ]; 1;
dmitrirussu/php-sepa-xml-generator
src/Unicode/data/perl_source/xb9.pm
Perl
mit
2,266
package XML::Grammar::Builder; use strict; use warnings; use base 'Test::Run::Builder'; our $VERSION = '0.0200'; sub new { my $package = shift; my %args = @_; my @extradata_files; my $builder = $package->SUPER::new( share_dir => 'extradata', auto_configure_requires => 1, @_ ); return $builder; } =begin excluded my $get_dest_extradata_cb = sub { my $fn = shift; # Trying if this makes it work. # TODO : Either remove this line or the rest of the lines. return $fn; $fn =~ s{^extradata}{data}; return "lib/$module_name/$fn"; }; =end excluded =cut 1;
gitpan/XML-Grammar-Vered
inc/XML/Grammar/Builder.pm
Perl
mit
668
:- module(ohno, [ ohno/1, pretty_print/1]). :- use_module(library(clpfd)). %%% LOGIC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% ohno(?Rows) % % True iff Rows is a solution of the game http://0hn0.com on a square % board at most 11 tiles wide and high, represented as a list of lists % (rows) in which red dots are represented by `0` and blue dots are % represented by the number of other blue dots they can see. ohno(Rows) :- % Board shape: between(1, 11, Length), % limit for the benefit of pretty-printing square(Length, Rows), % Determine minimum and maximum numbers for each dot: Max is (Length - 1) * 2, maplist(maplist(seemax(Max)), Rows), % Make four matrixes that indicate how many blue dots each dot sees in each % direction, i.e. in the East... maplist(row_seen, Rows, EastMatrix), % ...West... maplist(reverse, Rows, ReversedRows), maplist(row_seen, ReversedRows, ReversedWestMatrix), maplist(reverse, ReversedWestMatrix, WestMatrix), % ...South... transpose(Rows, Columns), maplist(row_seen, Columns, TransposedSouthMatrix), transpose(TransposedSouthMatrix, SouthMatrix), % ...and North. maplist(reverse, Columns, ReversedColumns), maplist(row_seen, ReversedColumns, ReversedTransposedNorthMatrix), maplist(reverse, ReversedTransposedNorthMatrix, TransposedNorthMatrix), transpose(TransposedNorthMatrix, NorthMatrix), % Sum up the four directions for each dot: maplist(maplist(sum), EastMatrix, WestMatrix, SouthMatrix, NorthMatrix, Rows), % Generate a ground solution: flatten(Rows, Cells), label(Cells). sum(East, West, South, North, Dot) :- Dot #= East + West + South + North. seemax(Max, Dot) :- Dot in 0..Max. square(Length, Rows) :- length(Rows, Length), maplist(length_(Length), Rows). length_(Length, List) :- length(List, Length). %% row_seen(+Row, -Seen) % % Given a row, indicates how many blue dots each dot in the row sees on % its right (red dots are blind and don't see anything). row_seen([_], [0]) :- !. row_seen([First,Second|Rest], [FirstSees,SecondSees|RestSee]) :- row_seen([Second|Rest], [SecondSees|RestSee]), % If the second dot is blue and so is the first, the first sees one more blue % dot than the second on the right: ( First #> 0 #/\ Second #> 0 #==> FirstSees #= SecondSees + 1 ), % If the second is red, it blocks the first dot's view and it doesn't see any % blue dots on the right: ( Second #= 0 #==> FirstSees #= 0 ). %%% PRETTY PRINTING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% pretty_print(Rows) :- forall( ( member(Row, Rows) ), ( forall( ( member(Cell, Row) ), ( cell_color(Cell, Color), cell_string(Cell, String), ansi_format([fg(Color)], '~w', [String]) ) ), nl ) ). cell_color(0, red) :- !. cell_color(_, blue). cell_string(0, ●) :- !. cell_string(N, String) :- nth1(N, [❶, ❷, ❸, ❹, ❺, ❻, ❼, ❽, ❾, ❿, ⓫, ⓬, ⓭, ⓮, ⓯, ⓰, ⓱, ⓲, ⓳, ⓴], String). %%% HELPERS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% maplist(:Goal, ?List1, ?List2, ?List3, ?List4) % % As maplist/2, operating on quintuples of elements from four % lists. maplist(Goal, List1, List2, List3, List4, List5) :- maplist_(List1, List2, List3, List4, List5, Goal). maplist_([], [], [], [], [], _). maplist_([Elem1|Tail1], [Elem2|Tail2], [Elem3|Tail3], [Elem4|Tail4], [Elem5|Tail5], Goal) :- call(Goal, Elem1, Elem2, Elem3, Elem4, Elem5), maplist_(Tail1, Tail2, Tail3, Tail4, Tail5, Goal).
texttheater/puzzling
ohno.pl
Perl
mit
3,700
#!/usr/bin/perl -wW use strict; use Net::Netmask; while (<>){ chomp; my $n=new Net::Netmask ($_); print "".$n->base()."/".$n->bits()."\n"; }
mmmonk/crap
home_stuff/net2bitbase.pl
Perl
mit
147
# # 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::aws::custom::awscli; use strict; use warnings; use DateTime; use JSON::XS; sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; if (!defined($options{output})) { print "Class Custom: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class Custom: Need to specify 'options' argument."); $options{output}->option_exit(); } if (!defined($options{noptions})) { $options{options}->add_options(arguments => { 'aws-secret-key:s' => { name => 'aws_secret_key' }, 'aws-access-key:s' => { name => 'aws_access_key' }, 'aws-session-token:s' => { name => 'aws_session_token' }, 'aws-profile:s' => { name => 'aws_profile' }, 'endpoint-url:s' => { name => 'endpoint_url' }, 'region:s' => { name => 'region' }, 'timeframe:s' => { name => 'timeframe' }, 'period:s' => { name => 'period' }, 'statistic:s@' => { name => 'statistic' }, 'zeroed' => { name => 'zeroed' }, 'timeout:s' => { name => 'timeout', default => 50 }, 'sudo' => { name => 'sudo' }, 'command:s' => { name => 'command', default => 'aws' }, 'command-path:s' => { name => 'command_path' }, 'command-options:s' => { name => 'command_options', default => '' }, 'proxyurl:s' => { name => 'proxyurl' } }); } $options{options}->add_help(package => __PACKAGE__, sections => 'AWSCLI OPTIONS', once => 1); $self->{output} = $options{output}; $self->{custommode_name} = $options{custommode_name}; return $self; } sub get_region { my ($self, %options) = @_; return $self->{option_results}->{region}; } sub set_options { my ($self, %options) = @_; $self->{option_results} = $options{option_results}; } sub set_defaults { my ($self, %options) = @_; foreach (keys %{$options{default}}) { if ($_ eq $self->{custommode_name}) { if (ref($options{default}->{$_}) eq 'ARRAY') { for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { foreach my $opt (keys %{$options{default}->{$_}[$i]}) { if (!defined($self->{option_results}->{$opt}[$i])) { $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; } } } } if (ref($options{default}->{$_}) eq 'HASH') { foreach my $opt (keys %{$options{default}->{$_}}) { if (!defined($self->{option_results}->{$opt})) { $self->{option_results}->{$opt} = $options{default}->{$_}->{$opt}; } } } } } } sub check_options { my ($self, %options) = @_; if (defined($self->{option_results}->{proxyurl}) && $self->{option_results}->{proxyurl} ne '') { $ENV{HTTP_PROXY} = $self->{option_results}->{proxyurl}; $ENV{HTTPS_PROXY} = $self->{option_results}->{proxyurl}; } if (defined($self->{option_results}->{aws_secret_key}) && $self->{option_results}->{aws_secret_key} ne '') { $ENV{AWS_SECRET_ACCESS_KEY} = $self->{option_results}->{aws_secret_key}; } if (defined($self->{option_results}->{aws_access_key}) && $self->{option_results}->{aws_access_key} ne '') { $ENV{AWS_ACCESS_KEY_ID} = $self->{option_results}->{aws_access_key}; } if (defined($self->{option_results}->{aws_session_token}) && $self->{option_results}->{aws_session_token} ne '') { $ENV{AWS_SESSION_TOKEN} = $self->{option_results}->{aws_session_token}; } if (defined($self->{option_results}->{aws_profile}) && $self->{option_results}->{aws_profile} ne '') { $ENV{AWS_PROFILE} = $self->{option_results}->{aws_profile}; } if (!defined($self->{option_results}->{region}) || $self->{option_results}->{region} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --region option."); $self->{output}->option_exit(); } if (defined($self->{option_results}->{statistic})) { foreach my $statistic (@{$self->{option_results}->{statistic}}) { if ($statistic !~ /minimum|maximum|average|sum/) { $self->{output}->add_option_msg(short_msg => "Statistic '" . $statistic . "' is not handled"); $self->{output}->option_exit(); } } } $self->{endpoint_url} = (defined($self->{option_results}->{endpoint_url})) ? $self->{option_results}->{endpoint_url} : undef; return 0; } sub execute { my ($self, %options) = @_; my $cmd_options = $options{cmd_options}; $cmd_options .= " --debug" if ($self->{output}->is_debug()); $self->{output}->output_add(long_msg => "Command line: '" . $self->{option_results}->{command} . " " . $cmd_options . "'", debug => 1); my ($response) = centreon::plugins::misc::execute( output => $self->{output}, options => $self->{option_results}, sudo => $self->{option_results}->{sudo}, command => $self->{option_results}->{command}, command_path => $self->{option_results}->{command_path}, command_options => $cmd_options, redirect_stderr => ($self->{output}->is_debug()) ? 0 : 1 ); my $raw_results; eval { $raw_results = JSON::XS->new->utf8->decode($response); }; if ($@) { $self->{output}->output_add(long_msg => $response, debug => 1); $self->{output}->add_option_msg(short_msg => "Cannot decode response (add --debug option to display returned content)"); $self->{output}->option_exit(); } return $raw_results; } sub cloudwatch_get_metrics_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "cloudwatch get-metric-statistics --region $self->{option_results}->{region} --namespace $options{namespace}" . " --metric-name '$options{metric_name}' --start-time $options{start_time} --end-time $options{end_time}" . " --period $options{period} --statistics " . join(' ', @{$options{statistics}}) . " --output json --dimensions"; foreach my $entry (@{$options{dimensions}}) { $cmd_options .= " 'Name=$entry->{Name},Value=$entry->{Value}'"; } $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub cloudwatch_get_metrics { my ($self, %options) = @_; my $metric_results = {}; my $start_time = DateTime->now->subtract(seconds => $options{timeframe})->iso8601; my $end_time = DateTime->now->iso8601; foreach my $metric_name (@{$options{metrics}}) { my $cmd_options = $self->cloudwatch_get_metrics_set_cmd(%options, metric_name => $metric_name, start_time => $start_time, end_time => $end_time); my $raw_results = $self->execute(cmd_options => $cmd_options); $metric_results->{$raw_results->{Label}} = { points => 0 }; foreach my $point (@{$raw_results->{Datapoints}}) { if (defined($point->{Average})) { $metric_results->{$raw_results->{Label}}->{average} = 0 if (!defined($metric_results->{$raw_results->{Label}}->{average})); $metric_results->{$raw_results->{Label}}->{average} += $point->{Average}; } if (defined($point->{Minimum})) { $metric_results->{$raw_results->{Label}}->{minimum} = $point->{Minimum} if (!defined($metric_results->{$raw_results->{Label}}->{minimum}) || $point->{Minimum} < $metric_results->{$raw_results->{Label}}->{minimum}); } if (defined($point->{Maximum})) { $metric_results->{$raw_results->{Label}}->{maximum} = $point->{Maximum} if (!defined($metric_results->{$raw_results->{Label}}->{maximum}) || $point->{Maximum} > $metric_results->{$raw_results->{Label}}->{maximum}); } if (defined($point->{Sum})) { $metric_results->{$raw_results->{Label}}->{sum} = 0 if (!defined($metric_results->{$raw_results->{Label}}->{sum})); $metric_results->{$raw_results->{Label}}->{sum} += $point->{Sum}; } $metric_results->{$raw_results->{Label}}->{points}++; } if (defined($metric_results->{$raw_results->{Label}}->{average})) { $metric_results->{$raw_results->{Label}}->{average} /= $metric_results->{$raw_results->{Label}}->{points}; } } return $metric_results; } sub discovery_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = $options{service} . " " . $options{command} . " --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub discovery { my ($self, %options) = @_; my $cmd_options = $self->discovery_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return $raw_results; } sub cloudwatch_get_alarms_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "cloudwatch describe-alarms --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub cloudwatch_get_alarms { my ($self, %options) = @_; my $cmd_options = $self->cloudwatch_get_alarms_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $alarm_results = []; foreach my $alarm (@{$raw_results->{MetricAlarms}}) { push @$alarm_results, { AlarmName => $alarm->{AlarmName}, StateValue => $alarm->{StateValue}, MetricName => $alarm->{MetricName}, StateReason => $alarm->{StateReason}, StateUpdatedTimestamp => $alarm->{StateUpdatedTimestamp}, }; } return $alarm_results; } sub cloudwatch_list_metrics_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "cloudwatch list-metrics --region $self->{option_results}->{region} --output json"; $cmd_options .= " --namespace $options{namespace}" if (defined($options{namespace})); $cmd_options .= " --metric-name $options{metric}" if (defined($options{metric})); $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub cloudwatch_list_metrics { my ($self, %options) = @_; my $cmd_options = $self->cloudwatch_list_metrics_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return $raw_results->{Metrics}; } sub cloudwatchlogs_describe_log_groups_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "logs describe-log-groups --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub cloudwatchlogs_describe_log_groups { my ($self, %options) = @_; my $cmd_options = $self->cloudwatchlogs_describe_log_groups_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return $raw_results->{logGroups}; } sub cloudwatchlogs_filter_log_events_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "logs filter-log-events --region $self->{option_results}->{region} --output json --log-group-name '$options{group_name}'"; $cmd_options .= " --start-time $options{start_time}" if (defined($options{start_time})); if (defined($options{stream_names})) { $cmd_options .= " --log-stream-names"; foreach (@{$options{stream_names}}) { $cmd_options .= " '$_'"; } } $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub cloudwatchlogs_filter_log_events { my ($self, %options) = @_; my $cmd_options = $self->cloudwatchlogs_filter_log_events_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return $raw_results->{events}; } sub ebs_list_volumes_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-volumes --no-dry-run --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub ebs_list_volumes { my ($self, %options) = @_; my $cmd_options = $self->ebs_list_volumes_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $resource_results = []; foreach my $volume_request (@{$raw_results->{Volumes}}) { my @name_tags; foreach my $tag (@{$volume_request->{Tags}}) { if ($tag->{Key} eq "Name" && defined($tag->{Value})) { push @name_tags, $tag->{Value}; } }; push @{$resource_results}, { VolumeId => $volume_request->{VolumeId}, VolumeName => join(",", @name_tags), VolumeType => $volume_request->{VolumeType}, VolumeState => $volume_request->{State} }; } return $resource_results; } sub ec2_get_instances_status_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-instance-status --include-all-instances --no-dry-run --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub ec2_get_instances_status { my ($self, %options) = @_; my $cmd_options = $self->ec2_get_instances_status_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $instance_results = {}; foreach (@{$raw_results->{InstanceStatuses}}) { $instance_results->{$_->{InstanceId}} = { state => $_->{InstanceState}->{Name}, status => $_->{InstanceStatus}->{Status} }; } return $instance_results; } sub ec2spot_get_active_instances_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-spot-fleet-instances --no-dry-run --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); $cmd_options .= " --spot-fleet-request-id " . $options{spot_fleet_request_id}; return $cmd_options; } sub ec2spot_get_active_instances_status { my ($self, %options) = @_; my $cmd_options = $self->ec2spot_get_active_instances_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $instance_results = {}; foreach (@{$raw_results->{ActiveInstances}}) { $instance_results->{$_->{InstanceId}} = { health => $_->{InstanceHealth}, type => $_->{InstanceType}, request_id => $_->{SpotInstanceRequestId} }; } return $instance_results; } sub ec2spot_list_fleet_requests_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-spot-fleet-requests --no-dry-run --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub ec2spot_list_fleet_requests { my ($self, %options) = @_; my $cmd_options = $self->ec2spot_list_fleet_requests_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $resource_results = []; foreach my $fleet_request (@{$raw_results->{SpotFleetRequestConfigs}}) { push @{$resource_results}, { SpotFleetRequestState => $fleet_request->{SpotFleetRequestState}, SpotFleetRequestId => $fleet_request->{SpotFleetRequestId}, ActivityStatus => $fleet_request->{ActivityStatus} }; } return $resource_results; } sub ec2_list_resources_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-instances --no-dry-run --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub ec2_list_resources { my ($self, %options) = @_; my $cmd_options = $self->ec2_list_resources_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $resource_results = []; foreach my $reservation (@{$raw_results->{Reservations}}) { foreach my $instance (@{$reservation->{Instances}}) { my @instance_tags; foreach my $tag (@{$instance->{Tags}}) { my %already = map { $_->{Name} => $_ } @{$resource_results}; if ($tag->{Key} eq "aws:autoscaling:groupName") { next if (defined($already{$tag->{Value}})); push @{$resource_results}, { Name => $tag->{Value}, Type => 'asg', }; } elsif ($tag->{Key} eq "Name" && defined($tag->{Value})) { push @instance_tags, $tag->{Value}; } } push @{$resource_results}, { Name => $instance->{InstanceId}, Type => 'instance', AvailabilityZone => $instance->{Placement}->{AvailabilityZone}, InstanceType => $instance->{InstanceType}, State => $instance->{State}->{Name}, Tags => join(',', @instance_tags), KeyName => $instance->{KeyName} }; } } return $resource_results; } sub ec2_get_instances { my ($self, %options) = @_; my $cmd_options = $self->ec2_list_resources_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $instance_results = {}; foreach my $reservation (@{$raw_results->{Reservations}}) { foreach my $instance (@{$reservation->{Instances}}) { $instance_results->{ $instance->{InstanceId} } = { State => $instance->{State}->{Name}, InstanceType => $instance->{InstanceType}, LaunchTime => $instance->{LaunchTime} }; } } return $instance_results; } sub asg_get_resources_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "autoscaling describe-auto-scaling-groups --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub asg_get_resources { my ($self, %options) = @_; my $cmd_options = $self->asg_get_resources_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return \@{$raw_results->{AutoScalingGroups}}; } sub rds_get_instances_status_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "rds describe-db-instances --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub rds_get_instances_status { my ($self, %options) = @_; my $cmd_options = $self->rds_get_instances_status_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $instance_results = {}; foreach (@{$raw_results->{DBInstances}}) { $instance_results->{$_->{DBInstanceIdentifier}} = { state => $_->{DBInstanceStatus} }; } return $instance_results; } sub rds_list_instances_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "rds describe-db-instances --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub rds_list_instances { my ($self, %options) = @_; my $cmd_options = $self->rds_list_instances_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $instance_results = []; foreach my $instance (@{$raw_results->{DBInstances}}) { push @{$instance_results}, { Name => $instance->{DBInstanceIdentifier}, AvailabilityZone => $instance->{AvailabilityZone}, Engine => $instance->{Engine}, StorageType => $instance->{StorageType}, DBInstanceStatus => $instance->{DBInstanceStatus}, AllocatedStorage => $instance->{AllocatedStorage} }; } return $instance_results; } sub rds_list_clusters_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "rds describe-db-clusters --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub rds_list_clusters { my ($self, %options) = @_; my $cmd_options = $self->rds_list_clusters_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $cluster_results = []; foreach my $cluster (@{$raw_results->{DBClusters}}) { push @{$cluster_results}, { Name => $cluster->{DBClusterIdentifier}, DatabaseName => $cluster->{DatabaseName}, Engine => $cluster->{Engine}, Status => $cluster->{Status}, AllocatedStorage => $cluster->{AllocatedStorage} }; } return $cluster_results; } sub vpn_list_connections_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-vpn-connections --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub vpn_list_connections { my ($self, %options) = @_; my $cmd_options = $self->vpn_list_connections_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $connections_results = []; foreach my $connection (@{$raw_results->{VpnConnections}}) { my @name_tags; foreach my $tag (@{$connection->{Tags}}) { if ($tag->{Key} eq "Name" && defined($tag->{Value})) { push @name_tags, $tag->{Value}; } } push @{$connections_results}, { id => $connection->{VpnConnectionId}, name => join(",", @name_tags), state => $connection->{State} } }; return $connections_results; } sub health_describe_events_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "health describe-events --region $self->{option_results}->{region} --output json"; my ($filter, $filter_append) = ('', ''); foreach ((['service', 'services'], ['region', 'regions'], ['entity_value', 'entityValues'], ['event_status', 'eventStatusCodes'], ['event_category', 'eventTypeCategories'])) { next if (!defined($options{ 'filter_' . $_->[0] })); $filter .= $filter_append . $_->[1] . '=' . join(',', @{$options{ 'filter_' . $_->[0] }}); $filter_append = ','; } $cmd_options .= " --filter '$filter'" if ($filter ne ''); $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub health_describe_events { my ($self, %options) = @_; my $cmd_options = $self->health_describe_events_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); return $raw_results->{events}; } sub health_describe_affected_entities_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "health describe-affected-entities --region $self->{option_results}->{region} --output json"; my $filter = ''; if (defined($options{filter_event_arns})) { $filter = 'eventArns=' . join(',', @{$options{filter_event_arns}}); } $cmd_options .= " --filter '$filter'" if ($filter ne ''); $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub health_describe_affected_entities { my ($self, %options) = @_; my $all_results = []; while (my @elements = splice(@{$options{filter_event_arns}}, 0, 10)) { my $cmd_options = $self->health_describe_affected_entities_set_cmd(filter_event_arns => \@elements); my $raw_results = $self->execute(cmd_options => $cmd_options); push @$all_results, @{$raw_results->{entities}}; } return $all_results; } sub sqs_list_queues_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "sqs list-queues --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub sqs_list_queues { my ($self, %options) = @_; my $cmd_options = $self->sqs_list_queues_set_cmd(%options); my $queues_results = $self->execute(cmd_options => $cmd_options); return $queues_results->{QueueUrls}; } sub sns_list_topics_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "sns list-topics --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub sns_list_topics { my ($self, %options) = @_; my $cmd_options = $self->sns_list_topics_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $topics_results = []; foreach my $topic (@{$raw_results->{Topics}}) { push @{$topics_results}, { name => $topic->{TopicArn} }; }; return $topics_results; } sub tgw_list_gateways_set_cmd { my ($self, %options) = @_; return if (defined($self->{option_results}->{command_options}) && $self->{option_results}->{command_options} ne ''); my $cmd_options = "ec2 describe-transit-gateways --region $self->{option_results}->{region} --output json"; $cmd_options .= " --endpoint-url $self->{endpoint_url}" if (defined($self->{endpoint_url}) && $self->{endpoint_url} ne ''); return $cmd_options; } sub tgw_list_gateways { my ($self, %options) = @_; my $cmd_options = $self->tgw_list_gateways_set_cmd(%options); my $raw_results = $self->execute(cmd_options => $cmd_options); my $gateway_results = []; foreach my $gateway (@{$raw_results->{TransitGateways}}) { push @{$gateway_results}, { id => $gateway->{TransitGatewayId}, name => $gateway->{Description} }; }; return $gateway_results; } 1; __END__ =head1 NAME Amazon AWS =head1 AWSCLI OPTIONS Amazon AWS CLI =over 8 =item B<--aws-secret-key> Set AWS secret key. =item B<--aws-access-key> Set AWS access key. =item B<--aws-session-token> Set AWS session token. =item B<--aws-profile> Set AWS profile. =item B<--endpoint-url> Override AWS service endpoint URL if necessary. =item B<--region> Set the region name (Required). =item B<--period> Set period in seconds. =item B<--timeframe> Set timeframe in seconds. =item B<--statistic> Set cloudwatch statistics (Can be: 'minimum', 'maximum', 'average', 'sum'). =item B<--zeroed> Set metrics value to 0 if none. Usefull when CloudWatch does not return value when not defined. =item B<--timeout> Set timeout in seconds (Default: 50). =item B<--sudo> Use 'sudo' to execute the command. =item B<--command> Command to get information (Default: 'aws'). Can be changed if you have output in a file. =item B<--command-path> Command path (Default: none). =item B<--command-options> Command options (Default: none). =item B<--proxyurl> Proxy URL if any =back =head1 DESCRIPTION B<custom>. =cut
Tpo76/centreon-plugins
cloud/aws/custom/awscli.pm
Perl
apache-2.0
32,081
=head1 LICENSE Copyright (c) 1999-2011 The European Bioinformatics Institute and Genome Research Limited. All rights reserved. This software is distributed under a modified Apache license. For license details, please see http://www.ensembl.org/info/about/code_licence.html =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <dev@ensembl.org>. Questions may also be sent to the Ensembl help desk at <helpdesk@ensembl.org>. =cut =head1 NAME Bio::EnsEMBL::DBSQL::BaseAlignFeatureAdaptor - Abstract Base class for AlignFeatureAdaptors =head1 SYNOPSIS Abstract class, should not be instantiated. Implementation of abstract methods must be performed by subclasses. =head1 DESCRIPTION This is a base adaptor for the align feature adaptors DnaAlignFeatureAdaptor and ProteinAlignFeatureAdaptor. =head1 METHODS =cut package Bio::EnsEMBL::DBSQL::BaseAlignFeatureAdaptor; use vars qw(@ISA @EXPORT); use strict; use Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor; @ISA = qw(Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor); @EXPORT = (@{$DBI::EXPORT_TAGS{'sql_types'}}); =head2 fetch_all_by_Slice_and_hcoverage Arg [1] : Bio::EnsEMBL::Slice $slice The slice from which to obtain align features. Arg [2] : (optional) float $hcoverage A lower bound for the hcoverage of feats to obtain. Arg [3] : (optional) string $logic_name The logic name of the type of features to obtain. Example : @feats = @{ $adaptor->fetch_all_by_Slice_and_hcoverage( $slice, 50.0 ) }; Description: Returns a listref of features created from the database which are on the Slice $slice and with a hcoverage greater than $hcoverage. If logic name is defined, only features with an analysis of type $logic_name will be returned. Returntype : listref of Bio::EnsEMBL::BaseAlignFeatures in Slice coordinates Exceptions : none Caller : general Status : At Risk =cut sub fetch_all_by_Slice_and_hcoverage { my ( $self, $slice, $hcoverage, $logic_name ) = @_; my $constraint; if ( defined($hcoverage) ) { $constraint = "hcoverage > $hcoverage"; } return $self->fetch_all_by_Slice_constraint( $slice, $constraint, $logic_name ); } =head2 fetch_all_by_Slice_and_external_db Arg [1] : Bio::EnsEMBL::Slice $slice The slice from which to obtain align features. Arg [2] : String $external_db_name Name of the external DB to which the align features should be restricted. Arg [3] : (optional) string $logic_name The logic name of the type of features to obtain. Example : @feats = @{ $adaptor->fetch_all_by_Slice_and_external_db( $slice, 'EMBL' ) }; Description: Returns a listref of features created from the database which are on the Slice $slice and associated with external DB $external_db_name. If logic name is defined, only features with an analysis of type $logic_name will be returned. Returntype : listref of Bio::EnsEMBL::BaseAlignFeatures in Slice coordinates Exceptions : thrown if $external_db_name is not defined or if the subclass does not return a table alias for the external_db table from _tables() Caller : general Status : At Risk =cut sub fetch_all_by_Slice_and_external_db { my ( $self, $slice, $external_db_name, $logic_name ) = @_; if ( !defined($external_db_name) ) { throw("Need name of external DB to restrict to"); } my @join_tables = $self->_tables(); my $edb_alias; foreach my $join_table (@join_tables) { my ( $table, $table_alias ) = @{$join_table}; if ( $table eq 'external_db' ) { $edb_alias = $table_alias; last; } } if ( !defined($edb_alias) ) { throw("Can not find alias for external_db table"); } my $constraint = sprintf( "%s.db_name = %s", $edb_alias, $self->dbc()->db_handle() ->quote( $external_db_name, SQL_VARCHAR ) ); return $self->fetch_all_by_Slice_constraint( $slice, $constraint, $logic_name ); } ## end sub fetch_all_by_Slice_and_external_db =head2 fetch_all_by_Slice_and_pid Arg [1] : Bio::EnsEMBL::Slice $slice The slice from which to obtain align features. Arg [2] : (optional) float $pid A lower bound for the percentage identity of features to obtain. Arg [3] : (optional) string $logic_name The logic name of the type of features to obtain. Example : @feats = @{ $adaptor->fetch_all_by_Slice_and_pid( $slice, 50.0 ) }; Description: Returns a listref of features created from the database which are on the Slice $slice and with a percentage identity greater than $pid. If logic name is defined, only features with an analysis of type $logic_name will be returned. Returntype : listref of Bio::EnsEMBL::BaseAlignFeatures in Slice coordinates Exceptions : none Caller : general Status : Stable =cut sub fetch_all_by_Slice_and_pid { my ( $self, $slice, $pid, $logic_name ) = @_; # #get the primary table alias # my @tabs = $self->_tables; # my $alias = $tabs[0]->[1]; # if(defined $pid) { # $constraint = "${alias}.perc_ident > $pid"; # } my $constraint; if ( defined($pid) ) { $constraint = sprintf( "perc_ident > %s", $self->dbc()->db_handle() ->quote( $pid, SQL_FLOAT ) ); } return $self->fetch_all_by_Slice_constraint( $slice, $constraint, $logic_name ); } =head2 fetch_all_by_hit_name Arg [1] : string $hit_name The hit_name of the features to obtain Arg [2] : (optional) string $logic_name The analysis logic name of the type of features to obtain. Example : @feats = @{ $adaptor->fetch_all_by_hit_name( $name, $logic_name ); } Description: Returns a listref of features created from the database which correspond to the given hit_name. If logic name is defined, only features with an analysis of type $logic_name will be returned. Returntype : listref of Bio::EnsEMBL::BaseAlignFeatures Exceptions : thrown if hit_name is not defined Caller : general Status : Stable =cut sub fetch_all_by_hit_name { my ( $self, $hit_name, $logic_name ) = @_; if ( !defined($hit_name) ) { throw("hit_name argument is required"); } # Construct a constraint like 't1.hit_name = "123"' my @tabs = $self->_tables(); my ( $name, $syn ) = @{ $tabs[0] }; my $constraint = sprintf( "%s.hit_name = %s", $syn, $self->dbc()->db_handle()->quote( $hit_name, SQL_VARCHAR ) ); if ( defined($logic_name) ) { # Add the $logic_name constraint $constraint = $self->_logic_name_to_constraint( $constraint, $logic_name ); } return $self->generic_fetch($constraint); } =head2 fetch_all_by_hit_name_unversioned Arg [1] : string $hit_name The beginning of the hit_name of the features to obtain, e.g. AA768786 would retrieve AA768786.1, AA768786.2 etc. Arg [2] : (optional) string $logic_name The analysis logic name of the type of features to obtain. Example : @feats = @{ $adaptor->fetch_all_by_hit_name( $name, $logic_name ) }; Description: Returns a listref of features created from the database which start with the given hit_name. If logic name is defined, only features with an analysis of type $logic_name will be returned. Returntype : listref of Bio::EnsEMBL::BaseAlignFeatures Exceptions : thrown if hit_name is not defined Caller : general Status : At risk =cut sub fetch_all_by_hit_name_unversioned { my ( $self, $hit_name, $logic_name ) = @_; if ( !defined($hit_name) ) { throw("hit_name argument is required"); } #construct a constraint like 't1.hit_name = "123"' my @tabs = $self->_tables; my ( $name, $syn ) = @{ $tabs[0] }; my $constraint = sprintf( "%s.hit_name LIKE %s", $syn, $self->dbc()->db_handle()->quote( $hit_name . '.%', SQL_VARCHAR ) ); if ( defined($logic_name) ) { # Add the $logic_name constraint $constraint = $self->_logic_name_to_constraint( $constraint, $logic_name ); } return $self->generic_fetch($constraint); } =head2 fetch_all_by_RawContig_and_pid Description: DEPRECATED use fetch_all_by_Slice_and_pid instead =cut sub fetch_all_by_RawContig_and_pid { my($self, $contig, $pid, $logic_name) = @_; my $constraint; #get the primary table alias my @tabs = $self->_tables; my $alias = $tabs[0]->[1]; if(defined $pid) { $constraint = "${alias}.perc_ident > $pid"; } return $self->fetch_all_by_RawContig_constraint($contig, $constraint, $logic_name); } ##implemented by subclasses: # store # _tables # _columns # _obj_from_hashref 1;
adamsardar/perl-libs-custom
EnsemblAPI/ensembl/modules/Bio/EnsEMBL/DBSQL/BaseAlignFeatureAdaptor.pm
Perl
apache-2.0
9,570
#!/usr/bin/perl -w # MySQL Database Backup Script # Licensed under ASF 2.0 (see LICENSE file) # Copyright 1999 - 2012 Philip Jacob <phil@whirlycott.com> use strict; use vars qw($HOSTNAME $USERNAME $PASSWORD @db); ########################################### #CONFIGURATION # Dbs you want to back up. my @db = qw( db_name_here wordpress another_db_name_here ); # Tables you want to ignore (optional) my @ignores = qw(""); #my $prefix=" --ignore-table=db_name_here."; my $prefix = " "; my %opts = ('db_name_here' => $prefix.join($prefix, @ignores)); # Pass these in on the command line in the order they appear in this list assignment. my ($HOSTNAME, $USERNAME, $PASSWORD) = @ARGV; unless ($HOSTNAME && $USERNAME && $PASSWORD) { print ("Usage: $0 hostname username password\n"); exit 1; } # I usually run this under a user called 'mybackups'. my $ZIP_PROGRAM = "/bin/gzip"; my $ZIP_SUFFIX = "gz"; my $BAK_DIR = "/home/mybackups/mysql_bak"; my $S3_BUCKET = "s3://yourcompany.mysql.backups/"; ########################################### #END CONFIGURATION foreach my $database (@db) { #Get a timestamp value. my ($timestamp) = &gettime; #Get a standard filename for this file. my ($filename) = "$HOSTNAME.mysql." . $database . "." . $timestamp . ".sql"; #Dump the db. &dbdump($filename, $database); #Symlink -latest `ln -sf $BAK_DIR/$filename.$ZIP_SUFFIX $BAK_DIR/$HOSTNAME.mysql.$database-latest.sql.$ZIP_SUFFIX`; #Send backup to s3 `s3cmd put $BAK_DIR/$filename.$ZIP_SUFFIX $S3_BUCKET`; } ##############SUBROUTINES sub dbdump { my ($filename, $db) = @_; my $command; if (defined($opts{$db})) { $command = "/usr/bin/mysqldump --single-transaction -q -h$HOSTNAME -u$USERNAME -p$PASSWORD ".$opts{$db}." $db | $ZIP_PROGRAM > $BAK_DIR/$filename.$ZIP_SUFFIX; /bin/chmod 440 $BAK_DIR/$filename.$ZIP_SUFFIX"; } else { $command = "/usr/bin/mysqldump --single-transaction -q -h$HOSTNAME -u$USERNAME -p$PASSWORD $db | $ZIP_PROGRAM > $BAK_DIR/$filename.$ZIP_SUFFIX; /bin/chmod 440 $BAK_DIR/$filename.$ZIP_SUFFIX"; } system ($command); #print $command, "\n"; } sub gettime { my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime; $year = 1900 + $year; my $monn = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[$mon]; my $wdayn = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")[$wday]; my $filename = $year . "_" . $monn . "_" . sprintf("%02d",$mday) . "_" . $wdayn . "_" . $hour . "_" . $min . "_" . $sec; return $filename; }
whirlycott/mysql-backup-script
backup-mysql.pl
Perl
apache-2.0
2,622
# # 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::extreme::snmp::mode::components::poe; use strict; use warnings; my %map_poe_status = ( 1 => 'initializing', 2 => 'operational', 3 => 'downloadFail', 4 => 'calibrationRequired', 5 => 'invalidFirmware', 6 => 'mismatchVersion', 7 => 'updating', 8 => 'invalidDevice', 9 => 'notOperational', 10 => 'other', ); my $mapping = { extremePethSlotPoeStatus => { oid => '.1.3.6.1.4.1.1916.1.27.1.2.1.8', map => \%map_poe_status }, }; my $mapping2 = { extremePethSlotMeasuredPower => { oid => '.1.3.6.1.4.1.1916.1.27.1.2.1.14' }, }; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $mapping->{extremePethSlotPoeStatus}->{oid} }, { oid => $mapping2->{extremePethSlotMeasuredPower}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking poes"); $self->{components}->{poe} = {name => 'poes', total => 0, skip => 0}; return if ($self->check_filter(section => 'poe')); my ($exit, $warn, $crit, $checked); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$mapping->{extremePethSlotPoeStatus}->{oid}}})) { $oid =~ /^$mapping->{extremePethSlotPoeStatus}->{oid}\.(.*)$/; my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$mapping->{extremePethSlotPoeStatus}->{oid}}, instance => $instance); my $result2 = $self->{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$mapping2->{extremePethSlotMeasuredPower}->{oid}}, instance => $instance); next if ($self->check_filter(section => 'poe', instance => $instance)); $result2->{extremePethSlotMeasuredPower} = defined($result2->{extremePethSlotMeasuredPower}) && $result2->{extremePethSlotMeasuredPower} =~ /\d+/ ? sprintf("%.3f", $result2->{extremePethSlotMeasuredPower} / 1000) : 'unknown'; $self->{components}->{poe}->{total}++; $self->{output}->output_add(long_msg => sprintf("Poe '%s' status is '%s' [instance = %s, power = %s]", $instance, $result->{extremePethSlotPoeStatus}, $instance, $result2->{extremePethSlotMeasuredPower})); $exit = $self->get_severity(section => 'poe', value => $result->{extremePethSlotPoeStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Poe '%s' status is '%s'", $instance, $result->{extremePethSlotPoeStatus})); next; } next if ($result2->{extremePethSlotMeasuredPower} !~ /\d+/); ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'poe', instance => $instance, value => $result2->{extremePethSlotMeasuredPower}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Poe '%s' is '%s' W", $instance, $result2->{extremePethSlotMeasuredPower})); } $self->{output}->perfdata_add(label => 'poe_power_' . $instance, unit => 'W', value => $result2->{extremePethSlotMeasuredPower}, warning => $warn, critical => $crit, min => 0 ); } } 1;
wilfriedcomte/centreon-plugins
network/extreme/snmp/mode/components/poe.pm
Perl
apache-2.0
4,426