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 |
|---|---|---|---|---|---|
#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Long;
use FindBin;
use List::Util qw(max);
sub usage{
print <<USAGE;
$FindBin::Script [OPTIONS]
A script to get window statistics from
a gene positions file.
Assume the table contains four columns:
ID Chr Start End
Particularly, the ID contains the type
information, e.g. Gene1_a2, underscore
is required, "a" is type, 2 will be
ignored.
[-i,--input] FILE
-o,--output FILE
Default print results to STDOUT
-w,--window NUM
Default: 1_000_000
USAGE
exit;
}
sub get_options{
GetOptions(
"input=s" => \my $infile,
"output=s" => \my $outfile,
"window=i" => \my $window_size,
"help" => \my $help
);
usage if $help or (@ARGV == 0 and not $infile and -t STDIN);
my $in_fh = \*STDIN;
$infile = shift @ARGV if !$infile and @ARGV > 0;
open $in_fh, "<", $infile or die "$infile: $!" if $infile;
my $out_fh = \*STDOUT;
open $out_fh, ">", $outfile or die "$outfile: $!" if $outfile;
$window_size ||= 1_000_000;
die "CAUTION: window size $window_size!\n" unless $window_size > 0;
return {
in_fh => $in_fh,
out_fh => $out_fh,
window_size => $window_size
}
}
sub get_type{
my $str = shift;
die "ERROR in ID: $str\n" unless $str =~ /^[^_]+_([A-Za-z]+)/;
return $1;
}
sub load_file{
my ($in_fh, $window) = @_;
my %data;
#warn "Loading data ...\n";
my $count;
while(<$in_fh>){
$count++;
next unless /^(\S+)\s+(\S+)\s+(\d+)\s+(\d+)/;
my ($id, $chr, $start, $end) = ($1,$2,$3,$4);
my $type = get_type($id);
%{$data{$id}} = (
id => $id,
type => $type,
chr => $chr,
start=> $start,
end => $end
);
}
#warn "Done! $count lines!\n";
return \%data;
}
sub analyze_data{
my ($data, $window_size) = @_;
my %stats;
for my $id (keys %$data){
my $chr = $data->{$id}->{chr};
my $start = $data->{$id}->{start};
my $end = $data->{$id}->{end};
my $type = $data->{$id}->{type};
my $window = int(($start + $end) / 2 / $window_size) + 1;
$stats{stats}->{$chr}->{$window}->{$type}++;
$stats{type}->{$type}++;
}
$stats{window_size} = $window_size;
return \%stats;
}
sub by_number{
my $chr = shift;
die "CAUTION: Chromosome name $chr\n"
unless $chr =~ /^\S*?(\d+)$/;
return $1;
}
sub get_unit{
my $window_size = shift;
if($window_size == 1_000_000){return "Mb"}
else{return "${window_size}bp"}
}
sub print_results{
my($results, $out_fh) = @_;
my @types = sort{$a cmp $b}(keys %{$results->{type}});
my $window_size = $results->{window_size};
my $unit = get_unit($window_size);
my $title = join("\t", qq/Chr Pos($unit)/, @types)."\n";
print $out_fh $title;
for my $chr (sort {by_number($a) <=> by_number($b)} keys %{$results->{stats}}){
my $max_pos = max(keys %{$results->{stats}->{$chr}});
for my $pos (1..$max_pos){
print $out_fh join("\t", $chr, $pos,
map{$results->{stats}->{$chr}->{$pos}->{$_} // 0}
@types), "\n";
}
}
}
sub main{
my $options = get_options;
my $in_fh = $options->{in_fh};
my $out_fh = $options->{out_fh};
my $window_size = $options->{window_size};
my $data = load_file($in_fh);
my $results = analyze_data($data, $window_size);
print_results($results, $out_fh);
}
main() unless caller;
| lileiting/gfat | projects/window_stats.pl | Perl | bsd-2-clause | 3,667 |
#!/usr/bin/perl
# Copyright (c) 2016, "ma16". All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# 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.
# This project is hosted at https://github.com/ma16/rpio
# ---------------------------------------------------------------------
# An ordinary counter
#
# A text file is generated and written to stdout. This text file can be
# used as argument for the "rpio" tool in "max7219" mode.
#
# arguments:
# -- the number of 8x8 dot matrices to be used
# -- the start value
# -- the number of iterations
# -- the delay in seconds between frames
#
# e.g.: $ count.pl 1 0 10 1
#
# The numbers are written left to right, so make sure there is enough
# space (clipped otherwise).
#
# The font file "6x9-ISO8859-15.bdf" needs to be located in the same
# directory as this perl script.
#
# Note: this is just a little light demo. It's barely tested and might
# not work properly.
# ---------------------------------------------------------------------
use strict ;
use warnings ;
use File::Basename qw(dirname) ; use lib dirname($0) ;
use Canvas ;
use Font ;
use Host ;
die("arguments: <matrices> <start> <iterations> <delay>")
unless 4 == scalar(@ARGV) ;
my ($matrices,$start,$iterations,$delay) = @ARGV ;
my $host = Host->ctor(\*STDOUT,$matrices) ;
$host->comment("create counter digits for rpio's max7219 mode") ;
$host->comment("for $matrices 8x8 dot matrices start=$start iterations=$iterations delay=$delay") ;
$host->comment("see https://github.com/ma16/rpio") ;
my $intensity = 5 ;
$host->init($intensity) ;
my $font = Font->load(dirname($0)."/6x9-ISO8859-15.bdf") ;
my $canvas = Canvas->make(8*$matrices,8) ;
for my $i ($start..$start+$iterations-1) {
use integer ;
my @L ;
do {
push @L,($i%10) ;
$i /= 10 ;
}
while ($i != 0) ;
my $x0 = 0 ;
$canvas->clear() ;
for my $i (reverse(@L)) {
$x0 = $font->draw($canvas,$x0,0,ord('0')+$i) ;
}
$host->display($canvas->map(0,0,8*$matrices,8)) ;
$host->delay($delay) ;
}
| ma16/rpio | script/Max7219/count.pl | Perl | bsd-2-clause | 3,249 |
$os = lc($^O);
$isWindows = ($os =~ /win/);
#print "$isWindows\n";
clear($ARGV[0]);
sub clear {
my $file = $_[0];
if (-d $file) {
opendir(DIR, $file) || die ("could not open dir $file");
my @nextFiles = readdir(DIR);
closedir(DIR);
my $nextFile = "";
foreach $nextFile (@nextFiles) {
if ($nextFile eq "." || $nextFile eq "..") { next; }
clear("$file/$nextFile");
}
if ($file =~ /\/CVS$/) {
print "Removing ".convertFileName($file)."\n";
rmdir(convertFileName($file));
}
} else {
if ($file =~ /\/CVS\//) {
print "Removing ".convertFileName($file)."\n";
unlink(convertFileName($file));
}
}
}
sub convertFileName {
my $file = $_[0];
if ($isWindows) {
$file =~ s/\//\\/g;
}
return $file;
} | NCIP/catrip | codebase/scripts/clearcvs.pl | Perl | bsd-3-clause | 786 |
:- use_module('../metagol').
%% tell metagol to use BK
body_pred(mother/2).
body_pred(father/2).
%% metarules
metarule([P,Q],([P,A,B]:-[[Q,A,B]])).
metarule([P,Q,R],([P,A,B]:-[[Q,A,C],[R,C,B]])).
%% background knowledge
mother(ann,amy).
mother(ann,andy).
mother(amy,amelia).
mother(linda,gavin).
father(steve,amy).
father(steve,andy).
father(gavin,amelia).
father(andy,spongebob).
father(spongebob,sally).
%% learn parent, then grandparent, then great-grandparent
:-
T1 = [
parent(ann,andy),
parent(steve,andy),
parent(ann,amy),
parent(ann,andy)
]/[],
T2 = [
grandparent(steve,amelia),
grandparent(ann,amelia),
grandparent(linda,amelia),
grandparent(ann,spongebob)
]/[],
T3 = [
great_grandparent(ann,sally),
great_grandparent(steve,sally)
]/[],
learn_seq([T1,T2,T3],Prog),
pprint(Prog). | metagol/metagol | examples/sequential1.pl | Perl | bsd-3-clause | 850 |
#! /usr/bin/perl
################################################################################
## NAME: kontroll-stats-gather-5.0.x_linux-x86.pl
## VERSION: 2.0.1
## DATE: 2008-12-01
## ID: $Id$
## WEBSITE: http://kontrollsoft.com
## EMAIL: kontact@kontrollsoft.com
## LICENSE: PLEASE REFER TO THE LICENSE.txt file bundled with this software release
## to understand your right and options for using this software.
## Copyright 2008 Kontrollsoft LLC
## All rights reserved.
################################################################################
use strict;
use warnings;
use DBI;
use XML::Parser;
use XML::SimpleObject;
use Fcntl;
use POSIX qw(strftime);
use Time::HiRes qw(gettimeofday tv_interval);
my $mysql_r_user = undef;
my $mysql_r_pass = undef;
my $mysql_r_db = undef;
my $mysql_r_host = undef;
my $mysql_w_user = undef;
my $mysql_w_pass = undef;
my $mysql_w_db = undef;
my $mysql_w_host = undef;
my $error_log = undef;
my $debug_log = undef;
my $datetime = strftime "%Y-%m-%d %H:%M:%S", localtime;
my $h = undef;
## begin long list of variable definitions
my %varlist = (
'server_list_id' => '0',
'cnf_file' => '0',
'os_load_1' => '0',
'os_load_5' => '0',
'os_load_15' => '0',
'os_mem_total' => '0',
'os_mem_used' => '0',
'os_swap_total' => '0',
'os_swap_free' => '0',
'os_cpu_user' => '0',
'os_cpu_system' => '0',
'os_cpu_idle' => '0',
'queries_per_second' => '0',
'num_schema' => '0',
'num_tables' => '0',
'num_connections' => '0',
'length_data' => '0',
'length_index' => '0',
'engine_count_innodb' => '0',
'engine_count_myisam' => '0',
'engine_myisam_size_data' => '0',
'engine_myisam_size_index' => '0',
'engine_innodb_size_data' => '0',
'engine_innodb_size_index' => '0',
'auto_increment_increment' => '0',
'auto_increment_offset' => '0',
'automatic_sp_privileges' => '0',
'back_log' => '0',
'basedir' => '0',
'binlog_cache_size' => '0',
'bulk_insert_buffer_size' => '0',
'character_set_client' => '0',
'character_set_connection' => '0',
'character_set_database' => '0',
'character_set_filesystem' => '0',
'character_set_results' => '0',
'character_set_server' => '0',
'character_set_system' => '0',
'character_sets_dir' => '0',
'collation_connection' => '0',
'collation_database' => '0',
'collation_server' => '0',
'completion_type' => '0',
'concurrent_insert' => '0',
'connect_timeout' => '0',
'datadir' => '0',
'date_format' => '0',
'datetime_format' => '0',
'default_week_format' => '0',
'delay_key_write' => '0',
'delayed_insert_limit' => '0',
'delayed_insert_timeout' => '0',
'delayed_queue_size' => '0',
'div_precision_increment' => '0',
'keep_files_on_create' => '0',
'engine_condition_pushdown' => '0',
'expire_logs_days' => '0',
'flush' => '0',
'flush_time' => '0',
'ft_boolean_syntax' => '0',
'ft_max_word_len' => '0',
'ft_min_word_len' => '0',
'ft_query_expansion_limit' => '0',
'ft_stopword_file' => '0',
'group_concat_max_len' => '0',
'have_archive' => '0',
'have_bdb' => '0',
'have_blackhole_engine' => '0',
'have_compress' => '0',
'have_crypt' => '0',
'have_csv' => '0',
'have_dynamic_loading' => '0',
'have_example_engine' => '0',
'have_federated_engine' => '0',
'have_geometry' => '0',
'have_innodb' => '0',
'have_isam' => '0',
'have_merge_engine' => '0',
'have_ndbcluster' => '0',
'have_openssl' => '0',
'have_ssl' => '0',
'have_query_cache' => '0',
'have_raid' => '0',
'have_rtree_keys' => '0',
'have_symlink' => '0',
'hostname' => '0',
'init_connect' => '0',
'init_file' => '0',
'init_slave' => '0',
'innodb_additional_mem_pool_size' => '0',
'innodb_autoextend_increment' => '0',
'innodb_buffer_pool_awe_mem_mb' => '0',
'innodb_buffer_pool_size' => '0',
'innodb_checksums' => '0',
'innodb_commit_concurrency' => '0',
'innodb_concurrency_tickets' => '0',
'innodb_data_file_path' => '0',
'innodb_data_home_dir' => '0',
'innodb_adaptive_hash_index' => '0',
'innodb_doublewrite' => '0',
'innodb_fast_shutdown' => '0',
'innodb_file_io_threads' => '0',
'innodb_file_per_table' => '0',
'innodb_flush_log_at_trx_commit' => '0',
'innodb_flush_method' => '0',
'innodb_force_recovery' => '0',
'innodb_lock_wait_timeout' => '0',
'innodb_locks_unsafe_for_binlog' => '0',
'innodb_log_arch_dir' => '0',
'innodb_log_archive' => '0',
'innodb_log_buffer_size' => '0',
'innodb_log_file_size' => '0',
'innodb_log_files_in_group' => '0',
'innodb_log_group_home_dir' => '0',
'innodb_max_dirty_pages_pct' => '0',
'innodb_max_purge_lag' => '0',
'innodb_mirrored_log_groups' => '0',
'innodb_open_files' => '0',
'innodb_rollback_on_timeout' => '0',
'innodb_support_xa' => '0',
'innodb_sync_spin_loops' => '0',
'innodb_table_locks' => '0',
'innodb_thread_concurrency' => '0',
'innodb_thread_sleep_delay' => '0',
'innodb_read_ahead' => '0',
'innodb_ibuf_contract_const' => '0',
'innodb_ibuf_contract_burst' => '0',
'innodb_buf_flush_const' => '0',
'innodb_buf_flush_burst' => '0',
'interactive_timeout' => '0',
'join_buffer_size' => '0',
'key_buffer_size' => '0',
'key_cache_age_threshold' => '0',
'key_cache_block_size' => '0',
'key_cache_division_limit' => '0',
'language' => '0',
'large_files_support' => '0',
'large_page_size' => '0',
'large_pages' => '0',
'lc_time_names' => '0',
'license' => '0',
'local_infile' => '0',
'locked_in_memory' => '0',
'log' => '0',
'log_bin' => '0',
'log_bin_trust_function_creators' => '0',
'log_error' => '0',
'log_queries_not_using_indexes' => '0',
'log_slave_updates' => '0',
'log_slow_queries' => '0',
'log_slow_filter' => '0',
'log_slow_verbosity' => '0',
'log_warnings' => '0',
'long_query_time' => '0',
'low_priority_updates' => '0',
'lower_case_file_system' => '0',
'lower_case_table_names' => '0',
'max_allowed_packet' => '0',
'max_binlog_cache_size' => '0',
'max_binlog_size' => '0',
'max_connect_errors' => '0',
'max_connections' => '0',
'max_delayed_threads' => '0',
'max_error_count' => '0',
'max_heap_table_size' => '0',
'max_insert_delayed_threads' => '0',
'max_join_size' => '0',
'max_length_for_sort_data' => '0',
'max_prepared_stmt_count' => '0',
'max_relay_log_size' => '0',
'max_seeks_for_key' => '0',
'max_sort_length' => '0',
'max_sp_recursion_depth' => '0',
'max_tmp_tables' => '0',
'max_user_connections' => '0',
'max_write_lock_count' => '0',
'min_examined_row_limit' => '0',
'multi_range_count' => '0',
'myisam_data_pointer_size' => '0',
'myisam_max_sort_file_size' => '0',
'myisam_recover_options' => '0',
'myisam_repair_threads' => '0',
'myisam_sort_buffer_size' => '0',
'myisam_stats_method' => '0',
'net_buffer_length' => '0',
'net_read_timeout' => '0',
'net_retry_count' => '0',
'net_write_timeout' => '0',
'new' => '0',
'old_passwords' => '0',
'open_files_limit' => '0',
'optimizer_prune_level' => '0',
'optimizer_search_depth' => '0',
'pid_file' => '0',
'port' => '0',
'preload_buffer_size' => '0',
'protocol_version' => '0',
'query_alloc_block_size' => '0',
'query_cache_limit' => '0',
'query_cache_min_res_unit' => '0',
'query_cache_size' => '0',
'query_cache_type' => '0',
'query_cache_wlock_invalidate' => '0',
'query_prealloc_size' => '0',
'range_alloc_block_size' => '0',
'log_slow_rate_limit' => '0',
'read_buffer_size' => '0',
'read_only' => '0',
'read_rnd_buffer_size' => '0',
'relay_log' => '0',
'relay_log_index' => '0',
'relay_log_info_file' => '0',
'relay_log_purge' => '0',
'relay_log_space_limit' => '0',
'rpl_recovery_rank' => '0',
'secure_auth' => '0',
'secure_file_priv' => '0',
'server_id' => '0',
'skip_external_locking' => '0',
'skip_networking' => '0',
'skip_show_database' => '0',
'slave_compressed_protocol' => '0',
'slave_load_tmpdir' => '0',
'slave_net_timeout' => '0',
'slave_skip_errors' => '0',
'slave_transaction_retries' => '0',
'slow_launch_time' => '0',
'socket' => '0',
'sort_buffer_size' => '0',
'sql_big_selects' => '0',
'sql_mode' => '0',
'sql_notes' => '0',
'sql_warnings' => '0',
'ssl_ca' => '0',
'ssl_capath' => '0',
'ssl_cert' => '0',
'ssl_cipher' => '0',
'ssl_key' => '0',
'storage_engine' => '0',
'sync_binlog' => '0',
'sync_frm' => '0',
'system_time_zone' => '0',
'table_cache' => '0',
'table_lock_wait_timeout' => '0',
'table_type' => '0',
'thread_cache_size' => '0',
'thread_stack' => '0',
'time_format' => '0',
'time_zone' => '0',
'timed_mutexes' => '0',
'tmp_table_size' => '0',
'tmpdir' => '0',
'transaction_alloc_block_size' => '0',
'transaction_prealloc_size' => '0',
'tx_isolation' => '0',
'updatable_views_with_limit' => '0',
'version' => '0',
'version_comment' => '0',
'version_compile_machine' => '0',
'version_compile_os' => '0',
'wait_timeout' => '0',
'Aborted_clients' => '0',
'Aborted_connects' => '0',
'Binlog_cache_disk_use' => '0',
'Binlog_cache_use' => '0',
'Bytes_received' => '0',
'Bytes_sent' => '0',
'Com_admin_commands' => '0',
'Com_alter_db' => '0',
'Com_alter_table' => '0',
'Com_analyze' => '0',
'Com_backup_table' => '0',
'Com_begin' => '0',
'Com_call_procedure' => '0',
'Com_change_db' => '0',
'Com_change_master' => '0',
'Com_check' => '0',
'Com_checksum' => '0',
'Com_commit' => '0',
'Com_create_db' => '0',
'Com_create_function' => '0',
'Com_create_index' => '0',
'Com_create_table' => '0',
'Com_create_user' => '0',
'Com_dealloc_sql' => '0',
'Com_delete' => '0',
'Com_delete_multi' => '0',
'Com_do' => '0',
'Com_drop_db' => '0',
'Com_drop_function' => '0',
'Com_drop_index' => '0',
'Com_drop_table' => '0',
'Com_drop_user' => '0',
'Com_execute_sql' => '0',
'Com_flush' => '0',
'Com_grant' => '0',
'Com_ha_close' => '0',
'Com_ha_open' => '0',
'Com_ha_read' => '0',
'Com_help' => '0',
'Com_insert' => '0',
'Com_insert_select' => '0',
'Com_kill' => '0',
'Com_load' => '0',
'Com_load_master_data' => '0',
'Com_load_master_table' => '0',
'Com_lock_tables' => '0',
'Com_optimize' => '0',
'Com_preload_keys' => '0',
'Com_prepare_sql' => '0',
'Com_purge' => '0',
'Com_purge_before_date' => '0',
'Com_rename_table' => '0',
'Com_repair' => '0',
'Com_replace' => '0',
'Com_replace_select' => '0',
'Com_reset' => '0',
'Com_restore_table' => '0',
'Com_revoke' => '0',
'Com_revoke_all' => '0',
'Com_rollback' => '0',
'Com_savepoint' => '0',
'Com_select' => '0',
'Com_set_option' => '0',
'Com_show_binlog_events' => '0',
'Com_show_binlogs' => '0',
'Com_show_charsets' => '0',
'Com_show_collations' => '0',
'Com_show_column_types' => '0',
'Com_show_create_db' => '0',
'Com_show_create_table' => '0',
'Com_show_databases' => '0',
'Com_show_errors' => '0',
'Com_show_fields' => '0',
'Com_show_grants' => '0',
'Com_show_innodb_status' => '0',
'Com_show_keys' => '0',
'Com_show_logs' => '0',
'Com_show_master_status' => '0',
'Com_show_ndb_status' => '0',
'Com_show_new_master' => '0',
'Com_show_open_tables' => '0',
'Com_show_privileges' => '0',
'Com_show_processlist' => '0',
'Com_show_slave_hosts' => '0',
'Com_show_slave_status' => '0',
'Com_show_status' => '0',
'Com_show_storage_engines' => '0',
'Com_show_tables' => '0',
'Com_show_triggers' => '0',
'Com_show_variables' => '0',
'Com_show_warnings' => '0',
'Com_slave_start' => '0',
'Com_slave_stop' => '0',
'Com_stmt_close' => '0',
'Com_stmt_execute' => '0',
'Com_stmt_fetch' => '0',
'Com_stmt_prepare' => '0',
'Com_stmt_reset' => '0',
'Com_stmt_send_long_data' => '0',
'Com_truncate' => '0',
'Com_unlock_tables' => '0',
'Com_update' => '0',
'Com_update_multi' => '0',
'Com_xa_commit' => '0',
'Com_xa_end' => '0',
'Com_xa_prepare' => '0',
'Com_xa_recover' => '0',
'Com_xa_rollback' => '0',
'Com_xa_start' => '0',
'Compression' => '0',
'Connections' => '0',
'Created_tmp_disk_tables' => '0',
'Created_tmp_files' => '0',
'Created_tmp_tables' => '0',
'Delayed_errors' => '0',
'Delayed_insert_threads' => '0',
'Delayed_writes' => '0',
'Flush_commands' => '0',
'Handler_commit' => '0',
'Handler_delete' => '0',
'Handler_discover' => '0',
'Handler_prepare' => '0',
'Handler_read_first' => '0',
'Handler_read_key' => '0',
'Handler_read_next' => '0',
'Handler_read_prev' => '0',
'Handler_read_rnd' => '0',
'Handler_read_rnd_next' => '0',
'Handler_rollback' => '0',
'Handler_savepoint' => '0',
'Handler_savepoint_rollback' => '0',
'Handler_update' => '0',
'Handler_write' => '0',
'Innodb_buffer_pool_pages_data' => '0',
'Innodb_buffer_pool_pages_dirty' => '0',
'Innodb_buffer_pool_pages_flushed' => '0',
'Innodb_buffer_pool_pages_free' => '0',
'Innodb_buffer_pool_pages_misc' => '0',
'Innodb_buffer_pool_pages_total' => '0',
'Innodb_buffer_pool_read_ahead_rnd' => '0',
'Innodb_buffer_pool_read_ahead_seq' => '0',
'Innodb_buffer_pool_read_requests' => '0',
'Innodb_buffer_pool_reads' => '0',
'Innodb_buffer_pool_wait_free' => '0',
'Innodb_buffer_pool_write_requests' => '0',
'Innodb_data_fsyncs' => '0',
'Innodb_data_pending_fsyncs' => '0',
'Innodb_data_pending_reads' => '0',
'Innodb_data_pending_writes' => '0',
'Innodb_data_read' => '0',
'Innodb_data_reads' => '0',
'Innodb_data_writes' => '0',
'Innodb_data_written' => '0',
'Innodb_dblwr_pages_written' => '0',
'Innodb_dblwr_writes' => '0',
'Innodb_log_waits' => '0',
'Innodb_log_write_requests' => '0',
'Innodb_log_writes' => '0',
'Innodb_os_log_fsyncs' => '0',
'Innodb_os_log_pending_fsyncs' => '0',
'Innodb_os_log_pending_writes' => '0',
'Innodb_os_log_written' => '0',
'Innodb_page_size' => '0',
'Innodb_pages_created' => '0',
'Innodb_pages_read' => '0',
'Innodb_pages_written' => '0',
'Innodb_row_lock_current_waits' => '0',
'Innodb_row_lock_time' => '0',
'Innodb_row_lock_time_avg' => '0',
'Innodb_row_lock_time_max' => '0',
'Innodb_row_lock_waits' => '0',
'Innodb_rows_deleted' => '0',
'Innodb_rows_inserted' => '0',
'Innodb_rows_read' => '0',
'Innodb_rows_updated' => '0',
'Key_blocks_not_flushed' => '0',
'Key_blocks_unused' => '0',
'Key_blocks_used' => '0',
'Key_read_requests' => '0',
'Key_reads' => '0',
'Key_write_requests' => '0',
'Key_writes' => '0',
'Last_query_cost' => '0',
'Max_used_connections' => '0',
'Not_flushed_delayed_rows' => '0',
'Open_files' => '0',
'Open_streams' => '0',
'Open_tables' => '0',
'Opened_tables' => '0',
'Prepared_stmt_count' => '0',
'Qcache_free_blocks' => '0',
'Qcache_free_memory' => '0',
'Qcache_hits' => '0',
'Qcache_inserts' => '0',
'Qcache_lowmem_prunes' => '0',
'Qcache_not_cached' => '0',
'Qcache_queries_in_cache' => '0',
'Qcache_total_blocks' => '0',
'Questions' => '0',
'Rpl_status' => '0',
'Select_full_join' => '0',
'Select_full_range_join' => '0',
'Select_range' => '0',
'Select_range_check' => '0',
'Select_scan' => '0',
'Slave_open_temp_tables' => '0',
'Slave_retried_transactions' => '0',
'Slave_running' => '0',
'Slow_launch_threads' => '0',
'Slow_queries' => '0',
'Sort_merge_passes' => '0',
'Sort_range' => '0',
'Sort_rows' => '0',
'Sort_scan' => '0',
'Table_locks_immediate' => '0',
'Table_locks_waited' => '0',
'Tc_log_max_pages_used' => '0',
'Tc_log_page_size' => '0',
'Tc_log_page_waits' => '0',
'Threads_cached' => '0',
'Threads_connected' => '0',
'Threads_created' => '0',
'Threads_running' => '0',
'Uptime' => '0',
'server_snmp_error_code' => '0',
'server_mysql_error_code' => '0',
'Slave_SQL_Running' => '0',
'Slave_IO_Running' => '0',
'Seconds_Behind_Master' => '0',
'illegal_global_user' => '0',
'illegal_grant_user' => '0',
'illegal_remote_root' => '0',
'illegal_user_nopass' => '0',
'illegal_user_noname' => '0',
'collection_time_elapse' => '0');
sub config_connect {
my $cfgapp = "../system/application/config/bin-read-configs.php";
$mysql_r_user = `php $cfgapp read username`;
$mysql_r_pass = `php $cfgapp read password`;
$mysql_r_db = `php $cfgapp read database`;
$mysql_r_host = `php $cfgapp read hostname`;
$mysql_w_user = `php $cfgapp write username`;
$mysql_w_pass = `php $cfgapp write password`;
$mysql_w_db = `php $cfgapp write database`;
$mysql_w_host = `php $cfgapp write hostname`;
$error_log = "../system/logs/sys_error.log";
$debug_log = "../system/logs/sys_debug.log";
}
sub insert_data {
my $sql0 = "INSERT INTO `server_statistics` (
`id`,
`server_list_id`,
`cnf_file`,
`os_load_1`,
`os_load_5`,
`os_load_15`,
`os_mem_total`,
`os_mem_used`,
`os_swap_total`,
`os_swap_free`,
`os_cpu_user`,
`os_cpu_system`,
`os_cpu_idle`,
`queries_per_second`,
`num_schema`,
`num_tables`,
`num_connections`,
`length_data`,
`length_index`,
`engine_count_innodb`,
`engine_count_myisam`,
`engine_myisam_size_data`,
`engine_myisam_size_index`,
`engine_innodb_size_data`,
`engine_innodb_size_index`,
`auto_increment_increment`,
`auto_increment_offset`,
`automatic_sp_privileges`,
`back_log`,
`basedir`,
`binlog_cache_size`,
`bulk_insert_buffer_size`,
`character_set_client`,
`character_set_connection`,
`character_set_database`,
`character_set_filesystem`,
`character_set_results`,
`character_set_server`,
`character_set_system`,
`character_sets_dir`,
`collation_connection`,
`collation_database`,
`collation_server`,
`completion_type`,
`concurrent_insert`,
`connect_timeout`,
`datadir`,
`date_format`,
`datetime_format`,
`default_week_format`,
`delay_key_write`,
`delayed_insert_limit`,
`delayed_insert_timeout`,
`delayed_queue_size`,
`div_precision_increment`,
`keep_files_on_create`,
`engine_condition_pushdown`,
`expire_logs_days`,
`flush`,
`flush_time`,
`ft_boolean_syntax`,
`ft_max_word_len`,
`ft_min_word_len`,
`ft_query_expansion_limit`,
`ft_stopword_file`,
`group_concat_max_len`,
`have_archive`,
`have_bdb`,
`have_blackhole_engine`,
`have_compress`,
`have_crypt`,
`have_csv`,
`have_dynamic_loading`,
`have_example_engine`,
`have_federated_engine`,
`have_geometry`,
`have_innodb`,
`have_isam`,
`have_merge_engine`,
`have_ndbcluster`,
`have_openssl`,
`have_ssl`,
`have_query_cache`,
`have_raid`,
`have_rtree_keys`,
`have_symlink`,
`hostname`,
`init_connect`,
`init_file`,
`init_slave`,
`innodb_additional_mem_pool_size`,
`innodb_autoextend_increment`,
`innodb_buffer_pool_awe_mem_mb`,
`innodb_buffer_pool_size`,
`innodb_checksums`,
`innodb_commit_concurrency`,
`innodb_concurrency_tickets`,
`innodb_data_file_path`,
`innodb_data_home_dir`,
`innodb_adaptive_hash_index`,
`innodb_doublewrite`,
`innodb_fast_shutdown`,
`innodb_file_io_threads`,
`innodb_file_per_table`,
`innodb_flush_log_at_trx_commit`,
`innodb_flush_method`,
`innodb_force_recovery`,
`innodb_lock_wait_timeout`,
`innodb_locks_unsafe_for_binlog`,
`innodb_log_arch_dir`,
`innodb_log_archive`,
`innodb_log_buffer_size`,
`innodb_log_file_size`,
`innodb_log_files_in_group`,
`innodb_log_group_home_dir`,
`innodb_max_dirty_pages_pct`,
`innodb_max_purge_lag`,
`innodb_mirrored_log_groups`,
`innodb_open_files`,
`innodb_rollback_on_timeout`,
`innodb_support_xa`,
`innodb_sync_spin_loops`,
`innodb_table_locks`,
`innodb_thread_concurrency`,
`innodb_thread_sleep_delay`,
`innodb_read_ahead`,
`innodb_ibuf_contract_const`,
`innodb_ibuf_contract_burst`,
`innodb_buf_flush_const`,
`innodb_buf_flush_burst`,
`interactive_timeout`,
`join_buffer_size`,
`key_buffer_size`,
`key_cache_age_threshold`,
`key_cache_block_size`,
`key_cache_division_limit`,
`language`,
`large_files_support`,
`large_page_size`,
`large_pages`,
`lc_time_names`,
`license`,
`local_infile`,
`locked_in_memory`,
`log`,
`log_bin`,
`log_bin_trust_function_creators`,
`log_error`,
`log_queries_not_using_indexes`,
`log_slave_updates`,
`log_slow_queries`,
`log_slow_filter`,
`log_slow_verbosity`,
`log_warnings`,
`long_query_time`,
`low_priority_updates`,
`lower_case_file_system`,
`lower_case_table_names`,
`max_allowed_packet`,
`max_binlog_cache_size`,
`max_binlog_size`,
`max_connect_errors`,
`max_connections`,
`max_delayed_threads`,
`max_error_count`,
`max_heap_table_size`,
`max_insert_delayed_threads`,
`max_join_size`,
`max_length_for_sort_data`,
`max_prepared_stmt_count`,
`max_relay_log_size`,
`max_seeks_for_key`,
`max_sort_length`,
`max_sp_recursion_depth`,
`max_tmp_tables`,
`max_user_connections`,
`max_write_lock_count`,
`min_examined_row_limit`,
`multi_range_count`,
`myisam_data_pointer_size`,
`myisam_max_sort_file_size`,
`myisam_recover_options`,
`myisam_repair_threads`,
`myisam_sort_buffer_size`,
`myisam_stats_method`,
`net_buffer_length`,
`net_read_timeout`,
`net_retry_count`,
`net_write_timeout`,
`new`,
`old_passwords`,
`open_files_limit`,
`optimizer_prune_level`,
`optimizer_search_depth`,
`pid_file`,
`port`,
`preload_buffer_size`,
`protocol_version`,
`query_alloc_block_size`,
`query_cache_limit`,
`query_cache_min_res_unit`,
`query_cache_size`,
`query_cache_type`,
`query_cache_wlock_invalidate`,
`query_prealloc_size`,
`range_alloc_block_size`,
`log_slow_rate_limit`,
`read_buffer_size`,
`read_only`,
`read_rnd_buffer_size`,
`relay_log`,
`relay_log_index`,
`relay_log_info_file`,
`relay_log_purge`,
`relay_log_space_limit`,
`rpl_recovery_rank`,
`secure_auth`,
`secure_file_priv`,
`server_id`,
`skip_external_locking`,
`skip_networking`,
`skip_show_database`,
`slave_compressed_protocol`,
`slave_load_tmpdir`,
`slave_net_timeout`,
`slave_skip_errors`,
`slave_transaction_retries`,
`slow_launch_time`,
`socket`,
`sort_buffer_size`,
`sql_big_selects`,
`sql_mode`,
`sql_notes`,
`sql_warnings`,
`ssl_ca`,
`ssl_capath`,
`ssl_cert`,
`ssl_cipher`,
`ssl_key`,
`storage_engine`,
`sync_binlog`,
`sync_frm`,
`system_time_zone`,
`table_cache`,
`table_lock_wait_timeout`,
`table_type`,
`thread_cache_size`,
`thread_stack`,
`time_format`,
`time_zone`,
`timed_mutexes`,
`tmp_table_size`,
`tmpdir`,
`transaction_alloc_block_size`,
`transaction_prealloc_size`,
`tx_isolation`,
`updatable_views_with_limit`,
`version`,
`version_comment`,
`version_compile_machine`,
`version_compile_os`,
`wait_timeout`,
`Aborted_clients`,
`Aborted_connects`,
`Binlog_cache_disk_use`,
`Binlog_cache_use`,
`Bytes_received`,
`Bytes_sent`,
`Com_admin_commands`,
`Com_alter_db`,
`Com_alter_table`,
`Com_analyze`,
`Com_backup_table`,
`Com_begin`,
`Com_call_procedure`,
`Com_change_db`,
`Com_change_master`,
`Com_check`,
`Com_checksum`,
`Com_commit`,
`Com_create_db`,
`Com_create_function`,
`Com_create_index`,
`Com_create_table`,
`Com_create_user`,
`Com_dealloc_sql`,
`Com_delete`,
`Com_delete_multi`,
`Com_do`,
`Com_drop_db`,
`Com_drop_function`,
`Com_drop_index`,
`Com_drop_table`,
`Com_drop_user`,
`Com_execute_sql`,
`Com_flush`,
`Com_grant`,
`Com_ha_close`,
`Com_ha_open`,
`Com_ha_read`,
`Com_help`,
`Com_insert`,
`Com_insert_select`,
`Com_kill`,
`Com_load`,
`Com_load_master_data`,
`Com_load_master_table`,
`Com_lock_tables`,
`Com_optimize`,
`Com_preload_keys`,
`Com_prepare_sql`,
`Com_purge`,
`Com_purge_before_date`,
`Com_rename_table`,
`Com_repair`,
`Com_replace`,
`Com_replace_select`,
`Com_reset`,
`Com_restore_table`,
`Com_revoke`,
`Com_revoke_all`,
`Com_rollback`,
`Com_savepoint`,
`Com_select`,
`Com_set_option`,
`Com_show_binlog_events`,
`Com_show_binlogs`,
`Com_show_charsets`,
`Com_show_collations`,
`Com_show_column_types`,
`Com_show_create_db`,
`Com_show_create_table`,
`Com_show_databases`,
`Com_show_errors`,
`Com_show_fields`,
`Com_show_grants`,
`Com_show_innodb_status`,
`Com_show_keys`,
`Com_show_logs`,
`Com_show_master_status`,
`Com_show_ndb_status`,
`Com_show_new_master`,
`Com_show_open_tables`,
`Com_show_privileges`,
`Com_show_processlist`,
`Com_show_slave_hosts`,
`Com_show_slave_status`,
`Com_show_status`,
`Com_show_storage_engines`,
`Com_show_tables`,
`Com_show_triggers`,
`Com_show_variables`,
`Com_show_warnings`,
`Com_slave_start`,
`Com_slave_stop`,
`Com_stmt_close`,
`Com_stmt_execute`,
`Com_stmt_fetch`,
`Com_stmt_prepare`,
`Com_stmt_reset`,
`Com_stmt_send_long_data`,
`Com_truncate`,
`Com_unlock_tables`,
`Com_update`,
`Com_update_multi`,
`Com_xa_commit`,
`Com_xa_end`,
`Com_xa_prepare`,
`Com_xa_recover`,
`Com_xa_rollback`,
`Com_xa_start`,
`Compression`,
`Connections`,
`Created_tmp_disk_tables`,
`Created_tmp_files`,
`Created_tmp_tables`,
`Delayed_errors`,
`Delayed_insert_threads`,
`Delayed_writes`,
`Flush_commands`,
`Handler_commit`,
`Handler_delete`,
`Handler_discover`,
`Handler_prepare`,
`Handler_read_first`,
`Handler_read_key`,
`Handler_read_next`,
`Handler_read_prev`,
`Handler_read_rnd`,
`Handler_read_rnd_next`,
`Handler_rollback`,
`Handler_savepoint`,
`Handler_savepoint_rollback`,
`Handler_update`,
`Handler_write`,
`Innodb_buffer_pool_pages_data`,
`Innodb_buffer_pool_pages_dirty`,
`Innodb_buffer_pool_pages_flushed`,
`Innodb_buffer_pool_pages_free`,
`Innodb_buffer_pool_pages_misc`,
`Innodb_buffer_pool_pages_total`,
`Innodb_buffer_pool_read_ahead_rnd`,
`Innodb_buffer_pool_read_ahead_seq`,
`Innodb_buffer_pool_read_requests`,
`Innodb_buffer_pool_reads`,
`Innodb_buffer_pool_wait_free`,
`Innodb_buffer_pool_write_requests`,
`Innodb_data_fsyncs`,
`Innodb_data_pending_fsyncs`,
`Innodb_data_pending_reads`,
`Innodb_data_pending_writes`,
`Innodb_data_read`,
`Innodb_data_reads`,
`Innodb_data_writes`,
`Innodb_data_written`,
`Innodb_dblwr_pages_written`,
`Innodb_dblwr_writes`,
`Innodb_log_waits`,
`Innodb_log_write_requests`,
`Innodb_log_writes`,
`Innodb_os_log_fsyncs`,
`Innodb_os_log_pending_fsyncs`,
`Innodb_os_log_pending_writes`,
`Innodb_os_log_written`,
`Innodb_page_size`,
`Innodb_pages_created`,
`Innodb_pages_read`,
`Innodb_pages_written`,
`Innodb_row_lock_current_waits`,
`Innodb_row_lock_time`,
`Innodb_row_lock_time_avg`,
`Innodb_row_lock_time_max`,
`Innodb_row_lock_waits`,
`Innodb_rows_deleted`,
`Innodb_rows_inserted`,
`Innodb_rows_read`,
`Innodb_rows_updated`,
`Key_blocks_not_flushed`,
`Key_blocks_unused`,
`Key_blocks_used`,
`Key_read_requests`,
`Key_reads`,
`Key_write_requests`,
`Key_writes`,
`Last_query_cost`,
`Max_used_connections`,
`Not_flushed_delayed_rows`,
`Open_files`,
`Open_streams`,
`Open_tables`,
`Opened_tables`,
`Prepared_stmt_count`,
`Qcache_free_blocks`,
`Qcache_free_memory`,
`Qcache_hits`,
`Qcache_inserts`,
`Qcache_lowmem_prunes`,
`Qcache_not_cached`,
`Qcache_queries_in_cache`,
`Qcache_total_blocks`,
`Questions`,
`Rpl_status`,
`Select_full_join`,
`Select_full_range_join`,
`Select_range`,
`Select_range_check`,
`Select_scan`,
`Slave_open_temp_tables`,
`Slave_retried_transactions`,
`Slave_running`,
`Slow_launch_threads`,
`Slow_queries`,
`Sort_merge_passes`,
`Sort_range`,
`Sort_rows`,
`Sort_scan`,
`Table_locks_immediate`,
`Table_locks_waited`,
`Tc_log_max_pages_used`,
`Tc_log_page_size`,
`Tc_log_page_waits`,
`Threads_cached`,
`Threads_connected`,
`Threads_created`,
`Threads_running`,
`Uptime`,
`server_snmp_error_code`,
`server_mysql_error_code`,
`Slave_SQL_Running`,
`Slave_IO_Running`,
`Seconds_Behind_Master`,
`illegal_global_user`,
`illegal_grant_user`,
`illegal_remote_root`,
`illegal_user_nopass`,
`illegal_user_noname`,
`collection_time_elapse`,
`Creation_time`)
VALUES (
NULL,
$varlist{'server_list_id'},
$varlist{'cnf_file'},
$varlist{'os_load_1'},
$varlist{'os_load_5'},
$varlist{'os_load_15'},
$varlist{'os_mem_total'},
$varlist{'os_mem_used'},
$varlist{'os_swap_total'},
$varlist{'os_swap_free'},
$varlist{'os_cpu_user'},
$varlist{'os_cpu_system'},
$varlist{'os_cpu_idle'},
$varlist{'queries_per_second'},
$varlist{'num_schema'},
$varlist{'num_tables'},
$varlist{'num_connections'},
$varlist{'length_data'},
$varlist{'length_index'},
$varlist{'engine_count_innodb'},
$varlist{'engine_count_myisam'},
$varlist{'engine_myisam_size_data'},
$varlist{'engine_myisam_size_index'},
$varlist{'engine_innodb_size_data'},
$varlist{'engine_innodb_size_index'},
$varlist{'auto_increment_increment'},
$varlist{'auto_increment_offset'},
$varlist{'automatic_sp_privileges'},
$varlist{'back_log'},
$varlist{'basedir'},
$varlist{'binlog_cache_size'},
$varlist{'bulk_insert_buffer_size'},
$varlist{'character_set_client'},
$varlist{'character_set_connection'},
$varlist{'character_set_database'},
$varlist{'character_set_filesystem'},
$varlist{'character_set_results'},
$varlist{'character_set_server'},
$varlist{'character_set_system'},
$varlist{'character_sets_dir'},
$varlist{'collation_connection'},
$varlist{'collation_database'},
$varlist{'collation_server'},
$varlist{'completion_type'},
$varlist{'concurrent_insert'},
$varlist{'connect_timeout'},
$varlist{'datadir'},
$varlist{'date_format'},
$varlist{'datetime_format'},
$varlist{'default_week_format'},
$varlist{'delay_key_write'},
$varlist{'delayed_insert_limit'},
$varlist{'delayed_insert_timeout'},
$varlist{'delayed_queue_size'},
$varlist{'div_precision_increment'},
$varlist{'keep_files_on_create'},
$varlist{'engine_condition_pushdown'},
$varlist{'expire_logs_days'},
$varlist{'flush'},
$varlist{'flush_time'},
$varlist{'ft_boolean_syntax'},
$varlist{'ft_max_word_len'},
$varlist{'ft_min_word_len'},
$varlist{'ft_query_expansion_limit'},
$varlist{'ft_stopword_file'},
$varlist{'group_concat_max_len'},
$varlist{'have_archive'},
$varlist{'have_bdb'},
$varlist{'have_blackhole_engine'},
$varlist{'have_compress'},
$varlist{'have_crypt'},
$varlist{'have_csv'},
$varlist{'have_dynamic_loading'},
$varlist{'have_example_engine'},
$varlist{'have_federated_engine'},
$varlist{'have_geometry'},
$varlist{'have_innodb'},
$varlist{'have_isam'},
$varlist{'have_merge_engine'},
$varlist{'have_ndbcluster'},
$varlist{'have_openssl'},
$varlist{'have_ssl'},
$varlist{'have_query_cache'},
$varlist{'have_raid'},
$varlist{'have_rtree_keys'},
$varlist{'have_symlink'},
$varlist{'hostname'},
$varlist{'init_connect'},
$varlist{'init_file'},
$varlist{'init_slave'},
$varlist{'innodb_additional_mem_pool_size'},
$varlist{'innodb_autoextend_increment'},
$varlist{'innodb_buffer_pool_awe_mem_mb'},
$varlist{'innodb_buffer_pool_size'},
$varlist{'innodb_checksums'},
$varlist{'innodb_commit_concurrency'},
$varlist{'innodb_concurrency_tickets'},
$varlist{'innodb_data_file_path'},
$varlist{'innodb_data_home_dir'},
$varlist{'innodb_adaptive_hash_index'},
$varlist{'innodb_doublewrite'},
$varlist{'innodb_fast_shutdown'},
$varlist{'innodb_file_io_threads'},
$varlist{'innodb_file_per_table'},
$varlist{'innodb_flush_log_at_trx_commit'},
$varlist{'innodb_flush_method'},
$varlist{'innodb_force_recovery'},
$varlist{'innodb_lock_wait_timeout'},
$varlist{'innodb_locks_unsafe_for_binlog'},
$varlist{'innodb_log_arch_dir'},
$varlist{'innodb_log_archive'},
$varlist{'innodb_log_buffer_size'},
$varlist{'innodb_log_file_size'},
$varlist{'innodb_log_files_in_group'},
$varlist{'innodb_log_group_home_dir'},
$varlist{'innodb_max_dirty_pages_pct'},
$varlist{'innodb_max_purge_lag'},
$varlist{'innodb_mirrored_log_groups'},
$varlist{'innodb_open_files'},
$varlist{'innodb_rollback_on_timeout'},
$varlist{'innodb_support_xa'},
$varlist{'innodb_sync_spin_loops'},
$varlist{'innodb_table_locks'},
$varlist{'innodb_thread_concurrency'},
$varlist{'innodb_thread_sleep_delay'},
$varlist{'innodb_read_ahead'},
$varlist{'innodb_ibuf_contract_const'},
$varlist{'innodb_ibuf_contract_burst'},
$varlist{'innodb_buf_flush_const'},
$varlist{'innodb_buf_flush_burst'},
$varlist{'interactive_timeout'},
$varlist{'join_buffer_size'},
$varlist{'key_buffer_size'},
$varlist{'key_cache_age_threshold'},
$varlist{'key_cache_block_size'},
$varlist{'key_cache_division_limit'},
$varlist{'language'},
$varlist{'large_files_support'},
$varlist{'large_page_size'},
$varlist{'large_pages'},
$varlist{'lc_time_names'},
$varlist{'license'},
$varlist{'local_infile'},
$varlist{'locked_in_memory'},
$varlist{'log'},
$varlist{'log_bin'},
$varlist{'log_bin_trust_function_creators'},
$varlist{'log_error'},
$varlist{'log_queries_not_using_indexes'},
$varlist{'log_slave_updates'},
$varlist{'log_slow_queries'},
$varlist{'log_slow_filter'},
$varlist{'log_slow_verbosity'},
$varlist{'log_warnings'},
$varlist{'long_query_time'},
$varlist{'low_priority_updates'},
$varlist{'lower_case_file_system'},
$varlist{'lower_case_table_names'},
$varlist{'max_allowed_packet'},
$varlist{'max_binlog_cache_size'},
$varlist{'max_binlog_size'},
$varlist{'max_connect_errors'},
$varlist{'max_connections'},
$varlist{'max_delayed_threads'},
$varlist{'max_error_count'},
$varlist{'max_heap_table_size'},
$varlist{'max_insert_delayed_threads'},
$varlist{'max_join_size'},
$varlist{'max_length_for_sort_data'},
$varlist{'max_prepared_stmt_count'},
$varlist{'max_relay_log_size'},
$varlist{'max_seeks_for_key'},
$varlist{'max_sort_length'},
$varlist{'max_sp_recursion_depth'},
$varlist{'max_tmp_tables'},
$varlist{'max_user_connections'},
$varlist{'max_write_lock_count'},
$varlist{'min_examined_row_limit'},
$varlist{'multi_range_count'},
$varlist{'myisam_data_pointer_size'},
$varlist{'myisam_max_sort_file_size'},
$varlist{'myisam_recover_options'},
$varlist{'myisam_repair_threads'},
$varlist{'myisam_sort_buffer_size'},
$varlist{'myisam_stats_method'},
$varlist{'net_buffer_length'},
$varlist{'net_read_timeout'},
$varlist{'net_retry_count'},
$varlist{'net_write_timeout'},
$varlist{'new'},
$varlist{'old_passwords'},
$varlist{'open_files_limit'},
$varlist{'optimizer_prune_level'},
$varlist{'optimizer_search_depth'},
$varlist{'pid_file'},
$varlist{'port'},
$varlist{'preload_buffer_size'},
$varlist{'protocol_version'},
$varlist{'query_alloc_block_size'},
$varlist{'query_cache_limit'},
$varlist{'query_cache_min_res_unit'},
$varlist{'query_cache_size'},
$varlist{'query_cache_type'},
$varlist{'query_cache_wlock_invalidate'},
$varlist{'query_prealloc_size'},
$varlist{'range_alloc_block_size'},
$varlist{'log_slow_rate_limit'},
$varlist{'read_buffer_size'},
$varlist{'read_only'},
$varlist{'read_rnd_buffer_size'},
$varlist{'relay_log'},
$varlist{'relay_log_index'},
$varlist{'relay_log_info_file'},
$varlist{'relay_log_purge'},
$varlist{'relay_log_space_limit'},
$varlist{'rpl_recovery_rank'},
$varlist{'secure_auth'},
$varlist{'secure_file_priv'},
$varlist{'server_id'},
$varlist{'skip_external_locking'},
$varlist{'skip_networking'},
$varlist{'skip_show_database'},
$varlist{'slave_compressed_protocol'},
$varlist{'slave_load_tmpdir'},
$varlist{'slave_net_timeout'},
$varlist{'slave_skip_errors'},
$varlist{'slave_transaction_retries'},
$varlist{'slow_launch_time'},
$varlist{'socket'},
$varlist{'sort_buffer_size'},
$varlist{'sql_big_selects'},
$varlist{'sql_mode'},
$varlist{'sql_notes'},
$varlist{'sql_warnings'},
$varlist{'ssl_ca'},
$varlist{'ssl_capath'},
$varlist{'ssl_cert'},
$varlist{'ssl_cipher'},
$varlist{'ssl_key'},
$varlist{'storage_engine'},
$varlist{'sync_binlog'},
$varlist{'sync_frm'},
$varlist{'system_time_zone'},
$varlist{'table_cache'},
$varlist{'table_lock_wait_timeout'},
$varlist{'table_type'},
$varlist{'thread_cache_size'},
$varlist{'thread_stack'},
$varlist{'time_format'},
$varlist{'time_zone'},
$varlist{'timed_mutexes'},
$varlist{'tmp_table_size'},
$varlist{'tmpdir'},
$varlist{'transaction_alloc_block_size'},
$varlist{'transaction_prealloc_size'},
$varlist{'tx_isolation'},
$varlist{'updatable_views_with_limit'},
$varlist{'version'},
$varlist{'version_comment'},
$varlist{'version_compile_machine'},
$varlist{'version_compile_os'},
$varlist{'wait_timeout'},
$varlist{'Aborted_clients'},
$varlist{'Aborted_connects'},
$varlist{'Binlog_cache_disk_use'},
$varlist{'Binlog_cache_use'},
$varlist{'Bytes_received'},
$varlist{'Bytes_sent'},
$varlist{'Com_admin_commands'},
$varlist{'Com_alter_db'},
$varlist{'Com_alter_table'},
$varlist{'Com_analyze'},
$varlist{'Com_backup_table'},
$varlist{'Com_begin'},
$varlist{'Com_call_procedure'},
$varlist{'Com_change_db'},
$varlist{'Com_change_master'},
$varlist{'Com_check'},
$varlist{'Com_checksum'},
$varlist{'Com_commit'},
$varlist{'Com_create_db'},
$varlist{'Com_create_function'},
$varlist{'Com_create_index'},
$varlist{'Com_create_table'},
$varlist{'Com_create_user'},
$varlist{'Com_dealloc_sql'},
$varlist{'Com_delete'},
$varlist{'Com_delete_multi'},
$varlist{'Com_do'},
$varlist{'Com_drop_db'},
$varlist{'Com_drop_function'},
$varlist{'Com_drop_index'},
$varlist{'Com_drop_table'},
$varlist{'Com_drop_user'},
$varlist{'Com_execute_sql'},
$varlist{'Com_flush'},
$varlist{'Com_grant'},
$varlist{'Com_ha_close'},
$varlist{'Com_ha_open'},
$varlist{'Com_ha_read'},
$varlist{'Com_help'},
$varlist{'Com_insert'},
$varlist{'Com_insert_select'},
$varlist{'Com_kill'},
$varlist{'Com_load'},
$varlist{'Com_load_master_data'},
$varlist{'Com_load_master_table'},
$varlist{'Com_lock_tables'},
$varlist{'Com_optimize'},
$varlist{'Com_preload_keys'},
$varlist{'Com_prepare_sql'},
$varlist{'Com_purge'},
$varlist{'Com_purge_before_date'},
$varlist{'Com_rename_table'},
$varlist{'Com_repair'},
$varlist{'Com_replace'},
$varlist{'Com_replace_select'},
$varlist{'Com_reset'},
$varlist{'Com_restore_table'},
$varlist{'Com_revoke'},
$varlist{'Com_revoke_all'},
$varlist{'Com_rollback'},
$varlist{'Com_savepoint'},
$varlist{'Com_select'},
$varlist{'Com_set_option'},
$varlist{'Com_show_binlog_events'},
$varlist{'Com_show_binlogs'},
$varlist{'Com_show_charsets'},
$varlist{'Com_show_collations'},
$varlist{'Com_show_column_types'},
$varlist{'Com_show_create_db'},
$varlist{'Com_show_create_table'},
$varlist{'Com_show_databases'},
$varlist{'Com_show_errors'},
$varlist{'Com_show_fields'},
$varlist{'Com_show_grants'},
$varlist{'Com_show_innodb_status'},
$varlist{'Com_show_keys'},
$varlist{'Com_show_logs'},
$varlist{'Com_show_master_status'},
$varlist{'Com_show_ndb_status'},
$varlist{'Com_show_new_master'},
$varlist{'Com_show_open_tables'},
$varlist{'Com_show_privileges'},
$varlist{'Com_show_processlist'},
$varlist{'Com_show_slave_hosts'},
$varlist{'Com_show_slave_status'},
$varlist{'Com_show_status'},
$varlist{'Com_show_storage_engines'},
$varlist{'Com_show_tables'},
$varlist{'Com_show_triggers'},
$varlist{'Com_show_variables'},
$varlist{'Com_show_warnings'},
$varlist{'Com_slave_start'},
$varlist{'Com_slave_stop'},
$varlist{'Com_stmt_close'},
$varlist{'Com_stmt_execute'},
$varlist{'Com_stmt_fetch'},
$varlist{'Com_stmt_prepare'},
$varlist{'Com_stmt_reset'},
$varlist{'Com_stmt_send_long_data'},
$varlist{'Com_truncate'},
$varlist{'Com_unlock_tables'},
$varlist{'Com_update'},
$varlist{'Com_update_multi'},
$varlist{'Com_xa_commit'},
$varlist{'Com_xa_end'},
$varlist{'Com_xa_prepare'},
$varlist{'Com_xa_recover'},
$varlist{'Com_xa_rollback'},
$varlist{'Com_xa_start'},
$varlist{'Compression'},
$varlist{'Connections'},
$varlist{'Created_tmp_disk_tables'},
$varlist{'Created_tmp_files'},
$varlist{'Created_tmp_tables'},
$varlist{'Delayed_errors'},
$varlist{'Delayed_insert_threads'},
$varlist{'Delayed_writes'},
$varlist{'Flush_commands'},
$varlist{'Handler_commit'},
$varlist{'Handler_delete'},
$varlist{'Handler_discover'},
$varlist{'Handler_prepare'},
$varlist{'Handler_read_first'},
$varlist{'Handler_read_key'},
$varlist{'Handler_read_next'},
$varlist{'Handler_read_prev'},
$varlist{'Handler_read_rnd'},
$varlist{'Handler_read_rnd_next'},
$varlist{'Handler_rollback'},
$varlist{'Handler_savepoint'},
$varlist{'Handler_savepoint_rollback'},
$varlist{'Handler_update'},
$varlist{'Handler_write'},
$varlist{'Innodb_buffer_pool_pages_data'},
$varlist{'Innodb_buffer_pool_pages_dirty'},
$varlist{'Innodb_buffer_pool_pages_flushed'},
$varlist{'Innodb_buffer_pool_pages_free'},
$varlist{'Innodb_buffer_pool_pages_misc'},
$varlist{'Innodb_buffer_pool_pages_total'},
$varlist{'Innodb_buffer_pool_read_ahead_rnd'},
$varlist{'Innodb_buffer_pool_read_ahead_seq'},
$varlist{'Innodb_buffer_pool_read_requests'},
$varlist{'Innodb_buffer_pool_reads'},
$varlist{'Innodb_buffer_pool_wait_free'},
$varlist{'Innodb_buffer_pool_write_requests'},
$varlist{'Innodb_data_fsyncs'},
$varlist{'Innodb_data_pending_fsyncs'},
$varlist{'Innodb_data_pending_reads'},
$varlist{'Innodb_data_pending_writes'},
$varlist{'Innodb_data_read'},
$varlist{'Innodb_data_reads'},
$varlist{'Innodb_data_writes'},
$varlist{'Innodb_data_written'},
$varlist{'Innodb_dblwr_pages_written'},
$varlist{'Innodb_dblwr_writes'},
$varlist{'Innodb_log_waits'},
$varlist{'Innodb_log_write_requests'},
$varlist{'Innodb_log_writes'},
$varlist{'Innodb_os_log_fsyncs'},
$varlist{'Innodb_os_log_pending_fsyncs'},
$varlist{'Innodb_os_log_pending_writes'},
$varlist{'Innodb_os_log_written'},
$varlist{'Innodb_page_size'},
$varlist{'Innodb_pages_created'},
$varlist{'Innodb_pages_read'},
$varlist{'Innodb_pages_written'},
$varlist{'Innodb_row_lock_current_waits'},
$varlist{'Innodb_row_lock_time'},
$varlist{'Innodb_row_lock_time_avg'},
$varlist{'Innodb_row_lock_time_max'},
$varlist{'Innodb_row_lock_waits'},
$varlist{'Innodb_rows_deleted'},
$varlist{'Innodb_rows_inserted'},
$varlist{'Innodb_rows_read'},
$varlist{'Innodb_rows_updated'},
$varlist{'Key_blocks_not_flushed'},
$varlist{'Key_blocks_unused'},
$varlist{'Key_blocks_used'},
$varlist{'Key_read_requests'},
$varlist{'Key_reads'},
$varlist{'Key_write_requests'},
$varlist{'Key_writes'},
$varlist{'Last_query_cost'},
$varlist{'Max_used_connections'},
$varlist{'Not_flushed_delayed_rows'},
$varlist{'Open_files'},
$varlist{'Open_streams'},
$varlist{'Open_tables'},
$varlist{'Opened_tables'},
$varlist{'Prepared_stmt_count'},
$varlist{'Qcache_free_blocks'},
$varlist{'Qcache_free_memory'},
$varlist{'Qcache_hits'},
$varlist{'Qcache_inserts'},
$varlist{'Qcache_lowmem_prunes'},
$varlist{'Qcache_not_cached'},
$varlist{'Qcache_queries_in_cache'},
$varlist{'Qcache_total_blocks'},
$varlist{'Questions'},
$varlist{'Rpl_status'},
$varlist{'Select_full_join'},
$varlist{'Select_full_range_join'},
$varlist{'Select_range'},
$varlist{'Select_range_check'},
$varlist{'Select_scan'},
$varlist{'Slave_open_temp_tables'},
$varlist{'Slave_retried_transactions'},
$varlist{'Slave_running'},
$varlist{'Slow_launch_threads'},
$varlist{'Slow_queries'},
$varlist{'Sort_merge_passes'},
$varlist{'Sort_range'},
$varlist{'Sort_rows'},
$varlist{'Sort_scan'},
$varlist{'Table_locks_immediate'},
$varlist{'Table_locks_waited'},
$varlist{'Tc_log_max_pages_used'},
$varlist{'Tc_log_page_size'},
$varlist{'Tc_log_page_waits'},
$varlist{'Threads_cached'},
$varlist{'Threads_connected'},
$varlist{'Threads_created'},
$varlist{'Threads_running'},
$varlist{'Uptime'},
$varlist{'server_snmp_error_code'},
$varlist{'server_mysql_error_code'},
$varlist{'Slave_SQL_Running'},
$varlist{'Slave_IO_Running'},
$varlist{'Seconds_Behind_Master'},
$varlist{'illegal_global_user'},
$varlist{'illegal_grant_user'},
$varlist{'illegal_remote_root'},
$varlist{'illegal_user_nopass'},
$varlist{'illegal_user_noname'},
$varlist{'collection_time_elapse'},
NOW()
);";
my $dbh = DBI->connect(
"DBI:mysql:$mysql_w_db:$mysql_w_host",
$mysql_w_user,
$mysql_w_pass,
{
PrintError => 0,
RaiseError => 0
}
) or error_report("$DBI::errstr");
my $sth = $dbh->prepare($sql0) or error_report("$DBI::errstr");
$sth->execute or error_report("$DBI::errstr");
$sth->finish;
$dbh->disconnect;
}
#populate all of the variables in the query list with their values from the xml file processing below
sub parse_data {
my $dbh = DBI->connect(
"DBI:mysql:$mysql_r_db:$mysql_r_host",
$mysql_r_user,
$mysql_r_pass,
{
PrintError => 0,
RaiseError => 0
}
) or error_report("$DBI::errstr");
my $file = $_[0];
my $server_id = $_[1];
my $active_status = $_[2];
my $updated_status;
my $parser = XML::Parser->new(ErrorContext => 2, Style => "Tree");
my $xso = XML::SimpleObject->new( $parser->parsefile($file));
foreach my $server ($xso->child('kontrollbase')->children('server')) {
$h = $server->attribute('hostname');
debug_report("$h [starting]");
# we get the time of the dataset
foreach my $datetime($server->child('datetime')) {
my $dt = $datetime->value;
debug_report("$h xml datetime = $dt");
$varlist{'datetime'} = $datetime->value;
}
# we find errors!
if($server->child('error')) {
foreach my $error($server->child('error')) {
my $error_type = $error->attribute('type');
my $error_value = $dbh->quote($error->value);
debug_report("error = $error_value");
debug_report("error type = $error_type");
if($error_type eq "snmp") {
$varlist{'server_snmp_error_code'} = $error_value;
}
if($error_type eq "mysql") {
$varlist{'server_mysql_error_code'} = $error_value;
}
if($error_type eq "mysql-connection-error") {
$varlist{'server_mysql_error_code'} = $error_value;
$updated_status = 2;
modify_active_status($server_id,$active_status,$updated_status);
error_report("mysql connection error occured, setting status of $h to inactive");
}
}
}
else {
debug_report("$h OS SNMP status [OK]");
}
# we assign values to hash
while (my($key,$value) = each(%varlist)) {
foreach my $item($server->child('item')) {
my $item_name = $item->attribute('name');
my $item_value = '0';
if($item->value) { $item_value = $item->value; }
if($item_name eq $key) {
$value = $dbh->quote($item_value);
#print "$key => $value: ";
$varlist{$key} = $value;
#print $varlist{$key}."\n";
}
}
}
#do some variable cleaning and math for queries/sec
my $Questions = $varlist{'Questions'};
my $Uptime = $varlist{'Uptime'};
$Questions =~ s/'//g;
$Uptime =~ s/'//g;
my $qsec = ($Questions/$Uptime);
$varlist{'queries_per_second'}=$qsec;
my $os_mem_total = $varlist{'os_mem_total'};
# We do the following to compensate for the OID for os_mem_used actually outputting the memAvailReal so we have to subtract that from the total to get the used value.
my $os_mem_total = $varlist{'os_mem_total'};
my $os_mem_used = $varlist{'os_mem_used'};
$os_mem_total =~ s/'//g;
$os_mem_used =~ s/'//g;
$varlist{'os_mem_used'} = $os_mem_total - $os_mem_used;
debug_report("$h MySQL Connection status [OK]");
#print compute time from xml
my $time = $varlist{'collection_time_elapse'};
$time =~ s/'//g;
debug_report("$h Collection time: $time seconds");
}
$dbh->disconnect;
debug_report("$h [success]");
}
sub error_report {
my $err0 = $_[0];
my $errtime = strftime "%Y-%m-%d %H:%M:%S", localtime;
my $err1 = $errtime." | ERROR | stats-gather-5.0.x_linux-x86: ".$err0."\n";
print $err1;
sysopen(FILE, $error_log, O_RDWR|O_EXCL|O_CREAT, 0644);
open FILE, ">>$error_log" or die $!;
print FILE $err1;
close FILE;
debug_report($err0);
exit 1;
}
sub debug_report {
my $note = $_[0];
my $debugtime = strftime "%Y-%m-%d %H:%M:%S", localtime;
$note = $debugtime." | DEBUG | stats-gather-5.0.x_linux-x86: ".$note."\n";
print $note;
sysopen(FILE, $debug_log, O_RDWR|O_EXCL|O_CREAT, 0644);
open FILE, ">>$debug_log" or die $!;
print FILE $note;
close FILE;
}
sub modify_active_status {
my $server_id = $_[0];
my $active_status = $_[1];
my $updated_status = $_[2];
my $server_hostname = $_[3];
my $sql1;
my $dbh = DBI->connect(
"DBI:mysql:$mysql_w_db:$mysql_w_host",
$mysql_w_user,
$mysql_w_pass,
{
PrintError => 0,
RaiseError => 0
}
) or error_report("$DBI::errstr");
if (($active_status == 1) && ($updated_status == 2)) {
$sql1 = "UPDATE server_list set active = '2' where id = $server_id;";
debug_report("connection with $server_hostname server_list_id: $server_id resulted in 0 byte XML file - check client script. Updating database, setting active = '2'")
}
elsif (($active_status == 2) && ($updated_status == 1)) {
$sql1 = "UPDATE server_list set active = '1' where id = $server_id;";
debug_report("connection with $server_hostname server_list_id: $server_id reestablished, updating database, setting active = '1'")
}
elsif ($active_status == $updated_status) {
$dbh->disconnect;
error_report("connection status of $server_hostname server_list_id: $server_id remains unchanged, no need to update database");
}
my $sth = $dbh->prepare($sql1) or error_report("$DBI::errstr");
$sth->execute or error_report("$DBI::errstr");
$sth->finish;
$dbh->disconnect;
exit 1;
}
config_connect();
my $xml_file = $ARGV[0];
my $server_id = $ARGV[1];
my $active_status = $ARGV[2];
my $server_hostname = $ARGV[3];
my $updated_status = 1;
$varlist{'server_list_id'} = $ARGV[1];
if(-e $xml_file) {
if(!$ARGV[1]) {
error_report("No server_id value specified. Exiting.");
}
if(-z $xml_file) {
debug_report("XML File is 0 size.");
modify_active_status($server_id,$active_status,"2",$server_hostname);
}
debug_report("## process start");
parse_data($xml_file,$server_id,$active_status);
insert_data() or error_report("$h [fail]");
if ($active_status == 2) {
modify_active_status( $server_id,$active_status,$updated_status,$server_hostname);
}
}
else {
error_report("No input file specified. Exiting.");
}
| ithoq/kontrollbase | bin/kontroll-stats-gather-5.0.x_linux-x86-2.0.1.pl | Perl | bsd-3-clause | 49,938 |
#
# ParsedVar.pm : part of the Mace toolkit for building distributed systems
#
# Copyright (c) 2010, Sunghwan Yoo, Charles Killian
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the names of Duke University nor The University of
# California, San Diego, nor the names of the authors or contributors
# may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ----END-OF-LEGAL-STUFF----
package Mace::Compiler::ParseTreeObject::ParsedVar;
use strict;
use Class::MakeMethods::Template::Hash
(
'new' => 'new',
'boolean' => 'is_static',
'boolean' => 'is_semi',
'scalar' => 'parameter',
);
sub toString {
my $this = shift;
my $s = "";
if( $this->is_static() ) {
$s = "static ";
}
$s .= $this->parameter();
if( $this->is_semi() ) {
$s .= ";";
}
return $s;
}
sub usedVar {
my $this = shift;
my @varArray = ();
# note : it is not processed. however, it should be changed to process expressions.
# push(@varArray, $this->parameter());
return @varArray;
}
1;
| jojochuang/eventwave | perl5/Mace/Compiler/ParseTreeObject/ParsedVar.pm | Perl | bsd-3-clause | 2,425 |
package DDG::Goodie::Poker;
# ABSTRACT: Returns requested statistic for the requested poker hand
use DDG::Goodie;
triggers any => 'poker';
zci answer_type => "poker";
zci is_cached => 1;
primary_example_queries 'poker odds three of a kind';
secondary_example_queries 'probability poker flush';
description 'returns requested statistic of the requested poker hand';
name 'Poker';
topics 'gaming', 'entertainment';
category 'random';
attribution github => [ 'austinheimark', 'Austin Heimark' ];
my %odds = (
"royal flush" => "649,739",
"straight flush" => "72,192",
"four of a kind" => "4,164",
"full house" => "693",
"flush" => "508",
"straight" => "254",
"three of a kind" => "46.3",
"two pair" => "20.0",
"one pair" => "1.36",
"no pair" => "0.995",
"high card" => "0.995",
);
my %frequency = (
"royal flush" => "4",
"straight flush" => "36",
"four of a kind" => "624",
"full house" => "3,744",
"flush" => "5,108",
"straight" => "10,200",
"three of a kind" => "54,912",
"two pair" => "123,552",
"one pair" => "1,098,240",
"no pair" => "1,302,540",
"high card" => "1,302,540",
);
my %probability = (
"royal flush" => "0.000154",
"straight flush" => "0.00139",
"four of a kind" => "0.0240",
"full house" => "0.144",
"flush" => "0.197",
"straight" => "0.392",
"three of a kind" => "2.11",
"two pair" => "4.75",
"one pair" => "42.3",
"no pair" => "50.1",
"high card" => "50.1",
);
my %webaddresses = (
"royal flush" => "Royal_flush",
"straight flush" => "Straight_flush",
"four of a kind" => "Four_of_a_kind",
"full house" => "Full_house",
"flush" => "Flush",
"straight" => "Straight",
"three of a kind" => "Three_of_a_kind",
"two pair" => "Two_pair",
"one pair" => "One_pair",
"no pair" => "High_card",
"high card" => "High_card",
);
handle remainder => sub {
#make sure the requested hand is listed
return unless /^(frequency|probability|odds)\s(.+)$/i && ($odds{lc$2});
my $query = lc $1;
my $hand = lc $2;
my $odds = "The odds of getting a $hand in poker are $odds{$hand} : 1.";
my $freq = "The frequency of a $hand in poker is $frequency{$hand} out of 2,598,960.";
my $prob = "The probability of getting a $hand in poker is $probability{$hand}%.";
my $link = qq(More at <a href="https://en.wikipedia.org/wiki/List_of_poker_hands#$webaddresses{$hand}">Wikipedia</a>.);
my %answer = (
'odds' => [$odds, 'html' => "$odds $link"],
'frequency' => [$freq, 'html' => "$freq $link"],
'probability' => [$prob, 'html' => "$prob $link"],
);
return @{$answer{$query}} if exists $answer{$query};
return;
};
1;
| Acidburn0zzz/zeroclickinfo-goodies | lib/DDG/Goodie/Poker.pm | Perl | apache-2.0 | 2,628 |
#!/usr/bin/perl
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use File::Find;
use Getopt::Std;
use vars qw($opt_d $opt_o $opt_v $opt_h);
use Cwd qw(abs_path);
no warnings 'File::Find';
getopts('d:o:vh');
my $usage = "Usage: $0 -d \"directories\" -o output_file [-v]";
if (defined $opt_h) {
print "$usage\n";
exit 0;
}
defined $opt_d or die "parameter error.\n$usage\n";
defined $opt_o or die "parameter error.\n$usage\n";
my @input_dir = split / /, $opt_d;
my @abs_input_dir = map {abs_path($_)} @input_dir;
my $output_file = abs_path($opt_o);
my $verbose = $opt_v;
my %result;
my $count = 0;
my @keys;
open OUTPUT, ">$output_file" or die "Can't open $output_file for write\n";
find(\&calc, @abs_input_dir);
@keys = keys %result;
foreach (@keys) {
print OUTPUT $_, "\x01", $result{$_}, "\n";
}
close OUTPUT;
print "Done: $count records have been written into $output_file.\n";
0;
sub calc {
my $file;
my $hash_value;
if (-d $_) {
return;
}
$file = $File::Find::name;
!defined $verbose or print "Processing: $file ... ";
# calc the md5sum of this file
if (!open READ, "<$file") {
!defined $verbose or print "Can't open this file, skip\n";
return;
}
$hash_value = md5_hex(<READ>);
if (defined($hash_value)) {
!defined $verbose or print "MD5: $hash_value\n";
} else {
!defined $verbose or print "Can't read this file, skip\n";
close READ;
return;
}
close READ;
$result{$file} = $hash_value;
$count++;
}
| 0x08e/SENginx | web-defacement.pl | Perl | bsd-3-clause | 1,563 |
package URI::tn3270;
use strict;
use warnings;
our $VERSION = '1.76';
use parent 'URI::_login';
sub default_port { 23 }
1;
| operepo/ope | client_tools/svc/rc/usr/share/perl5/vendor_perl/URI/tn3270.pm | Perl | mit | 128 |
# !!!!!!! 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';
12000 123FF
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/Cuneifor.pl | Perl | mit | 435 |
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::centreon::map::jmx::mode::sessions;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"warning:s" => { name => 'warning', },
"critical:s" => { name => 'critical', },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
$self->{output}->option_exit();
}
}
sub run {
my ($self, %options) = @_;
$self->{connector} = $options{custom};
$self->{request} = [
{ mbean => "com.centreon.studio:name=statistics,type=session" }
];
my $result = $self->{connector}->get_attributes(request => $self->{request}, nothing_quit => 0);
my $exit = $self->{perfdata}->threshold_check(value => $result->{"com.centreon.studio:name=statistics,type=session"}->{SessionCount},
threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning'} ]);
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Current sessions : %d",
$result->{"com.centreon.studio:name=statistics,type=session"}->{SessionCount}));
$self->{output}->perfdata_add(label => 'sessions',
value => $result->{"com.centreon.studio:name=statistics,type=session"}->{SessionCount},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'),
min => 0);
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check Centreon Map Number of sessions
Example:
perl centreon_plugins.pl --plugin=apps::centreon::map::jmx::plugin --custommode=jolokia --url=http://10.30.2.22:8080/jolokia-war --mode=sessions
=over 8
=item B<--warning>
Set this threshold if you want a warning if current session number match condition
=item B<--critical>
Set this threshold if you want a warning if current session number match condition
=back
=cut
| maksimatveev/centreon-plugins | apps/centreon/map/jmx/mode/sessions.pm | Perl | apache-2.0 | 3,858 |
#-----------------------------------------------------------
# wordwheelquery.pl
# For Windows 7
#
# Change history
# 20100330 - created
#
# References
# http://www.winhelponline.com/blog/clear-file-search-mru-history-windows-7/
#
# copyright 2010 Quantum Analytics Research, LLC
#-----------------------------------------------------------
package wordwheelquery;
use strict;
my %config = (hive => "NTUSER\.DAT",
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
osmask => 22,
version => 20100330);
sub getConfig{return %config}
sub getShortDescr {
return "Gets contents of user's WordWheelQuery key";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
sub pluginmain {
my $class = shift;
my $ntuser = shift;
::logMsg("Launching wordwheelquery v.".$VERSION);
::rptMsg("wordwheelquery v.".$VERSION); # banner
::rptMsg("(".getHive().") ".getShortDescr()."\n"); # banner
my $reg = Parse::Win32Registry->new($ntuser);
my $root_key = $reg->get_root_key;
my $key_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\WordWheelQuery";
my $key;
if ($key = $root_key->get_subkey($key_path)) {
::rptMsg($key_path);
::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
my @vals = $key->get_list_of_values();
if (scalar(@vals) > 0) {
my @list;
my %wwq;
foreach my $v (@vals) {
my $name = $v->get_name();
if ($name eq "MRUListEx") {
@list = unpack("V*",$v->get_data());
pop(@list) if ($list[scalar(@list) - 1] == 0xffffffff);
}
else {
my $data = $v->get_data();
$data =~ s/\x00//g;
$wwq{$name} = $data;
}
}
# list searches in MRUListEx order
::rptMsg("");
::rptMsg("Searches listed in MRUListEx order");
::rptMsg("");
foreach my $l (@list) {
::rptMsg(sprintf "%-4d %-30s",$l,$wwq{$l});
}
}
else {
::rptMsg($key_path." has no values.");
}
}
else {
::rptMsg($key_path." not found.");
}
}
1; | APriestman/autopsy | thirdparty/rr-full/plugins/wordwheelquery.pl | Perl | apache-2.0 | 2,118 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
10900 1091F
END
| Dokaponteam/ITF_Project | xampp/perl/lib/unicore/lib/Blk/Phoenici.pl | Perl | mit | 423 |
#! /usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
##
## Licensed under the Apache License, Version 2.0 (the "License"); you
## may not use this file except in compliance with the License. You may
## obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
##**************************************************************
BEGIN {$^W=1} #warnings enabled
kill 9, $$;
sleep 6 # just so it won't quit before the signal hits
| djw8605/htcondor | src/condor_tests/x_doublejeopardy.pl | Perl | apache-2.0 | 931 |
package HTML::Hard::Disk;
use strict;
use HTML::TokeParser;
use File::Find;
use File::Copy;
use vars qw($VERSION);
$VERSION = "0.2.1";
# Two utility functions
sub is_older
{
my $file1 = shift;
my $file2 = shift;
my @stat1 = stat($file1);
my @stat2 = stat($file2);
return ($stat1[9] <= $stat2[9]);
}
sub is_newer
{
my $file1 = shift;
my $file2 = shift;
return (! &is_older($file1, $file2));
}
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
$self->initialize(@_);
return $self;
}
sub set_base_dir
{
my $self = shift;
my $base_dir = shift;
$base_dir =~ s{/*$}{/};
$self->{'base_dir'} = $base_dir;
return 0;
}
sub get_base_dir
{
my $self = shift;
return $self->{'base_dir'};
}
sub set_dest_dir
{
my $self = shift;
my $dest_dir = shift;
$self->{'dest_dir'} = $dest_dir;
return 0;
}
sub get_dest_dir
{
my $self = shift;
return $self->{'dest_dir'};
}
sub initialize
{
my $self = shift;
my %args = @_;
$self->set_base_dir($args{'base_dir'} || ".");
$self->set_dest_dir($args{'dest_dir'} || "./dest");
return 0;
}
sub process_content
{
my $self = shift;
my $file = shift;
my $out_content = "";
my $out = sub {
$out_content .= join("", @_);
};
my $parser = HTML::TokeParser->new($file);
while (my $token = $parser->get_token())
{
my $type = $token->[0];
if ($type eq "E")
{
$out->($token->[2]);
}
elsif ($type eq "C")
{
$out->($token->[1]);
}
elsif ($type eq "T")
{
$out->($token->[1]);
}
elsif ($type eq "D")
{
$out->($token->[1]);
}
elsif ($type eq "PI")
{
$out->($token->[2]);
}
elsif ($type eq "S")
{
my $tag = $token->[1];
my %process_tags =
(
'form' => { 'action' => 1 },
'img' => { 'src' => 1},
'a' => { 'href' => 1},
'link' => { 'href' => 1},
);
if (exists($process_tags{$tag}))
{
my $ret = "<$tag";
my $attrseq = $token->[3];
my $attr_values = $token->[2];
my $process_attrs = $process_tags{$tag};
foreach my $attr (@$attrseq)
{
my $value = $attr_values->{$attr};
if (exists($process_attrs->{$attr}))
{
# If it's a local link that ends with slash -
# then append index.html
if (($value !~ /^[a-z]+:/) && ($value !~ /^\//) &&
($value =~ /\/(#[^#\/]*)?$/))
{
my $pos = rindex($value, "/");
substr($value,$pos+1,0) = "index.html";
}
}
if ($attr eq "/")
{
$ret .= " /";
}
else
{
$ret .= " $attr=\"$value\"";
}
}
$out->($ret);
$out->(">");
}
else
{
$out->($token->[4]);
}
}
}
return $out_content;
}
sub process_file
{
my $self = shift;
my $file = shift;
my $dest_dir = $self->get_dest_dir();
my $src_dir = $self->get_base_dir();
local (*I, *O);
open I, "<$src_dir/$file" || die "Cannot open '$src_dir/$file' - $!";
open O, ">$dest_dir/$file" || die "Cannot open '$dest_dir/$file' for writing- $!";
print O $self->process_content(\*I);
close(I);
close(O);
}
sub process_dir_tree
{
my $self = shift;
my %args = @_;
my $should_replace_file = sub {
my ($src, $dest) = @_;
if ($args{'only-newer'})
{
return ((! -e $dest) || (&is_newer($src, $dest)));
}
else
{
return 1;
}
};
my $src_dir = $self->get_base_dir();
my $dest_dir = $self->get_dest_dir();
my (@dirs, @other_files, @html_files);
my $wanted = sub {
my $filename = $File::Find::name;
if (length($filename) < length($src_dir))
{
return;
}
# Remove the $src_dir from the filename;
$filename = substr($filename, length($src_dir));
if (-d $_)
{
push @dirs, $filename;
}
elsif (/\.html?$/)
{
push @html_files, $filename;
}
else
{
push @other_files, $filename;
}
};
find($wanted, $src_dir);
my $soft_mkdir = sub {
my $dir = shift;
if (-d $dir)
{
# Do nothing
}
elsif (-e $dir)
{
die "$dir exists in destination and is not a directory";
}
else
{
mkdir($dir) || die "mkdir failed: $!\n";
}
};
# Create the directory structure in $dest
$soft_mkdir->($dest_dir);
foreach my $dir (@dirs)
{
$soft_mkdir->("$dest_dir/$dir");
}
foreach my $file (@other_files)
{
my $src = "$src_dir/$file";
my $dest = "$dest_dir/$file";
if ($should_replace_file->($src, $dest))
{
copy($src, $dest);
}
}
foreach my $file (@html_files)
{
my $src = "$src_dir/$file";
my $dest = "$dest_dir/$file";
if ($should_replace_file->($src,$dest))
{
$self->process_file($file);
}
}
return 0;
}
1;
=head1 NAME
HTML::Hard::Disk - Convert HTML Files to be used on a hard disk
=head1 SYNOPSIS
use HTML::Hard::Disk;
my $converter =
HTML::Hard::Disk->new(
'base_dir' => "/var/www/html/shlomi/Perl/Newbies/lecture4/",
'dest_dir' => "./dest"
);
$converter->process_file("mydir/myfile.html");
$converter->process_dir_tree('only-newer' => 1);
my $new_content = $converter->process_content(\$html_text);
=head1 DESCRIPTION
HTML::Hard::Disk converts HTML files to be used when viewing on the
hard disk. Namely, it converts relative links to point to "index.html"
files in their directories.
To use it, first initialize an instance using new. The constructor
accepts two named parameters which are mandatory. C<'base_dir'> is
the base directory (or source directory) for the operations.
C<'dest_dir'> is the root destination directory.
Afterwards, you can use the methods:
=head2 $new_content = $converter->process_content(FILE)
This function converts a singular text of an HTML file to a hard disk one.
FILE is any argument accepatble by L<HTML::TokeParser>. It returns
the new content.
=head2 $converter->process_file($filename)
This function converts a filename relative to the source directory to
its corresponding file in the destination directory.
=head2 $converter->process_dir_tree( [ 'only-newer' => 1] );
This function converts the entire directory tree that starts at the
base directory. only-newer means to convert only files that are newer
in a make-like fashion.
=head1 AUTHOR
Shlomi Fish E<lt>shlomif@vipe.technion.ac.ilE<gt>
=cut
| gitpan/HTML-Hard-Disk | lib/HTML/Hard/Disk.pm | Perl | mit | 7,508 |
package inc::MakeMaker;
use Moose;
use inc::MMHelper;
extends 'Dist::Zilla::Plugin::MakeMaker::Awesome';
around _build_MakeFile_PL_template => sub {
my $orig = shift;
my $self = shift;
my $tmpl = $self->$orig;
my $extra = inc::MMHelper::makefile_pl_extra;
$tmpl =~ s/^(WriteMakefile\()/$extra\n$1/m
or die "Couldn't fix template";
return $tmpl;
};
around _build_WriteMakefile_args => sub {
my $orig = shift;
my $self = shift;
my $args = $self->$orig(@_);
return {
%$args,
%{ inc::MMHelper::mm_args() },
}
};
__PACKAGE__->meta->make_immutable;
no Moose;
1;
| gitpan/Parse-Keyword | inc/MakeMaker.pm | Perl | mit | 629 |
#!/usr/bin/perl -w
# Copyright 2001, 20002 Rob Edwards
# For updates, more information, or to discuss the scripts
# please contact Rob Edwards at redwards@utmem.edu or via http://www.salmonella.org/
#
# This file is part of The Phage Proteome Scripts developed by Rob Edwards.
#
# Tnese scripts are free software; you can redistribute and/or modify
# them under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# They are distributed in the hope that they will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# in the file (COPYING) along with these scripts; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# combinprotdists.pl
# new version. This will assign a distance of $penalty to any sequence that does not match, and to all empty
# spaces. There is a good rationale for this. The The Dayhoff PAM matrix scoring system returns a percent of
# the amino acids that are likely to have changed. Therefore a 100% score means that they have all changed.
# We will make an average, and include the number of scores used to calculate the average. Then we can fitch
# it with the subreplicas option.
# the subreplicate number will be added if the protein appears, but is not similar. (i.e. an average score of 100 2
# means that two proteins were found to be similar but were to distant for a score. But an average score of
# 100 0 means that no proteins were found!
# in this version you can select -n for no padding of missing proteins. Padding runs through the genome and if
# no match to another genome is found it increments the score by 100 for each protein in the query (line) genome
use DBI;
use strict;
my $usage = "combineprotdists.pl <dir of prot dists> <matrix filename> <number of genomes used> <options>\nOPTIONS\n";
$usage .= "\t-n DON'T pad missing proteins with worst score (supplied with the -p option)\n\t-m print out all protein matches";
$usage .= "\n\t-p # penalty for being bad Rob. Default is 100\n\t-l factor lengths of proteins into the scores\n";
$usage .= "\t-lp penalize based on protein lengths (otherwise it will be whatever the penalty is)\n";
$usage .= "\t-s # skip proteins with match >= this value (treat as if there is no match)\n";
$usage .= "\t-c report progress (will be put on STDERR, but you may want to redirect this\n";
$usage .= "\t-a don't average the protein scores (only works with -l)\n";
my $dbh=DBI->connect("DBI:mysql:phage", "apache") or die "Can't connect to database\n";
my $dir= shift || &niceexit($usage);
my $matrixfilename = shift || &niceexit($usage);
my $nogenomes = shift || &niceexit($usage);
my $args= join (" ", @ARGV);
my $pad=1; my $penalty =100;
my $skip=100000000; # start with skip unreasonably high. Nothing will be bigger than this. Reset if called on command line
if ($args =~ /-n/) {$pad=0}
if ($args =~ /-p\s+(\d+)/) {$penalty=$1}
if ($args =~ /-s\s+(\d+)/) {$skip=$1; print STDERR "Using skip of $skip\n"}
print STDERR "Using PENALTY of $penalty and PAD of $pad\n";
my %noorfs;
&getnoorfs;
my %proteinlength;
if ($args =~ /-l/) {
my $length = &getprotlengths;
%proteinlength = %$length;
}
my @matrix; my @oldmatrix;
my @oldmatch; my @oldmatchcount; my @oldmismatch; my @oldmismatchcount;
my @newmatch; my @newmatchcount; my @newmismatch; my @newmismatchcount;
my @count; my @oldcount;
my @proteinmatches; my @genematches; my $minmatch = 100; my $maxmatch=1;
my %linegenomecount;
# read each file one at a time, and add the data to an array
opendir(DIR, $dir) || &niceexit("Can't open $dir");
print STDERR "Reading the files\n";
while (my $file=readdir(DIR)) {
next if ($file =~ /^\./);
open (IN, "$dir/$file") || &niceexit("Can't open $dir/$file");
my @genomes = ('0');
my @genes = ('0');
my @dists;
my %genomeshash;
my %checkdupgenomes;
my %genegenome;
# we need to know all the genomes before we can store the data. Therefore
# read and store each line in @dists
# then get all the genome numbers and store them in an array
while (my $line = <IN>) {
chomp($line);
my @line = split (/\s+/, $line);
next unless ($#line);
next if ($line =~ /^\s+/);
# added loop to get the genome number from the database
unless ($line[0] =~ /_/) {
unless ($genegenome{$line[0]}) {
my $exc = $dbh->prepare("select organism from protein where count like '$line[0]'");
$exc->execute or die $dbh->errstr;
my @retrieved = $exc->fetchrow_array;
$genegenome{$line[0]} = $retrieved[0];
}
$line[0] .= "_".$genegenome{$line[0]};
$line = join (" ", @line); # this just corrects $line if we change it
}
push (@dists, $line);
my ($gene, $genome) = split (/_/, $line[0]);
unless ($gene && $genome) {&niceexit("Can't parse $line in $file\n")}
push (@genes, $gene);
push (@genomes, $genome);
$checkdupgenomes{$genome}++;
}
# now we loop through all the lines, and split them on white space.
# then we add each value to the pre-existing value in the matrix
# note that because the genomes are represented as numbers we can just
# use these numbers for the position in the matrix.
# we are going to also count the number of times that we save each data
# point for the final average.
# Finally, we only do this in one direction because the input
# matrices are complete (and identical) on both halves.
# note that column zero of the matrix is empty (there is no genome 0)
foreach my $z (0 .. $#dists) {
my @line = split (/\s+/, $dists[$z]);
unless ($#line == $#genomes) {
my $x; foreach my $y (0 .. $#dists) {if ($dists[$y] eq $dists[$z]) {$x = $y}}
&niceexit("PROBLEM WITH \n@line AND \n@genomes\n\nIN FILE: $file\n\nBECAUSE $#line AND $#genomes AT LINE $x\n");
}
my ($gene, $linegenome) = split (/_/, $line[0]);
unless ($gene && $linegenome) {&niceexit("CAN'T PARSE @line SECOND TIME AROUND\n")}
$linegenomecount{$linegenome}++;
my @seengenome;
foreach my $x (1 .. $#genomes) { #do this for all the genomes.
next if ($x <= $z+1);
# If we are padding the table with 100s where there is no match, we
# need to convert the -1's to 100. Otherwise we will ignore it.
if ($line[$x] == -1) {if ($pad) {$line[$x] = $penalty} else {next}}
next if ($line[$x] > $skip);
my $oldline;
if ($args =~ /-l/) {
if ($args =~ /-c/) {print STDERR "For $x, $line[$x] has protein lengths $proteinlength{$genes[$x]} and $proteinlength{$gene} and becomes "}
$oldline=$line[$x];
$line[$x] = $line[$x] * ($proteinlength{$genes[$x]}+$proteinlength{$gene});
unless ($args =~ /-a/) {$line[$x] = $line[$x]/2}
if ($args =~ /-c/) {print STDERR " $line[$x]\n"}
if ($line[$x] > $maxmatch) {$maxmatch=$line[$x]}
if ($line[$x] < $minmatch) {$minmatch=$line[$x]}
}
#if it is itself, we want to make it zero. Otherwise, we'll save the protein numbers that match
if ($genomes[$x] == $linegenome) {$line[$x] = '0.000'}
else {
my $genematch;
# save the protein matches, but I only want to save them one way around
# to make it easier
if ($gene <$genes[$x]) {$genematch = $gene.",".$genes[$x].";".$line[$x]}
else {$genematch = $genes[$x].",".$gene.";".$line[$x]}
# protein match is a two dimensional array where each element is an array.
# but it is called with an array! 4 dimensions?
${$proteinmatches[$linegenome][$genomes[$x]]}{$genematch} =1;
# gene matches is all the genes from $linegenome that match genome. This will
# be used to calculate the penalty for ORFs that are missed.
${$genematches[$linegenome][$genomes[$x]]}{$gene} =1;
}
# add the length if we need to.
####### if ($args =~ /-l/ && $line[$x] > 0) {
if ($args =~ /-l/) {
#now save the data because the count is really the length not the number
$matrix[$linegenome][$genomes[$x]] += $line[$x];
$newmatch[$linegenome][$genomes[$x]] += $line[$x];
{
my $countadj;
if ($args =~ /-a/) {$countadj = ($proteinlength{$genes[$x]}+$proteinlength{$gene})}
else {$countadj = ($proteinlength{$genes[$x]}+$proteinlength{$gene})/2}
$count[$linegenome][$genomes[$x]] += $countadj;
$newmatchcount[$linegenome][$genomes[$x]] += $countadj;
}
$oldmatrix[$linegenome][$genomes[$x]] += $oldline; $oldcount[$linegenome][$genomes[$x]] ++;
$oldmatch[$linegenome][$genomes[$x]] += $oldline; $oldmatchcount[$linegenome][$genomes[$x]] ++;
}
else {
$matrix[$linegenome][$genomes[$x]] += $line[$x];
$count[$linegenome][$genomes[$x]] ++;
}
$seengenome[$linegenome][$genomes[$x]] ++;
}
# now we need to pad out all the missing genomes with 100's
if ($pad) {
foreach my $x (1 .. $nogenomes) {
next if ($checkdupgenomes{$x});
next if ($seengenome[$linegenome][$x]);
if ($args =~ /-lp/) {
$matrix[$linegenome][$x] += $penalty*$proteinlength{$gene};
$count[$linegenome][$x] += $proteinlength{$gene};
$oldmatrix[$linegenome][$x] += $penalty; $oldcount[$linegenome][$x] ++;
$newmismatch[$linegenome][$x] += $penalty*$proteinlength{$gene};
$newmismatchcount[$linegenome][$x] += $proteinlength{$gene};
$oldmismatch[$linegenome][$x] += $penalty; $oldmismatchcount[$linegenome][$x] ++;
}
else {
$matrix[$linegenome][$x] += $penalty;
$count[$linegenome][$x] ++;
}
}
}
}
}
print STDERR "\tDone\nSorting and calculating\n";
print STDERR "Minimum match was $minmatch and maximum match was $maxmatch\n";
my $genomeproteins;
{
# now we need to penalize genomes that have only a few macthes.
# we will go through gene matches for each pair in the matrix, and
# add a penalty based on the number of missing orfs.
if ($pad) {
if ($args =~ /-lp/) {$genomeproteins = &getallprots()}
else {
open (MISS, ">missing.seqs.txt") || &niceexit("Can't open missing.seqs.txt\n");
print MISS "Original\t#ORFs\tCompared to\t# similar\t# different\n";
}
foreach my $y (0 .. $#genematches) {
next unless (exists $noorfs{$y}); # this just checks we have orfs for genome $y
foreach my $x (1 .. $#{$matrix[$y]}) {
next unless (exists $noorfs{$x});
next if ($y == $x);
my @similar = keys %{$proteinmatches[$y][$x]};
if ($y + $x ==19) {print "xxsimilar $y, $x -> ", $#similar+1, ":\n|", join ("|\n|", @similar), "|\n"}
# need to add a loop to get all proteins per genome, and then remove the ones we've seen
if ($args =~ /-lp/) {
my %found;
foreach my $similar (@similar) {
my ($genes, $trash) = split /;/, $similar;
my ($gene1, $gene2) = split /,/, $genes;
$found{$gene1}=$found{$gene2}=1;
}
foreach my $missedprot (@{${$genomeproteins}{$y}}) {
next if (exists $found{$missedprot});
$matrix[$y][$x] += $proteinlength{$missedprot}*$penalty;
$count[$y][$x] += $proteinlength{$missedprot};
$oldmatrix[$y][$x] += $penalty; $oldcount[$y][$x]++;
$newmismatch[$y][$x] += $proteinlength{$missedprot}*$penalty;
$newmismatchcount[$y][$x] += $proteinlength{$missedprot};
$oldmismatch[$y][$x] += $penalty; $oldmismatchcount[$y][$x]++;
}
}
else {
my $difference = $noorfs{$y} - ($#similar+1);
print MISS "$y\t$noorfs{$y}\t$x\t",$#similar+1, "\t$difference\n";
next unless ($difference);
$matrix[$y][$x] += ($penalty * $difference);
$count[$y][$x] += $difference;
}
}
}
}
}
my %difference; my %genomedifference;
{
open (MISMATCH, ">$matrixfilename.old.vs.new") || print STDERR "WARNING: Can't open MISMATCH\n";
print MISMATCH "genome 1\tgenome 2\tOld match\tNew Match\tOld Mismatch\tNew Mismatch\tOld Score\tNew Score\tMatch Diff\tMisMatch Diff\tScore Diff\n";
my %seen;
# now we will average the matrix based on the count.
foreach my $y (0 .. $#matrix) {
next unless ($matrix[$y]);
foreach my $x (1 .. $#{$matrix[$y]}) {
next unless ($count[$y][$x] && $matrix[$y][$x]);
my $temp = $x."+".$y; my $temp1 = $y."+".$x;
next if ($seen{$temp} || $seen{$temp1});
$seen{$temp} = $seen{$temp1} =1;
# because we are only looking at one half of the matrix (see above)
# we need to be sure that both halves are the same.
# this loop will take care of that.
$matrix[$y][$x] = $matrix[$x][$y] = $matrix[$y][$x] + $matrix[$x][$y];
$count[$y][$x] = $count[$x][$y] = $count[$y][$x] + $count[$x][$y];
$matrix[$x][$y] = $matrix[$y][$x] = $matrix[$y][$x]/$count[$y][$x];
if ($oldmatrix[$y][$x] || $oldmatrix[$x][$x]) {
$oldmatrix[$y][$x] = $oldmatrix[$x][$y] = $oldmatrix[$y][$x] + $oldmatrix[$x][$y];
$oldcount[$y][$x] = $oldcount[$x][$y] = $oldcount[$y][$x] + $oldcount[$x][$y];
$oldmatrix[$y][$x] = $oldmatrix[$x][$y] = $oldmatrix[$y][$x]/$oldcount[$y][$x];
if (($oldmatch[$y][$x] || $oldmatch[$x][$y]) && ($oldmatchcount[$y][$x] || $oldmatchcount[$x][$y])) {
# this is just to get around various error messages
unless ($oldmatch[$y][$x]) {$oldmatch[$y][$x]=0}
unless ($oldmatch[$x][$y]) {$oldmatch[$x][$y]=0}
unless ($oldmatchcount[$y][$x]) {$oldmatchcount[$y][$x]=0}
unless ($oldmatchcount[$x][$y]) {$oldmatchcount[$x][$y]=0}
unless ($oldmismatch[$y][$x]) {$oldmismatch[$y][$x]=0}
unless ($oldmismatch[$x][$y]) {$oldmismatch[$x][$y]=0}
unless ($oldmismatchcount[$y][$x]) {$oldmismatchcount[$y][$x]=0}
unless ($oldmismatchcount[$x][$y]) {$oldmismatchcount[$x][$y]=0}
unless ($newmatch[$y][$x]) {$newmatch[$y][$x]=0}
unless ($newmatch[$x][$y]) {$newmatch[$x][$y]=0}
unless ($newmatchcount[$y][$x]) {$newmatchcount[$y][$x]=0}
unless ($newmatchcount[$x][$y]) {$newmatchcount[$x][$y]=0}
unless ($newmismatch[$y][$x]) {$newmismatch[$y][$x]=0}
unless ($newmismatch[$x][$y]) {$newmismatch[$x][$y]=0}
unless ($newmismatchcount[$y][$x]) {$newmismatchcount[$y][$x]=0}
unless ($newmismatchcount[$x][$y]) {$newmismatchcount[$x][$y]=0}
$oldmatch[$y][$x] = $oldmatch[$x][$y] = ($oldmatch[$y][$x]+$oldmatch[$x][$y])/($oldmatchcount[$y][$x]+$oldmatchcount[$x][$y]);
$oldmismatch[$y][$x] = $oldmismatch[$x][$y] = ($oldmismatch[$y][$x]+$oldmismatch[$x][$y])/($oldmismatchcount[$y][$x]+$oldmismatchcount[$x][$y]);
$newmatch[$y][$x] = $newmatch[$x][$y] = ($newmatch[$y][$x]+$newmatch[$x][$y])/($newmatchcount[$y][$x]+$newmatchcount[$x][$y]);
$newmismatch[$y][$x] = $newmismatch[$x][$y] = ($newmismatch[$y][$x]+$newmismatch[$x][$y])/($newmismatchcount[$y][$x]+$newmismatchcount[$x][$y]);
print MISMATCH "$y\t$x\t$oldmatch[$y][$x]\t$newmatch[$y][$x]\t$oldmismatch[$y][$x]\t$newmismatch[$y][$x]\t$oldmatrix[$y][$x]\t$matrix[$x][$y]\t";
print MISMATCH abs($oldmatch[$y][$x]-$newmatch[$y][$x]), "\t", abs($oldmismatch[$y][$x]-$newmismatch[$y][$x]), "\t", abs($oldmatrix[$y][$x]-$matrix[$x][$y]), "\n";
}
$difference{"genome$y, genome$x used to be ".$oldmatrix[$y][$x].", and now is ".$matrix[$x][$y]} = abs($oldmatrix[$y][$x]-$matrix[$x][$y]);
$genomedifference{$y}+=abs($oldmatrix[$y][$x]-$matrix[$x][$y]);
$genomedifference{$x}+=abs($oldmatrix[$y][$x]-$matrix[$x][$y]);
}
}
}
}
{
# we are going to output the matrix twice. This first loop will output the matrix with
# the replicates number, and the second loop will output the matrix alone with no replicates
# number. This is to test whether FITCH is breaking on the number of replicates.
my $minmatch=100; my $maxmatch=1;
# now we have all the data, lets just print out the matrix
open (OUT, ">$matrixfilename");
print OUT $#matrix, "\n";
#foreach my $y (1 .. $#matrix) {print STDERR "\t$y"}
#print STDERR "\n";
foreach my $y (1 .. $#matrix) {
my $tempstring = "genome".$y;
if (length($tempstring) > 10) {print STDERR "$tempstring is too long\n"}
my $spacestoadd = " " x (10 - length($tempstring));
print OUT $tempstring,$spacestoadd;
foreach my $x (1 .. $#matrix) {
if ($y == $x) {
if ($args=~ /-l/) {
my $total;
foreach my $protein (@{${$genomeproteins}{$y}}) {$total+=$proteinlength{$protein}}
print OUT "0 $total ";
}
else {print OUT "0 $noorfs{$x} "}
next;
}
unless (defined $matrix[$y][$x]) {print OUT "$penalty 0 "; next}
unless ($matrix[$y][$x]) {
print OUT "0 ";
if ($count[$y][$x]) {print OUT int($count[$y][$x])," "}
else {print OUT "0 "}
next;
}
if ($matrix[$y][$x] > $maxmatch) {$maxmatch=$matrix[$y][$x]}
if ($matrix[$y][$x] < $minmatch) {$minmatch=$matrix[$y][$x]}
print OUT $matrix[$y][$x], " ", int($count[$y][$x]), " ";
if ($args=~ /-c/) {print STDERR "For $y, $x, matrix would have been $oldmatrix[$y][$x] but has become $matrix[$y][$x]\n"}
}
print OUT "\n";
}
print STDERR "MATRIX: Minimum = $minmatch and MAXIMUM = $maxmatch\n";
close OUT;
}
{
# output the matrix again, this time do not put out the replicates number
open (OUT, ">$matrixfilename.nosubreplicates");
print OUT $#matrix, "\n";
#foreach my $y (1 .. $#matrix) {print STDERR "\t$y"}
#print STDERR "\n";
foreach my $y (1 .. $#matrix) {
my $tempstring = "genome".$y;
if (length($tempstring) > 10) {print STDERR "$tempstring is too long\n"}
my $spacestoadd = " " x (10 - length($tempstring));
print OUT $tempstring,$spacestoadd;
foreach my $x (1 .. $#matrix) {
if ($y == $x) {print OUT "0 "; next}
unless (defined $matrix[$y][$x]) {print OUT "$penalty "; next}
unless ($matrix[$y][$x]) {print OUT "0 "; next}
print OUT $matrix[$y][$x], " ";
}
print OUT "\n";
}
close OUT;
}
if ($args =~ /-c/) {
foreach my $key (sort {$difference{$a} <=> $difference{$b}} keys %difference) {print "$key difference: $difference{$key}\n"}
foreach my $key (sort {$genomedifference{$b} <=> $genomedifference{$a}} keys %genomedifference) {print "genome$key difference: $genomedifference{$key}\n"}
}
if ($args=~ /-m/) {
open (PROT, ">$dir.protein.matches") || &niceexit("Can't open $dir.protein.matches for writing\n");
#print out all the protein matches
foreach my $y (1 .. $nogenomes) {
my $tempstring = "genome".$y;
if (length($tempstring) > 10) {print STDERR "$tempstring is too long\n"}
my $spacestoadd = " " x (10 - length($tempstring));
print PROT $tempstring,$spacestoadd, "\t";
foreach my $x (1 .. $nogenomes) {
unless (defined $proteinmatches[$y][$x]) {print PROT "\t"; next}
unless ($proteinmatches[$y][$x]) {print PROT "\t"; next}
my @allmatches = (keys %{$proteinmatches[$y][$x]}, keys %{$proteinmatches[$x][$y]});
my %allmatches;
@allmatches{@allmatches}=1;
@allmatches = sort keys %allmatches;
print PROT join (" ", sort @allmatches), "\t";
}
print PROT "\n";
}
}
&niceexit(0);
sub getnoorfs {
my $exc = $dbh->prepare("select organism from protein");
$exc->execute or die $dbh->errstr;
while (my @retrieved = $exc->fetchrow_array) {$noorfs{$retrieved[0]}++}
}
sub getprotlengths {
local $| =1;
my %length; my $total; my $count;
print STDERR "Getting protein lengths ";
my $exc = $dbh->prepare("select count,translation from protein");
$exc->execute or die $dbh->errstr;
while (my @retrieved = $exc->fetchrow_array) {$length{$retrieved[0]}=length($retrieved[1]); $total += $length{$retrieved[0]}; $count++}
print STDERR "Done\n";
print STDERR "Total length found is $total for $count proteins, average is ", $total/$count, "\n";
return \%length;
}
sub getallprots {
my %genomeproteins;
my $exc = $dbh->prepare("select count,organism from protein");
$exc->execute or die $dbh->errstr;
while (my @ret = $exc->fetchrow_array) {push (@{$genomeproteins{$ret[1]}}, $ret[0])}
return \%genomeproteins;
}
sub niceexit {
my $reason = shift;
$dbh->disconnect;
if ($reason) {print STDERR $reason; exit(-1)}
else {exit(0)}
}
| linsalrob/bioinformatics | phage_tree/combineprotdists.by.length.compare.pl | Perl | mit | 20,674 |
use strict;
use warnings;
use LWP::UserAgent;
if (scalar @ARGV < 2 or scalar @ARGV > 3) {
print STDERR "Usage: $0 <host> <port> [cafile]\n";
exit 1;
}
my ($host, $port, $cafile) = @ARGV;
my $ua = LWP::UserAgent->new;
if (defined $cafile) {
eval {
$ua->ssl_opts(SSL_ca_file => $cafile);
};
if ($@) {
print "UNSUPPORTED\n";
exit 0;
}
}
my $response = $ua->get("https://$host:$port");
my $client_warning = $response->header('Client-Warning') || '';
if ($client_warning eq 'Internal response') {
if ($response->code == 500 and $response->content =~ m/hostname verification failed|SSL connect/) {
print "REJECT\n";
} else {
print STDERR $response->as_string;
exit 1;
}
} else {
print "ACCEPT\n"
}
| ouspg/trytls | stubs/perl-lwp/run.pl | Perl | mit | 782 |
#!/usr/bin/perl
# Written by Dr. Ken Lunde (lunde@adobe.com)
# Senior Computer Scientist 2, Adobe Inc.
# Version 2019-03-27
#
# This tool lists the glyphs in the specified font, which can be a
# CIDFont resource, a name-keyed Type 1 font (PFA), or an 'sfnt'
# (TrueType or OpenType) font. By default, glyphs are listed as CIDs
# or glyph names, depending on whether the font is CID- or name-keyed.
# CIDs are prefixed with a slash. The "-g" command-line option will
# list GIDs in lieu of CIDs or glyph names. The "-r" command-line
# option will turn the list of CIDs or GIDs into ranges. The "-s"
# command-line option will additionally output lists or ranges onto
# a single line with comma separators so that it can be repurposed, such
# as to be used as the argument of the "-g" or "-gx" command-line
# options that are supported by many AFDKO tools.
#
# Tool Dependencies: tx (AFDKO)
$usegid = $second = $range = 0;
$iscid = 1;
$sep = "\n";
$prefix = "/";
$data = "";
while ($ARGV[0]) {
if ($ARGV[0] =~ /^-[huHU]/) {
print STDERR "Usage: glyph-list.pl [-g] [-r] [-s] <font>\n";
exit;
} elsif ($ARGV[0] =~ /^-[gG]/) {
$usegid = 1;
$prefix = "";
shift;
} elsif ($ARGV[0] =~ /^-[rR]/) {
$range = 1;
shift;
} elsif ($ARGV[0] =~ /^-[sS]/) {
$sep = ",";
shift;
} else {
$file = "\"$ARGV[0]\"";
shift;
}
}
open(FILE,"tx -1 $file |") or die "Cannot open $file input file!\n";
while(defined($line = <FILE>)) {
chomp $line;
if ($line =~ /^sup\.srcFontType/) {
if ($line =~ /(?:TrueType|name-keyed)/) {
$iscid = 0;
$range = 0 if not $usegid;
$prefix = "";
}
next;
}
next if $line !~ /glyph\[\d+\]/;
if ($usegid) {
($glyph) = $line =~ /glyph\[(\d+)\]/;
} else {
($glyph) = $line =~ /{(.+?),/;
}
if ($range) {
if (not $second) {
$orig = $previous = $glyph;
$second = 1;
next;
}
if ($glyph != $previous + 1) {
if ($orig == $previous) {
$data .= "$prefix$orig$sep";
} else {
$data .= "$prefix$orig-$prefix$previous$sep";
}
$orig = $previous = $glyph;
} else {
$previous = $glyph;
}
} else {
if (not $sep) {
$data .= "$prefix$glyph\n";
} else {
if (not $data) {
$data .= "$prefix$glyph";
} else {
$data .= "$sep$prefix$glyph";
}
}
}
}
if ($range) {
if ($orig == $previous) {
$data .= "$prefix$orig\n";
} else {
$data .= "$prefix$orig-$prefix$previous\n";
}
} else {
$data .= "\n";
}
print STDOUT $data;
| adobe-type-tools/perl-scripts | glyph-list.pl | Perl | mit | 2,831 |
##############################################################################
# $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/distributions/Perl-Critic/lib/Perl/Critic/Policy/ControlStructures/ProhibitUnlessBlocks.pm $
# $Date: 2012-07-02 22:16:39 -0700 (Mon, 02 Jul 2012) $
# $Author: thaljef $
# $Revision: 4126 $
##############################################################################
package Perl::Critic::Policy::ControlStructures::ProhibitUnlessBlocks;
use 5.006001;
use strict;
use warnings;
use Readonly;
use Perl::Critic::Utils qw{ :severities };
use base 'Perl::Critic::Policy';
our $VERSION = '1.118';
#-----------------------------------------------------------------------------
Readonly::Scalar my $DESC => q{"unless" block used};
Readonly::Scalar my $EXPL => [ 97 ];
#-----------------------------------------------------------------------------
sub supported_parameters { return () }
sub default_severity { return $SEVERITY_LOW }
sub default_themes { return qw(core pbp cosmetic) }
sub applies_to { return 'PPI::Statement::Compound' }
#-----------------------------------------------------------------------------
sub violates {
my ( $self, $elem, undef ) = @_;
if ( $elem->first_element() eq 'unless' ) {
return $self->violation( $DESC, $EXPL, $elem );
}
return; #ok!
}
1;
__END__
#-----------------------------------------------------------------------------
=pod
=head1 NAME
Perl::Critic::Policy::ControlStructures::ProhibitUnlessBlocks - Write C<if(! $condition)> instead of C<unless($condition)>.
=head1 AFFILIATION
This Policy is part of the core L<Perl::Critic|Perl::Critic>
distribution.
=head1 DESCRIPTION
Conway discourages using C<unless> because it leads to
double-negatives that are hard to understand. Instead, reverse the
logic and use C<if>.
unless($condition) { do_something() } #not ok
unless(! $no_flag) { do_something() } #really bad
if( ! $condition) { do_something() } #ok
This Policy only covers the block-form of C<unless>. For the postfix
variety, see C<ProhibitPostfixControls>.
=head1 CONFIGURATION
This Policy is not configurable except for the standard options.
=head1 SEE ALSO
L<Perl::Critic::Policy::ControlStructures::ProhibitPostfixControls|Perl::Critic::Policy::ControlStructures::ProhibitPostfixControls>
=head1 AUTHOR
Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>
=head1 COPYRIGHT
Copyright (c) 2005-2011 Imaginative Software Systems. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. The full text of this license
can be found in the LICENSE file included with this module.
=cut
# Local Variables:
# mode: cperl
# cperl-indent-level: 4
# fill-column: 78
# indent-tabs-mode: nil
# c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/Perl/Critic/Policy/ControlStructures/ProhibitUnlessBlocks.pm | Perl | mit | 3,000 |
# Copyright (c) 2009-2015 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
=pod
=head1 NAME
Date::Manip::Migration5to6 - how to upgrade from 5.xx to 6.00
=head1 SYNOPSIS
When upgrading from Date::Manip 5.xx to 6.00, a few changes may be
necessary to your scripts.
The L<Date::Manip::Changes5to6> document lists in more detail the ways in
which Date::Manip changed, but very few of these actually entail
changes to your script.
It should be noted that once the changes are made to your script,
it will no longer run correctly in 5.xx.
=head1 NECESSARY AND SUGGESTED CHANGES
The following changes are necessary, or strongly suggested:
=over 4
=item B<Reading config files with Date_Init>
If you use Date_Init to read any config files (if you do business mode
calculations, you probably do), you should remove all of the following
config variables from your call to Date_Init:
GlobalCnf=FILE
PersonalCnf=FILE
PathSep=*
IgnoreGlobalCnf=*
PersonalCnfPath=*
and replace them with:
ConfigFile=FILE
where FILE is now the full path to a config file. Also, the ConfigFile
argument should be the first argument in Date_Init.
=item B<Date_ConvTZ>
The Date_ConvTZ function has changed. It should now take 3 arguments:
$date = Date_ConvTZ($date,$from,$to);
If C<$from> is not given, it defaults to the local time zone. If C<$to> is
not given, it defaults to the local time zone.
The date is converted from the C<$from> time zone into the C<$to>
time zone. Both should be any time zone (or alias) supported by
Date::Manip.
The old C<$errlevel> argument is no longer handled.
=item B<ConvTZ and TZ config variables>
If you use either the ConvTZ or TZ config variables, you should
replace them with either SetDate or ForceDate. See the
L<Date::Manip::Config> document for information.
The TZ variable will continue to work until Dec 2015 at which point
it will be removed.
=item B<Other deprecated config variables>
The following config variables have been deprecated, but will continue
to function (though they will be removed at a future date):
TZ (removed Mar 2016)
The following variables have been removed. If you use any of them,
you may need to modify your scripts:
IntCharSet
GlobalCnf
PersonalCnf
PathSep
IgnoreGlobalCnf
PersonalCnfPath
ConvTZ
Internal
TodayIsMidnight
DeltaSigns
UpdateCurrTZ
ResetWorkdDay
=item B<today, yesterday, tomorrow>
If you parse the strings "today", "yesterday", or "tomorrow" in order
to get the time now, or 24 hours in the past/future, this will no
longer work. These strings now refer strictly to the date (so "today"
is the current day at midnight, "yesterday" is the previous day at
midnight, etc.).
To get the time now, 24 hours ago, or 24 hours in the future, you
would need to parse the strings "now", "-24:00:00", or "+24:00:00"
respectively.
=item B<Do not use Memoize>
In 5.xx, it was documented that you could use the module Memoize to
speed up Date::Manip, especially when sorting dates.
This information is no longer accurate. Using Memoize in conjunction
with Date::Manip should have little impact on performance, and may
lead to incorrect results, especially if you change config variables.
Please refer to L<Date::Manip::Changes5to6/"GENERAL CHANGES"> for
more information.
=back
If you find other instances where it is necessary to modify your
script, please email me so that I can add that information to this
document.
=head1 BUGS AND QUESTIONS
Please refer to the L<Date::Manip::Problems> documentation for
information on submitting bug reports or questions to the author.
=head1 SEE ALSO
L<Date::Manip> - main module documentation
=head1 LICENSE
This script is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 AUTHOR
Sullivan Beck (sbeck@cpan.org)
=cut
| jkb78/extrajnm | local/lib/perl5/Date/Manip/Migration5to6.pod | Perl | mit | 3,972 |
package GD::Barcode;
require Exporter;
use strict;
use vars qw($VERSION @ISA $errStr);
@ISA = qw(Exporter);
$VERSION=1.15;
my @aLoaded = ();
#------------------------------------------------------------------------------
# new (for GD::Barcode)
#------------------------------------------------------------------------------
sub new($$$;$) {
my($sClass, $sType, $sTxt, $rhPrm) = @_;
my $oThis = {};
unless(grep(/^$sType$/, @aLoaded)) {
eval "require 'GD/Barcode/$sType.pm';";
if($@) {
$errStr = "Can't load $sType : $@";
return undef;
}
push(@aLoaded, $sType);
}
bless $oThis, "GD::Barcode::$sType";
return undef if($errStr = $oThis->init($sTxt, $rhPrm));
return $oThis;
}
#------------------------------------------------------------------------------
# barPtn (for GD::Barcode)
#------------------------------------------------------------------------------
sub barPtn {
my($bar, $table) = @_;
my($sWk, $sRes);
$sRes = '';
foreach $sWk (split(//, $bar)) {
$sRes .= $table->{$sWk};
}
return $sRes;
}
#------------------------------------------------------------------------------
# dumpCode (for GD::Barcode) for Code39, NW7...
#------------------------------------------------------------------------------
sub dumpCode {
my( $sCode ) = @_;
my($sWk, $sRes, $sClr);
#Init
$sRes = '';
$sClr = '1'; # 1: Black, 0:White
foreach $sWk (split(//, $sCode)) {
$sRes .= ($sWk eq '1')? $sClr x 3 : $sClr; #3 times or Normal
$sClr = ($sClr eq '0')? '1': '0';
}
return $sRes;
}
#------------------------------------------------------------------------------
# plot (for GD::Barcode)
#------------------------------------------------------------------------------
sub plot($$$$$) {
my($sBarcode, $iWidth, $iHeight, $fH, $iStart) = @_;
#Create Image
my ($gdNew, $cWhite, $cBlack);
eval {
$gdNew = GD::Image->new($iWidth, $iHeight);
$cWhite = $gdNew->colorAllocate(255, 255, 255);
$cBlack = $gdNew->colorAllocate( 0, 0, 0);
my $iPos =$iStart;
foreach my $cWk (split(//,$sBarcode)) {
if($cWk eq '0') {
$gdNew->line($iPos, 0, $iPos, $iHeight - $fH, $cWhite);
}
elsif ($cWk eq 'G') {
$gdNew->line($iPos, 0, $iPos, $iHeight - 2*($fH/3), $cBlack);
}
else { #$cWk eq "1" etc.
$gdNew->line($iPos, 0, $iPos, $iHeight - $fH, $cBlack);
}
$iPos++;
}
};
return ($gdNew, $cBlack);
}
#------------------------------------------------------------------------------
# Text (for GD::Barcode)
#------------------------------------------------------------------------------
sub Text($) {
my($oThis) = @_;
return $oThis->{text};
}
1;
__END__
=head1 NAME
GD::Barcode - Create barcode image with GD
=head1 SYNOPSIS
I<ex. CGI>
use GD::Barcode::UPCE;
binmode(STDOUT);
print "Content-Type: image/png\n\n";
print GD::Barcode->new('EAN13', '123456789012')->plot->png;
I<with Error Check>
my $oGdBar = GD::Barcode->new('EAN13', '12345678901');
die $GD::Barcode::errStr unless($oGdBar); #Invalid Length
$oGdBar->plot->png;
=head1 DESCRIPTION
GD::Barcode is a subclass of GD and allows you to create barcode image with GD.
This module based on "Generate Barcode Ver 1.02 By Shisei Hanai 97/08/22".
From 1.14, you can use this module even if no GD (except plot method).
=head2 new
I<$oGdBar> = GD::Barcode::UPCE->new(I<$sType>, I<$sTxt>);
Constructor.
Creates a GD::Barcode::I<$sType> object for I<$sTxt>.
=head2 plot()
I<$oGd> = $oGdBar->plot([Height => I<$iHeight>, NoText => I<0 | 1>]);
creates GD object with barcode image for the I<$sTxt> specified at L<new> method.
I<$iHeight> is height of the image. If I<NoText> is 1, the image has no text image of I<$sTxt>.
ex.
my $oGdB = GD::Barcode->new('EAN13', '123456789012');
my $oGD = $oGdB->plot(NoText=>1, Height => 20);
# $sGD is a GD image with Height=>20 pixels, with no text.
=head2 barcode()
I<$sPtn> = $oGdBar->barcode();
returns a barcode pattern in string with '1' and '0'.
'1' means black, '0' means white.
ex.
my $oGdB = GD::Barcode->new('UPCE', '123456789012');
my $sPtn = $oGdB->barcode();
# $sPtn = '';
=head2 $errStr
$GD::Barcode::errStr
has error message.
=head2 $text
$oGdBar->{$text}
has barcode text based on I<$sTxt> specified in L<new> method.
=head1 AUTHOR
Kawai Takanori GCD00051@nifty.ne.jp
=head1 COPYRIGHT
The GD::Barocde module is Copyright (c) 2000 Kawai Takanori. Japan.
All rights reserved.
You may distribute under the terms of either the GNU General Public
License or the Artistic License, as specified in the Perl README file.
=head1 SEE ALSO
GD GD::Barcode subclasses
=cut
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/GD/Barcode.pm | Perl | mit | 4,909 |
# Copyright (c) 2010 - Action Without Borders
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#=====================================
# Qualifier
# Abstracts SQL qualifiers
# into a tree-based system of
# related qualifiers
package IF::Qualifier;
use strict;
use vars qw($QUALIFIER_TYPES @QUALIFIER_OPERATORS $QUALIFIER_REGEX);
use base qw(
IF::Interface::SQLGeneration
);
use IF::Log;
use IF::DB;
use IF::Model;
use IF::Relationship::Derived;
use IF::Relationship::Modelled;
use IF::Utility;
$QUALIFIER_TYPES = {
"AND" => 1,
"OR" => 2,
"KEY" => 3,
"SQL" => 4,
"MATCH" => 5,
};
@QUALIFIER_OPERATORS = (
"=",
'>=',
'<=',
'<>',
'>',
'<',
'!=',
'LIKE',
'REGEXP',
'IN',
'NOT IN',
'IS',
'IS NOT',
);
$QUALIFIER_REGEX = "(".join("|", @QUALIFIER_OPERATORS).")";
# Class Methods
sub new {
my $className = shift;
my $qualifierType = shift;
# decide if the type's valid
return undef unless ($QUALIFIER_TYPES->{$qualifierType});
my $self = {
type => $qualifierType,
_bindValues => [],
_requiresRepeatedJoin => 0,
};
if ($qualifierType eq "KEY") {
$self->{condition} = shift;
# this is bogus because there can only be one bindvalue per qualifier
foreach my $bindValue (@_) {
push (@{$self->{_bindValues}}, $bindValue);
}
} elsif ($qualifierType eq "AND" || $qualifierType eq "OR" || $qualifierType eq "NOT") {
my $qualifiers = shift;
return undef unless $qualifiers;
return $qualifiers->[0] unless (scalar @$qualifiers > 1);
my $validQualifiers = [];
foreach my $q (@$qualifiers) {
next unless $q;
push @$validQualifiers, $q;
}
$self->{subQualifiers} = $validQualifiers;
} elsif ($qualifierType eq "SQL") {
$self->{condition} = shift;
} elsif ($qualifierType eq "MATCH") {
# form is
# IF::Qualifier->match("attribute, attribute, ...", "terms")
# where, if the attribute list is empty, we'll use all text attributes
# in the entity. "terms" must be present and can use boolean
# terms (in the expected MySQL format).
$self->{_attributes} = [split(/,\s*/, shift)];
$self->{_terms} = shift;
}
return bless $self, $className;
}
# helper constructors:
# these should clean up the consumers a tad
sub key {
my $className = shift;
return $className->new("KEY", @_);
}
sub and {
my $className = shift;
return $className->new("AND", @_);
}
sub or {
my $className = shift;
return $className->new("OR", @_);
}
sub not {
my $className = shift;
return $className->new("NOT", @_);
}
sub sql {
my $className = shift;
return $className->new("SQL", @_);
}
sub match {
my $className = shift;
return $className->new("MATCH", @_);
}
#--- instance methods ----
sub requiresRepeatedJoin {
my ($self) = @_;
$self->{_requiresRepeatedJoin} = 1;
return $self;
}
sub setEntity {
my $self = shift;
my $entity = shift;
foreach my $subQualifier (@{$self->{subQualifiers}}) {
$subQualifier->setEntity($entity);
}
$self->{entity} = $entity;
}
sub entity {
my $self = shift;
return $self->{entity};
}
sub sqlWithBindValuesForExpressionAndModel {
my ($self, $sqlExpression, $model) = @_;
return $self->sqlWithBindValuesForExpressionAndModelAndClause($sqlExpression, $model, "WHERE");
}
sub sqlWithBindValuesForExpressionAndModelAndClause {
my ($self, $sqlExpression, $model, $clause) = @_;
# This whole thing needs to be refactored
if ($self->{type} eq "AND" || $self->{type} eq "OR") {
#IF::Log::debug("Found AND or OR qualifier");
my $subQualifierSQL = [];
my $subQualifierBindValues = [];
foreach my $subQualifier (@{$self->{subQualifiers}}) {
my $subQualifierSQLWithBindValues =
$subQualifier->sqlWithBindValuesForExpressionAndModelAndClause(
$sqlExpression, $model, $clause
);
push (@$subQualifierSQL, $subQualifierSQLWithBindValues->{SQL});
push (@$subQualifierBindValues, @{$subQualifierSQLWithBindValues->{BIND_VALUES}});
}
my $qualifierAsSQL = "(".join (" ".$self->{type}." ", @$subQualifierSQL).")";
if ($self->isNegated()) {
$qualifierAsSQL = " NOT ($qualifierAsSQL) ";
}
return {
SQL => $qualifierAsSQL,
BIND_VALUES => $subQualifierBindValues,
};
}
if ($self->{type} eq "KEY" || $self->{type} eq "SQL") {
if ($clause eq "HAVING") {
return $self->translateIntoHavingSQLExpressionForModel($sqlExpression, $model);
}
return $self->translateConditionIntoSQLExpressionForModel($sqlExpression, $model);
}
# hacking the match type in here. see the note above about
# this needing to be refactored.
if ($self->{type} eq "MATCH") {
return $self->translateConditionIntoMatchExpressionForModel($sqlExpression, $model);
}
}
# What a friggin mouthful. I just had to pull this crap out
# and isolate it from the rest of the goop. This will get
# rewritten at a later date...
sub _translateQualifierWithGoo {
my ($self, $qualifierKey, $relationship, $targetEntity, $model, $sqlExpression, $operator, $value) = @_;
my $aggregatorOperator;
my $qualifierOperator;
if ($operator eq "<>") {
$aggregatorOperator = "NOT IN";
$qualifierOperator = "=";
} elsif ($operator eq "IS NOT") {
$aggregatorOperator = "NOT IN";
$qualifierOperator = "IS";
} else {
$aggregatorOperator = "IN";
$qualifierOperator = $operator;
}
my $qualifiers = [];
if ($relationship->qualifier()) {
push (@$qualifiers, $relationship->qualifier());
}
my $rsa = $relationship->sourceAttribute();
my $rta = $relationship->targetAttribute();
my $groupingQualifier;
if ($qualifierKey eq "creationDate" || $qualifierKey eq "modificationDate") {
$groupingQualifier = IF::Qualifier->key($rsa." $aggregatorOperator %@",
IF::FetchSpecification->new($targetEntity->name(),
IF::Qualifier->and([
@$qualifiers,
IF::Qualifier->key("$qualifierKey $qualifierOperator $value"),
]),
)->subqueryForAttributes([$rta])
);
} else {
$groupingQualifier = IF::Qualifier->key($rsa." $aggregatorOperator %@",
IF::FetchSpecification->new($targetEntity->name(),
IF::Qualifier->and([
@$qualifiers,
IF::Qualifier->key($targetEntity->aggregateKeyName()." = %@", $qualifierKey),
IF::Qualifier->key($targetEntity->aggregateValueName()." $qualifierOperator $value"),
]),
)->subqueryForAttributes([$rta])
);
}
$groupingQualifier->setEntity($self->entity());
my $bindValues = $self->{_bindValues};
my $subquery = $groupingQualifier->translateConditionIntoSQLExpressionForModel($sqlExpression, $model);
return {
SQL => $subquery->{SQL},
BIND_VALUES => [ @{$subquery->{BIND_VALUES}}, @{$self->{_bindValues}}],
};
}
# this breaks down the keypath by traversing it from relationship
# to relationship, and returns the target ecd and attribute
# TODO rewrite the translation code to use this. That's a bit
# tricky because it'll require some stuff to be done during keypath
# traversal
sub _parseKeyPathOnEntityClassDescriptionWithSQLExpressionAndModel {
my ($self, $keyPath, $ecd, $sqlExpression, $model) = @_;
my $oecd = $ecd; # original ecd
my $cecd = $ecd; # current ecd
# Figure out the target ecd for the qualifier by looping through the keys in the path
my $bits = [split(/\./, $keyPath)];
if (scalar @$bits == 0) {
$bits = [$keyPath];
}
my $qualifierKey;
#$DB::single = 1;
for my $i (0..$#$bits) {
$qualifierKey = $bits->[$i];
#IF::Log::debug("Checking $qualifierKey");
# if it's the last key in the path, bail now
last if ($i >= $#$bits);
# otherwise, look up the relationship
my $relationship = $cecd->relationshipWithName($qualifierKey);
# if there's no such relationship, it might be a derived data source
# so check for that
unless ($relationship) {
#IF::Log::debug("Grabbing derived source with name $qualifierKey");
$relationship = $sqlExpression->derivedDataSourceWithName($qualifierKey);
}
unless (IF::Log::assert($relationship, "Relationship $qualifierKey exists on entity ".$cecd->name())) {
$relationship = $sqlExpression->dynamicRelationshipWithName($qualifierKey);
#IF::Log::error("Using dynamic relationship");
}
unless ($relationship) {
return {};
}
my $tecd = $relationship->targetEntityClassDescription($model);
return {} unless (IF::Log::assert($tecd, "Target entity class ".$relationship->targetEntity()." exists"));
if ($tecd->isAggregateEntity()) {
# We just bail on it if it's aggregate
# TODO see if there's a way to insert an aggregate qualifier into the key path
return {};
}
# follow it
$cecd = $tecd;
}
#IF::Log::debug("Returning ".$cecd->name()." with attribute $qualifierKey");
return {
TARGET_ENTITY_CLASS_DESCRIPTION => $cecd,
TARGET_ATTRIBUTE => $qualifierKey,
};
}
# This is a bit of a mess because it actually assumes that the
# derived source is >first< right now, as in
# "DerivedSource.foo = id" whereas it should allow the
# derived source to be anywhere in the key path.
sub translateDerivedRelationshipQualifierIntoSQLExpressionForModel {
my ($self, $relationship, $sqlExpression, $model) = @_;
my ($sourceKeyPath, $operator, $subqueryOperator, $targetKeyPath) =
($self->{condition} =~ /^\s*([\w\._-]+)\s*$QUALIFIER_REGEX\s*(ANY|ALL|SOME)?(.*)$/i);
my $recd = $model->entityClassDescriptionForEntityNamed($self->{entity});
my $sourceGoo = $self->_parseKeyPathOnEntityClassDescriptionWithSQLExpressionAndModel(
$sourceKeyPath,
$recd,
$sqlExpression,
$model);
my $rhs = $targetKeyPath;
if (IF::Utility::expressionIsKeyPath($targetKeyPath)) {
my $targetGoo = $self->_parseKeyPathOnEntityClassDescriptionWithSQLExpressionAndModel(
$targetKeyPath,
$recd,
$sqlExpression,
$model);
if (my $rtecd = $targetGoo->{TARGET_ENTITY_CLASS_DESCRIPTION}) {
# create SQL for the qualifier on >that< entity
my $tableName = $rtecd->_table();
my $columnName = $rtecd->columnNameForAttributeName($targetGoo->{TARGET_ATTRIBUTE});
if ($sqlExpression->hasSummaryAttributeForTable($targetGoo->{TARGET_ATTRIBUTE}, $tableName)) {
$columnName = $sqlExpression->aliasForSummaryAttributeOnTable($targetGoo->{TARGET_ATTRIBUTE}, $tableName);
}
IF::Log::debug("Right target table name is $tableName");
my $tableAlias = $sqlExpression->aliasForTable($tableName);
$rhs = $tableAlias.".".$columnName;
}
}
my $secd = $sourceGoo->{TARGET_ENTITY_CLASS_DESCRIPTION};
#my $tableName = $secd->_table();
#my $columnName = $secd->columnNameForAttributeName($sourceGoo->{TARGET_ATTRIBUTE});
#if ($sqlExpression->hasSummaryAttributeForTable($sourceGoo->{TARGET_ATTRIBUTE}, $tableName)) {
# $columnName = $sqlExpression->aliasForSummaryAttributeOnTable($sourceGoo->{TARGET_ATTRIBUTE}, $tableName);
#}
my $tableAlias = $sqlExpression->aliasForTable($relationship->name());
my $itn = $relationship->fetchSpecification()->entityClassDescription()->_table();
IF::Log::debug("Looking for $sourceGoo->{TARGET_ATTRIBUTE} on $itn");
my $columnName = $relationship->fetchSpecification()->entityClassDescription()->columnNameForAttributeName($sourceGoo->{TARGET_ATTRIBUTE});
$columnName = $relationship->fetchSpecification()->sqlExpression()->aliasForColumnOnTable(
$columnName,
$itn
);
unless ($columnName) {
if ($relationship->fetchSpecification()->sqlExpression()->hasSummaryAttributeForTable(
$sourceGoo->{TARGET_ATTRIBUTE},
$relationship->fetchSpecification()->entityClassDescription()->_table())) {
$columnName = $relationship->fetchSpecification()->sqlExpression()->aliasForSummaryAttributeOnTable(
$sourceGoo->{TARGET_ATTRIBUTE},
$relationship->fetchSpecification()->entityClassDescription()->_table());
} else {
IF::Log::debug("Couldn't find alias for column $sourceGoo->{TARGET_ATTRIBUTE}");
}
}
my $lhs = $tableAlias.".".$columnName;
return { SQL => join(" ", $lhs, $operator, $subqueryOperator, $rhs), BIND_VALUES => $self->{_bindValues} };
}
# TODO move this method into a subclass of IF::Qualifier
# for match qualifiers
sub translateConditionIntoMatchExpressionForModel {
my ($self, $sqlExpression, $model) = @_;
my $ecd = $model->entityClassDescriptionForEntityNamed($self->{entity});
return {} unless (IF::Log::assert($ecd, "Entity class description exists for $self->{entity}"));
my $oecd = $ecd; # original ecd
my $cecd = $ecd; # current ecd
# figure out the attributes
my $attributes = $self->{_attributes} || [];
if (scalar @$attributes == 0) {
foreach my $attribute (@{$oecd->allAttributes()}) {
next unless $attribute->{TYPE} =~ /(CHAR|TEXT|BLOB)/i;
push @$attributes, $attribute->{NAME};
}
}
my $mappedAttributes = [];
# calculate attributes by walking the key paths... is this even valid?
foreach my $attributeName (@$attributes) {
my $targetGoo = $self->_parseKeyPathOnEntityClassDescriptionWithSQLExpressionAndModel(
$attributeName, $oecd, $sqlExpression, $model);
if (my $tecd = $targetGoo->{TARGET_ENTITY_CLASS_DESCRIPTION}) {
my $tableName = $tecd->_table();
my $columnName = $tecd->columnNameForAttributeName($targetGoo->{TARGET_ATTRIBUTE});
# if ($sqlExpression->hasSummaryAttributeForTable($targetGoo->{TARGET_ATTRIBUTE}, $tableName)) {
# $columnName = $sqlExpression->aliasForSummaryAttributeOnTable($targetGoo->{TARGET_ATTRIBUTE}, $tableName);
# }
#IF::Log::debug("Full-text match target table name is $tableName, column is $columnName");
my $tableAlias = $sqlExpression->aliasForTable($tableName);
push @$mappedAttributes, "$tableAlias.$columnName";
}
}
IF::Log::dump("Matching on ".join(", ", @$mappedAttributes));
# TODO escape terms here.
my $terms = [split(/\s+/, $self->{_terms})];
return {
SQL => "MATCH(".join(", ", @$mappedAttributes).") AGAINST (? IN BOOLEAN MODE)",
BIND_VALUES => [join(" ", @$terms)],
};
}
# This is truly a rat's nest. I need to gut and rewrite this
# ASAP...
sub translateConditionIntoSQLExpressionForModel {
my ($self, $sqlExpression, $model) = @_;
# short-circuit qualifiers that don't need to be translated.
# TODO : rework the SQL in these to use the table aliases
if ($self->{type} eq "SQL") {
return {
SQL => $self->{condition},
BIND_VALUES => [],
};
}
# There are three parts to a key-qualifier:
# 1. key path
# 2. operator
# 3. values
my ($keyPath, $operator, $subqueryOperator, $value) = ($self->{condition} =~ /^\s*([\w\._-]+)\s*$QUALIFIER_REGEX\s*(ANY|ALL|SOME)?(.*)$/i);
my $ecd = $model->entityClassDescriptionForEntityNamed($self->{entity});
return {} unless (IF::Log::assert($ecd, "Entity class description exists for $self->{entity} for $self->{condition}"));
my $oecd = $ecd; # original ecd
my $cecd = $ecd; # current ecd
# Figure out the target ecd for the qualifier by looping through the keys in the path
my $bits = [split(/\./, $keyPath)];
#IF::Log::debug("Bits from $keyPath");
#IF::Log::dump($bits);
if (scalar @$bits == 0) {
$bits = [$keyPath];
}
my $qualifierKey;
my $deferredJoins = [];
for my $i (0..$#$bits) {
$qualifierKey = $bits->[$i];
# if it's the last key in the path, bail now
last if ($i >= $#$bits);
# otherwise, look up the relationship
my $relationship = $cecd->relationshipWithName($qualifierKey);
# if there's no such relationship, it might be a derived data source
# so check for that
unless ($relationship) {
$relationship = $sqlExpression->derivedDataSourceWithName($qualifierKey);
# short circuit the rest of the loop if it's a derived
# relationship because we don't need to add any
# relationship traversal info to the sqlExpression
if ($relationship) {
return $self->translateDerivedRelationshipQualifierIntoSQLExpressionForModel($relationship, $sqlExpression, $model);
}
}
unless ($relationship) {
$relationship = $sqlExpression->dynamicRelationshipWithName($qualifierKey);
#IF::Log::debug("Using dynamic relationship");
}
unless (IF::Log::assert($relationship, "Relationship $qualifierKey exists on entity ".$cecd->name())) {
return {
SQL => "", BIND_VALUES => [],
};
}
my $tecd = $relationship->targetEntityClassDescription($model);
return {} unless (IF::Log::assert($tecd, "Target entity class ".$relationship->targetEntity()." exists"));
if ($tecd->isAggregateEntity()) {
# We just bail on it if it's aggregate
# TODO see if there's a way to insert an aggregate qualifier into the key path
return $self->_translateQualifierWithGoo(
$bits->[$i+1],
$relationship,
$tecd,
$model,
$sqlExpression,
$operator,
$value
);
}
# add traversed relationships to the SQL expression
if ($self->{_requiresRepeatedJoin}) {
push (@$deferredJoins, { ecd => $cecd, key => $qualifierKey });
} else {
$sqlExpression->addTraversedRelationshipOnEntity($qualifierKey, $cecd);
}
# follow it
$cecd = $tecd;
}
# create SQL for the qualifier on >that< entity
my $tableName = $cecd->_table();
my $columnName = $cecd->columnNameForAttributeName($qualifierKey);
if ($sqlExpression->hasSummaryAttributeForTable($qualifierKey, $tableName)) {
$columnName = $sqlExpression->aliasForSummaryAttributeOnTable($qualifierKey, $tableName);
}
my $tn = $tableName;
# XXX! Kludge! XXX!
if ($self->{_requiresRepeatedJoin}) {
$tn = $sqlExpression->addRepeatedTable($tn);
}
my $tableAlias = $sqlExpression->aliasForTable($tn);
IF::Log::assert($tableAlias, "Alias for table $tn is $tableAlias");
my $conditionInSQL;
my $bindValues;
if ($self->hasSubQuery()) {
my $subquery = $value;
my $sqlWithBindValues = $self->subQuery()->toSQLFromExpression();
$subquery =~ s/\%\@/\($sqlWithBindValues->{SQL}\)/;
$conditionInSQL = "$tableAlias.$columnName $operator $subqueryOperator $subquery";
$bindValues = $sqlWithBindValues->{BIND_VALUES};
} else {
my $aggregateColumns = {
uc($oecd->aggregateKeyName()) => 1,
uc($oecd->aggregateValueName()) => 1,
"creationDate" => 1,
"modificationDate" => 1,
};
if ($oecd->isAggregateEntity()
&& !$aggregateColumns->{uc($columnName)}
&& !$oecd->_primaryKey()->hasKeyField(uc($columnName))) {
$conditionInSQL = "$tableAlias.".$oecd->aggregateKeyName().
" = %@ AND $tableAlias.".$oecd->aggregateValueName().
" $operator $value";
$bindValues = [$columnName, @{$self->{_bindValues}}];
} else {
#IF::Log::debug("MEOW $value");
# TODO... I am pretty sure this code is redundant now;
# the code above takes care of resolving the key paths now.
if (IF::Utility::expressionIsKeyPath($value)) {
IF::Log::debug("key path");
my $targetGoo = $self->_parseKeyPathOnEntityClassDescriptionWithSQLExpressionAndModel(
$value,
$ecd,
$sqlExpression,
$model);
my $tecd = $targetGoo->{TARGET_ENTITY_CLASS_DESCRIPTION};
my $ta = $targetGoo->{TARGET_ATTRIBUTE};
if ($tecd) {
my $tn = $ecd->_table();
# XXX! Kludge! XXX!
if ($self->{_requiresRepeatedJoin}) {
# add that to the fetch representation
$tn = $sqlExpression->addRepeatedTable($tn);
}
my $targetTableAlias = $sqlExpression->aliasForTable($tn);
my $targetColumnName = $sqlExpression->aliasForColumnOnTable($ta, $ecd->_table());
$value = "$targetTableAlias.$targetColumnName";
}
}
$conditionInSQL = "$tableAlias.$columnName $operator $value";
$bindValues = $self->{_bindValues};
}
$conditionInSQL =~ s/\%\@/\?/g;
}
# hack to add a join to a repeated qualifier
foreach my $j (@$deferredJoins) {
IF::Log::debug("Adding repeated join on ".$j->{ecd}->name()." with key $j->{key}");
$sqlExpression->addRepeatedTraversedRelationshipOnEntity($j->{key}, $j->{ecd});
}
return {
SQL => $conditionInSQL,
BIND_VALUES => $bindValues,
};
}
# TODO: Slated for rewrite to bring it up to date with
# the method above.
sub translateIntoHavingSQLExpressionForModel {
my $self = shift;
my $sqlExpression = shift;
my $model = shift;
if ($self->{type} eq "SQL") {
return {
SQL => $self->{condition},
BIND_VALUES => [],
};
}
my $conditionInSQL = "";
my $bindValues;
foreach my $operator (@QUALIFIER_OPERATORS) {
next unless ($self->{condition} =~ /^\s*([\w\.]+)\s*$operator\s*(ANY|ALL|SOME)?(.*)$/i);
my $key = $1;
my $subqueryOperator = $2;
my $value = $3;
# check key for compound construct
my @keyPathElements = split (/\./, $key);
my $entityClassDescription = $model->entityClassDescriptionForEntityNamed($self->{entity});
if ($entityClassDescription->isAggregateEntity()) {
$entityClassDescription = $entityClassDescription->aggregateEntityClassDescription();
}
my ($tableName, $columnName, $columnAlias);
if ($#keyPathElements > 0) {
# traversing a relationship
my $relationshipName = $keyPathElements[0];
my $relationshipKey = $keyPathElements[1];
IF::Log::debug("Relationship is named $relationshipName, entity is $self->{entity}");
my $relationship = $model->relationshipWithNameOnEntity($relationshipName, $self->{entity});
#IF::Log::dump($relationship);
my $targetEntity = $model->entityClassDescriptionForEntityNamed($relationship->{TARGET_ENTITY});
unless ($targetEntity) {
IF::Log::error("No target entity found for qualifier $self->{condition} on $self->{entity}");
last;
}
if ($targetEntity->isAggregateEntity()) {
IF::Log::debug("Target entity is aggregate");
my $aggregatorOperator;
my $qualifierOperator;
if ($operator eq "<>") {
$aggregatorOperator = "NOT IN";
$qualifierOperator = "=";
} elsif ($operator eq "IS NOT") {
$aggregatorOperator = "NOT IN";
$qualifierOperator = "IS";
} else {
$aggregatorOperator = "IN";
$qualifierOperator = $operator;
}
my $groupingQualifier = IF::Qualifier->key($relationship->{SOURCE_ATTRIBUTE}." $aggregatorOperator %@",
IF::FetchSpecification->new($targetEntity->name(),
IF::Qualifier->and([
IF::Qualifier->key($targetEntity->aggregateKeyName()." = %@", $relationshipKey),
IF::Qualifier->key($targetEntity->aggregateValueName()." $qualifierOperator $value"),
]),
)->subqueryForAttributes([$relationship->{TARGET_ATTRIBUTE}])
);
$groupingQualifier->setEntity($self->entity());
my $bindValues = $self->{_bindValues};
my $subquery = $groupingQualifier->translateConditionIntoSQLExpressionForModel($sqlExpression, $model);
return {
SQL => $subquery->{SQL},
BIND_VALUES => [ @{$subquery->{BIND_VALUES}}, @{$self->{_bindValues}}],
};
} else {
$sqlExpression->addTraversedRelationshipOnEntity($relationshipName, $entityClassDescription);
$tableName = $targetEntity->_table();
$columnName = $targetEntity->columnNameForAttributeName($relationshipKey);
}
} else {
$columnName = $entityClassDescription->columnNameForAttributeName($key);
$tableName = $entityClassDescription->_table();
}
if ($sqlExpression->hasColumnForTable($columnName, $tableName)) {
$columnAlias = $sqlExpression->aliasForColumnOnTable($columnName, $tableName);
} elsif ($sqlExpression->hasSummaryAttributeForTable($columnName, $tableName)) {
$columnAlias = $sqlExpression->aliasForSummaryAttributeOnTable($columnName, $tableName);
} else {
IF::Log::error("Can't locate attribute $columnName for table $tableName");
}
if ($self->hasSubQuery()) {
my $subquery = $value;
my $sqlWithBindValues = $self->subQuery()->toSQLFromExpression();
$subquery =~ s/\%\@/\($sqlWithBindValues->{SQL}\)/;
$conditionInSQL = "$columnAlias $operator $subqueryOperator $subquery";
$bindValues = $sqlWithBindValues->{BIND_VALUES};
} else {
$conditionInSQL = "$columnAlias $operator $value";
$conditionInSQL =~ s/\%\@/\?/g;
$bindValues = $self->{_bindValues};
}
last;
}
return {
SQL => $conditionInSQL,
BIND_VALUES => $bindValues,
};
}
sub subQualifiers {
my $self = shift;
return $self->{subQualifiers};
}
sub setSubQualifiers {
my $self = shift;
$self->{subQualifiers} = shift;
}
sub condition {
my $self = shift;
return $self->{condition};
}
sub setCondition {
my $self = shift;
$self->{condition} = shift;
}
sub isNegated {
my $self = shift;
return $self->{isNegated};
}
sub setIsNegated {
my $self = shift;
$self->{isNegated} = shift;
}
sub hasSubQuery {
my $self = shift;
return ($self->subQuery()?1:0);
}
sub subQuery {
my $self = shift;
foreach my $bv (@{$self->{_bindValues}}) {
return $bv if UNIVERSAL::isa($bv, "IF::FetchSpecification");
}
return undef;
}
#----------------------------------------------------
# class methods
sub orQualifierFromMultipleValuesForExpression {
my $values = shift;
my $expression = shift;
return unless (IF::Array::isArray($values) && scalar @$values > 0);
my $qualifiers = [];
foreach my $value (@$values) {
push (@$qualifiers, IF::Qualifier->key($expression, $value));
}
if (scalar @$values == 1) {
return $qualifiers->[0];
}
return IF::Qualifier->or($qualifiers);
}
1;
| quile/if-framework | framework/lib/IF/Qualifier.pm | Perl | mit | 30,324 |
#!/usr/bin/env perl
use Catalyst::ScriptRunner;
Catalyst::ScriptRunner->run('OpenClimateClient', 'CGI');
1;
=head1 NAME
openclimateclient_cgi.pl - Catalyst CGI
=head1 SYNOPSIS
See L<Catalyst::Manual>
=head1 DESCRIPTION
Run a Catalyst application as a CGI script.
=head1 AUTHORS
Catalyst Contributors, see Catalyst.pm
=head1 COPYRIGHT
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
| blakecrosley/openclimate | OpenClimateClient/script/openclimateclient_cgi.pl | Perl | mit | 462 |
/*
verb(X, be) :-
root@X -- [be],
language@X -- english,
X <> [+invertsubj],
cat@THERE -- there,
NP <> [np, theta(exists)],
tverb(X, THERE, NP, 'VB').
*/
verb(X, be) :-
root@X -- [be],
language@X -- english,
-def@X,
-target@X,
PRED <> [+predicative, -zero, saturated, postarg],
+n:xbar@cat@PRED,
theta@PRED -- predication(cat@PRED),
trigger(set:position@moved@PRED, (movedBefore(PRED) -> \+ (n(PRED), subjcase(PRED)); true)),
trigger(start@subject@X, \+ (start@PRED > start@X, start@subject@X > start@PRED)),
trigger(start@subject@X, \+ (start@subject@X > end@X)),
X <> [+invertsubj],
%% [agree] :: [X, PRED],
tverb(X, PRED, 'VB').
verb(X, be) :-
root@X -- [be],
language@X -- english,
trigger((finite@X, tense@X), \+ presPartForm(X)),
finite@COMP -- participle,
tense@COMP -- present,
+def@X,
aux(X, COMP).
verb(X, begin) :-
X <> [sverb(S)],
S <> [toForm],
+zero@subject@S.
verb(X, begin) :-
tverb(X).
verb(X, buy) :-
uverb(X).
verb(X, come) :-
X <> [+active],
tverb(X, ADJ),
ADJ <> [a, theta(cost)],
root@ADJ -- [(cheap>_):adj].
verb(X, come) :-
iverb(X).
verb(X, do) :-
aux(X, S),
X <> [tensedForm],
S <> [infinitiveForm, aspect(simple)].
verb(X, do) :-
tverb(X).
verb(X, do) :-
tverb(X, ADV, 'VD'),
ADV <> [adv, theta(quality)].
verb(X, can) :-
modal(X, S),
X <> [inflected, presTense],
S <> [infinitiveForm],
-zero@subject@S.
verb(X, might) :-
modal(X, S),
X <> [inflected, presTense],
S <> [infinitiveForm],
-zero@subject@S.
verb(X, expect) :-
X <> [sverb(S)],
S <> [tensedForm].
verb(X, expect) :-
X <> [sverb(S)],
S <> [toForm].
verb(X, expect) :-
tverb(X).
verb(X, get) :-
S <> [-active, pastPartForm],
sverb(X, S).
verb(X, get) :-
tverb(X).
verb(X, have) :-
aux(X, S),
X <> [+specified],
S <> [pastPart].
verb(X, have) :-
tverb(X, 'VH').
/*
verb(X, have) :-
sverb(X, S),
S <> [s, -active, presPartForm].
verb(X, have) :-
sverb(X, S),
S <> [s, toForm, -aux],
+zero@subject@S.
*/
verb(X, make) :-
tverb(X).
verb(X, meet) :-
iverb(X),
subject@X <> [plural].
verb(X, meet) :-
tverb(X).
verb(X, use) :-
aux(X, COMP),
COMP <> [toForm].
verb(X, will) :-
aux(X, S),
X <> [tensed, +specified, future, -def],
S <> [infinitiveForm].
verb(X, win) :-
tverb(X).
verb(X, write) :-
tverb(X).
verb(X, write) :-
COMP <> [tensedForm],
sverb(X, COMP).
| AllanRamsay/dgParser | verbs.pl | Perl | mit | 2,593 |
package WWW::Livesite::Args;
use strict;
use Perl::Module;
use Data::OrderedHash;
use Tie::Hash;
use base qw(Tie::ExtraHash);
our $VERSION = 0;
our $Field_Delimiter = '&'; # Used when re-creating the query-string
our $Assignment_Operator = '='; # Used when re-creating the query-string
# ---
sub _unescape {
my $url = shift;
$url =~ tr/+/ /;
$url =~ s/%([a-fA-F0-9]{2})/pack("C",hex($1))/eg;
$url;
}
sub _escape {
my $str = shift;
$str =~ tr/ /+/;
$str =~ s/([^\w\+])/sprintf('%%%02x',ord($1))/eg;
$str;
}
sub _to_param {
my $k = shift;
my $v = shift;
if (isa($v, 'ARRAY')) {
return join $Field_Delimiter, map { $k . $Assignment_Operator . _escape($_) } @$v;
} else {
return $k . $Assignment_Operator . _escape($v);
}
}
# ---
sub new {
my $class = ref($_[0]) ? ref(shift) : shift;
my $self = bless {}, $class;
tie %$self, $class;
return $self->parse(@_);
}
sub parse {
my $self = shift;
%$self = map {_unescape($_);} split /[=&;]/ for @_;
return $self;
}
sub as_string {goto \&to_string}
sub to_string {
my $self = shift;
join $Field_Delimiter, map { _to_param($_, $$self{$_}) } keys %$self;
}
# ---
sub TIEHASH {
my $pkg = shift;
return bless [Data::OrderedHash->new(), @_], $pkg;
}
sub FETCH {
my $k = $_[1];
my $r = $_[0][0]{$k} or return;
return @$r == 1 ? $r->[0] : $r;
}
sub STORE {
my $k = $_[1];
$_[0][0]{$k} ||= [];
return push @{$_[0][0]{$k}}, $_[2];
}
1;
__END__
=pod:summary Case insensitive query string arguemnts
=pod:synopsis
=test(match,hello world)
use WWW::Livesite::Args;
my $qs = WWW::Livesite::Args->new('msg=hello%20world');
die if defined $qs->{MSG};
return $qs->{msg};
=test(match,1|2)
use WWW::Livesite::Args;
my $qs = WWW::Livesite::Args->new('a=1&a=2');
my $a = $qs->{a};
return join '|', @$a;
=pod:description
=cut
| ryangies/lsn-data-hub | src/lib/WWW/Livesite/Args.pm | Perl | mit | 1,859 |
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=pod
=head1 NAME
Bio::EnsEMBL::Compara::Production::EPOanchors::RemoveAnchorOverlaps
=cut
=head1 SYNOPSIS
parameters
{input_analysis_id=> ?,method_link_species_set_id=> ?,input_method_link_species_set_id=> ?, genome_db_ids => [?],}
=cut
=head1 DESCRIPTION
Removes the minimum number of overlappping anchors.
=cut
=head1 CONTACT
ensembl-compara@ebi.ac.uk
=cut
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
package Bio::EnsEMBL::Compara::Production::EPOanchors::RemoveAnchorOverlaps;
use strict;
use Data::Dumper;
use Bio::EnsEMBL::Compara::Production::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Hive::Process;
use Bio::EnsEMBL::Compara::MethodLinkSpeciesSet;
use Bio::EnsEMBL::Compara::Production::EPOanchors::AnchorAlign;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
our @ISA = qw(Bio::EnsEMBL::Hive::Process);
sub configure_defaults {
my $self = shift;
return 1;
}
sub fetch_input {
my ($self) = @_;
$self->configure_defaults();
$self->{'comparaDBA'} = Bio::EnsEMBL::Compara::Production::DBSQL::DBAdaptor->new(-DBCONN=>$self->db->dbc);
$self->{'comparaDBA'}->dbc->disconnect_when_inactive(0);
$self->get_params($self->parameters);
return 1;
}
sub run {
my ($self) = @_;
my $anchor_align_adaptor = $self->{'comparaDBA'}->get_AnchorAlignAdaptor();
my $dnafrag_ids = $anchor_align_adaptor->fetch_all_dnafrag_ids($self->input_method_link_species_set_id);
my (%Overlappping_anchors, %Anchors_2_remove, %Scores);
my $input_mlssid = $self->input_method_link_species_set_id;
foreach my $genome_db_id(sort keys %{$dnafrag_ids}) {
my %genome_db_dnafrags;
foreach my $genome_db_anchors(@{ $anchor_align_adaptor->fetch_all_anchors_by_genome_db_id_and_mlssid(
$genome_db_id, $input_mlssid) }) {
push(@{ $genome_db_dnafrags{ $genome_db_anchors->[0] } }, [ @{ $genome_db_anchors }[1..4] ]);
}
foreach my $dnafrag_id(sort keys %genome_db_dnafrags) {
my @Dnafrag_anchors = @{ $genome_db_dnafrags{$dnafrag_id} };
for(my$i=0;$i<@Dnafrag_anchors-1;$i++) { #count number of overlaps an anchor has at every position to which it maps
for(my$j=$i+1;$j<@Dnafrag_anchors;$j++) {
if($Dnafrag_anchors[$i]->[3] >= $Dnafrag_anchors[$j]->[2]) {
$Overlappping_anchors{$Dnafrag_anchors[$i]->[1]}{$Dnafrag_anchors[$j]->[1]}++;
$Overlappping_anchors{$Dnafrag_anchors[$j]->[1]}{$Dnafrag_anchors[$i]->[1]}++;
}
else {
splice(@Dnafrag_anchors, $i, 1);
$i--;
last;
}
}
}
}
}
foreach my$anchor(sort keys %Overlappping_anchors) {
foreach my $overlapping_anchor(sort keys %{$Overlappping_anchors{$anchor}}) {
$Scores{$anchor} += ($Overlappping_anchors{$anchor}{$overlapping_anchor})**2; #score the anchors according to the number of overlaps
}
}
print STDERR "scores: ", scalar(keys %Scores), "\n";
my$flag = 1;
while($flag) {
$flag = 0;
foreach my $anchor(sort {$Scores{$b} <=> $Scores{$a}} keys %Scores) { #get highest scoring anchor
next unless(exists($Scores{$anchor})); #don't add it to "remove list" if it's already gone from the score hash
foreach my $anc_with_overlap_2_anchor(sort keys %{$Overlappping_anchors{$anchor}}) { #find all the anchors which overlap this anchor
$Scores{$anc_with_overlap_2_anchor} -= ($Overlappping_anchors{$anc_with_overlap_2_anchor}{$anchor})**2; #decrement the score
delete $Scores{$anc_with_overlap_2_anchor} unless($Scores{$anc_with_overlap_2_anchor});
#if score is zero remove this anchor from the overlapping list,
delete($Overlappping_anchors{$anc_with_overlap_2_anchor}{$anchor}); #remove high scoring anchor from hash of overlaps
}
delete($Overlappping_anchors{$anchor}); #remove high scoring anchor from hash
delete($Scores{$anchor}); #also remove it from scoring hash
$Anchors_2_remove{$anchor}++; #add it to list of ancs to remove
}
$flag = 1 if (scalar(keys %Scores));
}
print STDERR "anchors to remove: ", scalar(keys %Anchors_2_remove), "\n";
$self->overlapping_ancs_to_remove(\%Anchors_2_remove);
return 1;
}
sub write_output {
my ($self) = @_;
my $anchor_align_adaptor = $self->{'comparaDBA'}->get_AnchorAlignAdaptor();
my $Anchors_2_remove = $self->overlapping_ancs_to_remove();
my $input_mlssid = $self->input_method_link_species_set_id();
#set up jobs for TrimAnchorAlign
my $trim_anchor_align_analysis_id = $self->analysis->adaptor->fetch_by_logic_name("TrimAnchorAlign")->dbID;
my $current_analysis_id = $self->input_analysis_id();
$anchor_align_adaptor->update_failed_anchor($Anchors_2_remove, $current_analysis_id, $input_mlssid);
$anchor_align_adaptor->setup_jobs_for_TrimAlignAnchor($trim_anchor_align_analysis_id, $input_mlssid) if ($trim_anchor_align_analysis_id);
return 1;
}
sub input_method_link_species_set_id {
my $self = shift;
if (@_) {
$self->{input_method_link_species_set_id} = shift;
}
return $self->{input_method_link_species_set_id};
}
sub overlapping_ancs_to_remove {
my $self = shift;
if (@_) {
$self->{overlapping_ancs_to_remove} = shift;
}
return $self->{overlapping_ancs_to_remove};
}
sub genome_db_ids {
my $self = shift;
if (@_) {
$self->{genome_db_ids} = shift;
}
return $self->{genome_db_ids};
}
sub method_link_species_set_id {
my $self = shift;
if (@_) {
$self->{method_link_species_set_id} = shift;
}
return $self->{method_link_species_set_id};
}
sub input_analysis_id {
my $self = shift;
if (@_) {
$self->{input_analysis_id} = shift;
}
return $self->{input_analysis_id};
}
sub get_params {
my $self = shift;
my $param_string = shift;
return unless($param_string);
print("parsing parameter string : ",$param_string,"\n");
my $params = eval($param_string);
return unless($params);
if(defined($params->{'genome_db_ids'})) {
$self->genome_db_ids($params->{'genome_db_ids'});
}
if(defined($params->{'input_method_link_species_set_id'})) {
$self->input_method_link_species_set_id($params->{'input_method_link_species_set_id'});
}
if(defined($params->{'method_link_species_set_id'})) {
$self->method_link_species_set_id($params->{'method_link_species_set_id'});
}
if(defined($params->{'input_analysis_id'})) {
$self->input_analysis_id($params->{'input_analysis_id'});
}
return 1;
}
#sub store_input {
# my $self = shift;
#
# if (@_) {
# $self->{_store_input} = shift;
# }
#
# return $self->{_store_input};
#}
#
#sub store_output {
# my $self = shift;
#
# if (@_) {
# $self->{_store_output} = shift;
# }
#
# return $self->{_store_output};
#}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl-compara/modules/Bio/EnsEMBL/Compara/Production/EPOanchors/RemoveAnchorOverlaps.pm | Perl | apache-2.0 | 6,707 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Resources::CombinedAudience;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
description => $args->{description},
id => $args->{id},
name => $args->{name},
resourceName => $args->{resourceName},
status => $args->{status}};
# 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/V10/Resources/CombinedAudience.pm | Perl | apache-2.0 | 1,184 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Resources::CustomerConversionGoal;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
biddable => $args->{biddable},
category => $args->{category},
origin => $args->{origin},
resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V10/Resources/CustomerConversionGoal.pm | Perl | apache-2.0 | 1,158 |
=head1 Perl 6 Summary for 2005-12-05 through 2005-12-12
All~
Welcome to another Perl 6 summary. This week, like last, Parrot has produced the highest volume of emails. Fine by me, Parrot tends to be easiest to summarize. This summary is brought to you by Snow (the latest soft toy in the house). I would say you should get one, but apparently Borders stores everywhere are sold out of them. He is quite soft and a little mischievous. Maybe he belonged to a samurai once...
=head2 Perl 6 Compiler
=head3 Context Confusion
Mike Li wondered how to make his sample code work in Perl 6. Jonathan Scott Duff pointed out that the part he was curious about, was correct already. Score one for Perl 6.
L<http://groups.google.com/group/perl.perl6.compiler/browse_frm/thread/f2aeff93e8b65008/701c88448d3e0619#701c88448d3e0619>
=head3 Unbracketed Text from Text::bracketed
Allison Randal wanted to be able to access the text within PGE::Text::bracketed's match object. Patrick made it work, and Allison happily used it.
L<http://groups.google.com/group/perl.perl6.compiler/browse_frm/thread/b52eb566b1b74920/2ddc89650cba0213#2ddc89650cba0213>
=head3 Security Model
Bryan Burgers wondered how Parrot would support security. Luke Palmer pointed him to the p6i list and explained that Dan did have a plan for this that he couldn't recall. I recall something about VMS and having active and allowable capabilities. It sounded really cool when I read it.
L<http://groups.google.com/group/perl.perl6.compiler/browse_frm/thread/915ab29243296b6d/b1d2111587381192#b1d2111587381192>
=head2 Parrot
=head3 Build Failure
David Dyck managed to make the build fail on his bizarre setup. Leo fixed it.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/ea4bddf4f484b99e/ca867985648c6649#ca867985648c6649>
=head3 C<src/revision.c> Dependencies
Leo discovered that src/revision.c is missing some dependencies. He would love it if someone fixed that.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/ede1170028d51291/f1601d9906d83ccc#f1601d9906d83ccc>
=head3 Documenting C< .lex > Syntax
Klaas-Jan Stol documented the new syntax for lexicals. Jerry Gay applied the patch.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/323320bdd15dd3ec/44af2088a9038b01#44af2088a9038b01>
=head3 Multidimensional Arrays
Roger Browne found that he could not make multidimensional array access work with PMCs. Leo said that should be filed as a TODO.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/4c909d028217668d/f893d00cb7963847#f893d00cb7963847>
=head3 Directory Reorganization
Jerry Gay has made good progress spearheading the directory reorganization of Parrot. Rather than give you a bunch of links to emails that are essentially the same, I will skip them, but thank you Jerry.
=head3 C< make test > Error on OS X Tiger
Jason Gessner reported a test failure on OS X Tiger. Warnock applies.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/9c77186313236db3/46f78b57ee2dda85#46f78b57ee2dda85>
=head3 C3 MRO Test
C3 MRO (C3 P0's younger brother) recently underwent his factory acceptance test and will be released into the world. Like his older brother, he also speaks fluent Tibetan. On an unrelated note, Stevan Little added some test for the C3 method resolution order used in Parrot.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/67f6ee697aee1227/6ab6531cd56d004f#6ab6531cd56d004f>
=head3 Global Store Hash
Klaas-Jan Stol wanted to access the global store hash directly. Leo showed him how.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/3cf163422b9ac964/2c2eff348205c4de#2c2eff348205c4de>
=head3 Release Goals
Leo kicked off a brain storming session for what to focus on for the next release. Brains promptly began storming.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/0d335b722d2b383c/1e7680ea0214861d#1e7680ea0214861d>
=head3 Sun4 JIT Fix
Andy Dougherty submitted a big fix to make Sun4's JIT link again. Leo applied the patch.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/2db5724da187e75a/89c3ca829e14fce4#89c3ca829e14fce4>
=head3 :flat and :slurpy issues
Bob Rogers was having trouble making Parrot eat linguine because it would not mix :flat and :slurpy arguments. He also found that the problem was do to premature optimization (actually a PREMATURE_OPTIMIZATION define) and submitted a fix and test. Leo thanked him and applied them.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/b82229068aaa5da0/388895f10caf4730#388895f10caf4730>
=head3 Parrot 0.4.0 Luthor
Leo announced the latest release of Parrot 0.4.0 aka "Luthor". There was much rejoicing, but I was left wondering where Leo comes up with these release names.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/7bf518d01c05a68e/68e0857c8780647a#68e0857c8780647a>
=head3 C< loadlib > Cleanup
Leo has been hunting some uninitialized memory bugs in Parrot's library loading code. He has been having a difficult time finding the problem, and thus is looking into a general code clean up to make the problem easier to find (or possibly just fix it). Jerry Gay said he would make it work on windows, but no one volunteered for the main portion of the work.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/b669af010f24183e/1ee9073230febf94#1ee9073230febf94>
=head3 C<languages/regex/Makefile> is not Generated
Jerry Gay noticed that languages/regex/Makefile really ought to be a generated file. He opened a TODO for it.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/8a8f95f74e599c0c/ac889de56fe5168c#ac889de56fe5168c>
=head3 Fix Parrot IO Test 23
chromatic the ever uncapitalized proferred a patch for a failing Parrot_IO test. He seemed to feel that someone else ought to review it as he was not 100% on it. Warnock applies.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/bef9cae7bd0d285c/124ac8b68c92829d#124ac8b68c92829d>
=head3 C< load_bytecode > Fails Outside of Parrot
Bob Rogers noticed that load bytecode didn't work when not in the Parrot directory. Leo mistakenly fixed a different problem before he fixed this one. Sounds like a win/win to me.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/fcc0dbdfecb71d39/aaaac4bbc173b556#aaaac4bbc173b556>
=head3 Tcl Win32 Trouble
Jerry Gay noticed a problem building Tcl on Win32. François Perrad pointed out an old patch from Nick Glencross which apparently solves the problem. Warnock applies.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/5896bd53058f508d/7220acc0ec1612fd#7220acc0ec1612fd>
=head3 C< abs2rel > Issues
Alberto Simões spotted a problem with abs2rel. People seem to like the patch so it was applied.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/598d41a0905dc249/82e5874d4fa636c1#82e5874d4fa636c1>
=head3 OS X Build Errors (Reprise)
Brent Fulgham noticed some build errors on OS X using XCode 2.2. Leo pointed out that he had a stale parrot installed and that the two were not co-installable.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/ccea1a3f8df3d019/7a81eb526a0f1965#7a81eb526a0f1965>
=head3 Web Docs Broken
Joshua Hoblitt supplied a patch fixing the docs after the recent tree reorganization. Will Coleda applied it.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/8508aaabcd2e451d/f9d82fdd0f71861d#f9d82fdd0f71861d>
=head3 Parrot's Test Pod
Alberto Simoes provided a patch which fills out tests.pod a little more. chromatic applied the patch.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/684325566fb20f36/0673f15e6ac280be#0673f15e6ac280be>
=head3 C< make smoke > Progresses
Alberto Simoes made C< make smoke > provide progress. Will Coleda applied the patch.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/09a53d6e32d58e92/372bad7ef2f7e806#372bad7ef2f7e806>
=head3 JIT on FreeBSD
Joshua Isom reported a broken JIT on FreeBSD. Leo promptly fixed it.
L<http://groups.google.com/group/perl.perl6.internals?start=0>
=head3 C< runtime/parrot/include/*.pasm > Ought to be Made
Leo opened a ticket for C< runtime/parrot/include/*.pasm >. Currently they are generated by Configure.pl. They ought to be generated by make with the correct dependencies.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/2517202d98388ab1/4cfb56a53d3f3d44#4cfb56a53d3f3d44>
=head3 c< make smoke > JIT Easier
Alberto Simões posted a patch to make C< make smokej > run smoke testing with the JIT. Warnock applies.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/87ae9a18260af803/c42ae458735e4394#c42ae458735e4394>
=head3 MSVC Compiling
Ron Blaschke posted some informative summaries of test results using Visual Studio 7.1 and 8.0. People generally found it useful.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/af8b881c677c39f9/3c31a48390f588eb#3c31a48390f588eb>
=head3 CREDITS
Joshua Hoblitt suggested updating submission.pod to point out the CREDITS file. Chip agreed that would be a good idea.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/c98c13461a4f525e/8c9aea59444cfe7f#8c9aea59444cfe7f>
=head3 Library Loading Without Duplicates
Leo provided rudimentary support for avoiding loading the same bytecode file twice. Chip agreed that it was a good idea.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/7cc4e2b33933c2d9/38625781b0fc614e#38625781b0fc614e>
=head3 BigInt Needs Your Tests
Jerry Gay created a ticket at Leo's suggestion. BigInt needs both tests and design. You should add those tests.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/18b985b9d0a75617/556a15e5db0d4eaf#556a15e5db0d4eaf>
=head3 Parrot Shootout
Brent Fulgham announced that he had added Parrot to the great language shootout. This led to an inevitable round of optimizations as well as a few more of the benchmarks being written.
http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/a4cff1f015b466a5/b9aa4bbfcb04cd46#b9aa4bbfcb04cd46
=head3 PAST?
Jerry Gay's directory reorganization veered off to talk of imcc's PAST. Bernhard Schmalhofer noted that punie also has a different PAST. Too many acronyms...
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/33df7fe590a3dabb/059381abe4d068a2#059381abe4d068a2>
=head3 Solaris Threads
Erik Paulson noticed that Parrot's threads on solaris won't actually cross CPUs. Jack Woehr explained that it was an issue with how Solaris implements POSIX threading.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/8f4046a3683fadc0/628f0960341e12ed#628f0960341e12ed>
=head3 Multiline Macro Bug
Joshua Isom found a bizarre behavior that he felt was likely a bug involving multiline marcos and commas. Consensus it that it should be clarified and documented at the very least.
L<http://groups.google.com/group/perl.perl6.internals/browse_frm/thread/b6f976ef9a96fab7/e99715a66fc31b2f#e99715a66fc31b2f>
=head2 Perl 6 Language
=head3 C<Test::fail> Problems
Gaal Yahas noted that C<Test::fail> needs re-examination as fail is a built-in in Perl 6. Discussion ensued, although I don't think an answer was posed.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/58bf5777665fded1/cc7c6f74c8d98248#cc7c6f74c8d98248>
=head3 Perl5 to Perl6 Translator
Peter Schwenn asked what progress was being made on a Perl5 to Perl6 Translator. Larry provided an update of the one that he was working on. Based on Larry's update, I can bet that the Perl6 to Perl7 translator will be FAR easier than the 5 to 6 one.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/c79cd1ad5db8fc77/a46e96ac84c58020#a46e96ac84c58020>
=head3 $!?
Daren Duncan was having trouble working out exactly how to work with $!. Larry and others provided some answers, but I don't think any were final.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/e9a10a5b3d645a73/bd9b09e58c292872#bd9b09e58c292872>
=head3 Module Versioning
David Green wondered how different module versions and APIs would be handled in Perl 6. Larry provided answers.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/40ec1866f50908e4/f9e8308425a464d6#f9e8308425a464d6>
=head3 Regex Captures into Locals
Brad Bowman wondered if there was a good way to have regexes capture into newly created local variables. Currently, no, you must predeclare them.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/ef6638e1ea4501c0/aeff63cf1f6af03c#aeff63cf1f6af03c>
=head3 Threading Thoughts Through the Ether
Ron Blaschke posted a few of his thoughts and a few links on threading in languages. Sam Vilain posted a pointer to the S17 draft that includes atomic blocks and co-routines.
L<http://groups.google.com/group/perl.perl6.language/browse_frm/thread/e6b3ca5a600ebde7/017e56166e196ac1#017e56166e196ac1>
=head2 The usual footer
To post to any of these mailing lists please subscribe by sending email to <perl6-internals-subscribe@perl.org>, <perl6-language-subscribe@perl.org>, or <perl6-compiler-subscribe@perl.org>. If you find these summaries useful or enjoyable, please consider contributing to the Perl Foundation to help support the development of Perl. You might also like to send feedback to ubermatt@gmail.com
L<http://donate.perl-foundation.org/> -- The Perl Foundation
L<http://dev.perl.org/perl6/> -- Perl 6 Development site
L<http://planet.parrotcode.org/> -- Parrot Blog aggregator
| autarch/perlweb | docs/dev/perl6/list-summaries/2005/p6summary.2005-12-12.pod | Perl | apache-2.0 | 13,995 |
% CVS: $Id: essln.pl,v 1.3 1998/11/26 05:18:40 pets Exp $
% ESSLN - Version 2, written in standard Prolog
%======================================================================
% This file contains the code of ESSLN's version 2, which is written
% in standard Prolog (This version does not use the special built-in
% predicates of Arity-Prolog mentioned on page 365. The first version
% of ESSLN, which runs faster, is stored in file \CHAP9\ESSLN.ARI of
% the diskette).
% To experiment with this system, first check the following points:
% 1: The builtin predicate "system" used in this program (to test
% if a predicate is a builtin predicate) may be equivalent to
% "sys" (or something else) in your Prolog system. In which case
% change it by adding the following clause (simply remove %):
% system(F/N) :- sys(F).
% 2: The builtin predicate "cls" is used in this program to clear
% the screen before displaying menus. Check your Prolog system
% for the equivalent predicate and replace it if necessary. For
% example, if it is equivalent to "clscr" in your system, then
% add the following clause (by simply removing the symbol %):
% cls :- clscr.
% If your Prolog system has no such predicate, then define it
% using the following clauses (again by removing the symbols %):
% cls :- cursor(&:,0,0),clear(23,80).
%
% clear(0,0) :- !,cursor(&:,0,0).
% clear(M,0) :- !,nl,M1 is M-1,clear(M1,80).
% clear(M,N) :- put(32),N1 is N-1,clear(M,N1).
% Here, the goal "cursor(&:,0,0)" moves the cursor to row 0 and
% column 0. If the cursor moving predicate is also not available,
% then remove all goals "cls" from this program.
%
% 3: The arithmetic function "round" used in this program may be
% equivalent to some function "floor" (or "int"), say, in your
% Prolog system. In which case, change this by adding the following
% clause (again by removing the symbol %):
% roundz(X,Y) :- Y is floor(X).
%
% Now to run ESSLN, perform the following steps:
% a) Consult this file.
% b) Enter the following query to invoke the system:
% ?- essln.
% Then press any key to start (press 'e' to exit).
%
% c) Select one of the three languages available in this package:
% English, French or Vietnamese, and type the number terminated with
% a period, for example, type 3.
%
% d) When the prompt Q:> appears, load an existing knowledge-base
% (this diskette contains the files \chap9\supplier.eng and
% \chap9\detectiv.eng in English and also their versions in French
% and Vietnamese, which should have been copied to your hard disk),
% by entering the following query, say:
% Q:> load 'c:\chap9\supplier.eng'.
%
% e) Enter the queries as presented on pages 430-432 to experiment
% with the system (Observe the use of the underscore to indicate
% types). In response to the prompt ->, you must type 'how.' (to
% ask for explanation) or 'ok.' (to accept the answer) or 'more.'
% (to ask for alternative answers). Note the required period at
% the end. For example, try the following queries:
% Q:> which _agent is a fractional supplier?
% Q:> which _agent is not a fractional supplier?
% Q:> which _agent supply _item b1?
% Q:> which _agent not supply _item b2?
% Q:> which _agent supply all _item?
% Q:> which _agent supply no _item?
% Q:> _agent 'Adams & Sons' supply which _item?
% Q:> _agent 'Mitre 10' not supply which _item?
% Q:> which _agent supply which _item?
% Q:> which _agent not supply which _item?
% Then add the following new information:
% Q:> _agent 'Rossianno Co' supply no _item.
% Q:> _agent 'Yoshima Kuru' supply all _item.
% and try the above queries again.
%
% f) To terminate the session, enter the query Q:> bye.
%
% g) Now re-start the system (by pressing any key), and load the second
% file by entering:
% Q:> load 'c:\chap9\detectiv.eng'.
% then enter the queries as presented on pages 434-436, 457-460.
% Start with the query:
% Q:> which _suspect murdered _victim 'J.R.'?
% (Beware, the name 'J.R.' has two dots in it. Also remember to use
% a question mark at the end, as any sentence terminated with a period
% is accepted as a new information to be stored in the knowledge-base).
% You can use the query Q:> list base. to see the knowledge-base
% in Prolog form. Similarly a query Q:> list predicate. will
% show all the predicate definitions, including the built-in ones;
% Q:> list domain. lists all the domains, Q:> list constsymbol. shows
% all the constant symbols currently available, etc.
% (For other languages, see the dictionaries in this file for the
% corresponding commands. For example, 'list' in French is 'montrez'
% and in Vietnamese is 'liet-ke'; 'bye' in French is 'aurevoir' and
% in Vietnamese is 'het', etc.).
%
% To terminate this session, enter the query Q:> bye.
%
% h) Now re-start the system again (by pressing any key), select the
% French language by typing the number 4., and load the French file
% by entering:
% Q:> chargez 'c:\chap9\supplier.fre'.
% Then enter the following queries. In response to the prompt ->,
% you must type 'comment.' (to ask for explanation) or 'ok.' (to
% accept the answer) or 'encore.' (to ask for alternative answers).
% Again, note the required period at the end:
% Q:> quel _agent est un fournisseur fractionnaire?
% Q:> quel _agent ne est pas un fournisseur fractionnaire?
% Q:> quel _agent fournit _item b1?
% Q:> quel _agent ne fournit pas _item b2?
% Q:> quel _agent fournit tout _item?
% Q:> quel _agent fournit aucun-de _item?
% Q:> _agent 'Adams & Sons' fournit quel _item?
% Q:> _agent 'Mitre 10' ne fournit quel _item?
% Q:> quel _agent fournit quel _item?
% Q:> quel _agent ne fournit quel _item?
% Then add the following new information:
% Q:> _agent 'Rossianno Co' fournit aucun-de _item.
% Q:> _agent 'Yoshima Kuru' fournit tout _item.
% and try the above queries again.
%
% To terminate, enter the query Q:> aurevoir.
% You may like to try the file \chap9\supplier.vie as well.
%
% NOTE: To study the separate components of ESSLN such as: the query
% converter, the goal displayer and the meta-interpreter, see files
% \chap9\figure21.pro (or \chap9\convertr.pro),
% \chap9\figure31.pro (or \chap9\displayr.pro), and
% \chap9\intpretr.pro.
%
%==========================================================================
%=========== ESSLN: AN EXPERT SYSTEM SHELL THAT SUPPORTS ==================
%========== NEGATIVE AND QUANTIFIED QUERIES, AND SUBTYPES =================
%==========================================================================
% TOP-LEVEL CONTROL
% =========================================================================
:- op(500,xfx,#).
:- op(500,xfy,:).
goal :- essln.
essln :-
initialize,
repeat,
receive_query(Q,C),
process_query(Q,C),
terminate(Q).
essln.
initialize :-
display_banner,
create_workspace,
choose_language.
create_workspace :-
clear_workspace,
prepare_tools.
prepare_tools :-
builtin(P),
assertz(P),
fail.
prepare_tools :-
assert(symbol_index(0)).
choose_language :-
display_languages,
read(Language),
(available(Language),!,
get_dictionary(Language); learn_new(Language)).
available(L) :- member(L,[3,4,15]).
get_dictionary(L) :-
language(L,A),assertz(A),fail.
get_dictionary(L) :-
true. % cls.
% --------------------------------------------------------------------
% RECEIVE QUERY
% ====================================================================
receive_query(Q,C) :-
nl, write('Q:> '),
readstring(T,C),
scan_text(T,Q),!.
receive_query(Q,C) :-
error_query,
receive_query(Q,C).
readstring(T,C1) :-
get0(C),
read_chars(C,[],[C1|L]),
reverse([C1|L],[],T).
read_chars(13,[C|L],[C|L]) :-
nl,end_char(C),!.
read_chars(13,L,L1) :- !,
nl,get0(C),
read_chars(C,[32|L],L1).
read_chars(8,[C|L],L1) :- !,
put(32),put(8),
get0(C1),
read_chars(C1,L,L1).
read_chars(C,L,L1) :-
get0(C1),
read_chars(C1,[C|L],L1).
chars_int([],N,N).
chars_int([C|L],M,N) :-
M1 is 10*M + C - 48,
chars_int(L,M1,N).
end_char(C) :- C = 46; C = 63. % period or ?
scan_text([],[]) :- !.
scan_text(T,[W|L]) :-
append(_,[C|T1],T), \+(member(C,[32,13,10])),!,% skip spaces, eoln.
get_word([C|T1],W,T2), scan_text(T2,L).
get_word([C|T],C,T) :- member(C,[58,44,46,63]),!. % (: , . ?)
get_word([C|T],[C],T) :- C = 61,!. % (=)
get_word([C|T],[C|W],T2) :- bracket(C,C1),!,get_chars(0,C1,T,W,T2).
get_word([C|T],[C|W],T2) :- valid_start(C),!, get_chars(1,32,T,W,T2).
get_chars(K,C1,[C|T],[C|W],T2) :-
valid_char(K,C,C1),!,get_chars(K,C1,T,W,T2).
get_chars(0,39,[39|T],[],T) :- !.
get_chars(0,C,[C|T],[C],T) :- (C = 41; C = 93),!. % ) or ]
get_chars(1,C1,[C|T],[],[C|T]) :- member(C,[32,61,58,44,46,63,13,10]).
valid_start(C) :- valid(C); C = 37. % (%)
valid_char(K,C,C1) :- K = 0,!, \+(C = C1); K = 1, valid(C).
bracket(39,39). % single quotes
bracket(40,41). % round brackets ()
bracket(91,93). % square brackets []
% --------------------------------------------------------------------
% PROCESS QUERY
% ====================================================================
process_query(Q,_) :-
special_query(Q),!.
process_query(Q,46) :- !,
convert_clause(c,[],Q,E),
store_clause(E).
process_query(Q,63) :-
convert_query([],Q,G),
evaluate(G).
special_query([[95|W],A,46]) :- !,
atomname(A,A1),
name(T,W),assert(constsymbol(T:A1)).
special_query([[95|W],63]) :- !,
name(T,W),constsymbol(T:X),
nl,write_list([T,' ',X,' ->']),get0(13).
special_query([[95|W],X,[95|W1],46]) :-
name(Is,X),trans_word(is,Is),!,
name(T,W),name(T1,W1),process_subtype(T,T1).
special_query([Q|R]) :-
name(Q1,Q),trans_word(W,Q1),
member(W,[bye,list,load,save,reload]),!,
process_special_query(W,R).
process_special_query(bye,_) :- !.
process_special_query(list,R) :- !,
(R = [46],!,nl,listing;
R = [P,46],name(N,P),
nl,(trans_word(base,N),listing('#'),!; listing(N))).
process_special_query(reload,[[39|N],46]) :- !,
(retract(symbol_index(_)),!; true),
name(Filename,N),reconsult(Filename).
process_special_query(load,[[39|N],46]) :- !,
trans_word(bye,W),name(W,L),append(L,[46],E),
name(Filename,N),
see(Filename),
readfile(E),
seen.
process_special_query(save,[[39|N],46]) :- !,
name(Filename,N),
tell(Filename),
listing,
told.
readfile(E) :-
readline(0,[],L),
(append(_,E,L),!;
process_line(L), readfile(E)).
readline(0,[46|L],L1) :- !,reverse(L,[46],L1).
readline(S,L,L1) :-
get0(C),put(C),
(C = 39,!,R is (S+1) mod 2; R is S),
readline(R,[C|L],L1).
reverse([],L,L).
reverse([H|T],L,R) :- reverse(T,[H|L],R).
process_line(L) :-
scan_text(L,Q),
process_query(Q,46),!.
process_line(_).
% -------------------------------------------------------------------
% PROCESS SUBTYPE
% ===================================================================
process_subtype(T1,T2) :-
\+(subtype(T1,T2)),
asserta(subtype(T1,T2)),
subtype(S,T),
clause(predicate(Phrase,A),true),
append(W,[(T,R:X)|Rest],Phrase),
append(W,[(S,R:X)|Rest],Phrase1),
process_subphrase(Phrase1,R,S,T,A),
fail.
process_subtype(_,_).
process_subphrase(Phrase,R,S,T,A) :-
clause(predicate(Phrase,A1),true),!,
\+(clause((A # 1),A1)),
assert((A # 1 :- A1));
generate_symbol(P1),
A =.. [P|L1], A1 =..[P1|L1],
assert(predicate(Phrase,A1)),
assert((A # 1 :- A1)),
clause(domain(A),Types),conv(TL,Types),
append(W,[type(R1,T)|Rest],TL), R == R1,!,
append(W,[type(R1,S)|Rest],TL1),conv(TL1,Types1),
assert((domain(A1) :- Types1)).
conv([X|T],(X,R)) :- T \== [],!,conv(T,R).
conv([X],(X)).
type(T,T).
type(S,T) :- subtype(S,T).
%-------------------------------------------------------------------
% TERMINATION
%===================================================================
end([Q,46]) :- name(Q1,Q),trans_word(bye,Q1).
terminate([Q,_]) :-
name(Q1,Q),trans_word(bye,Q1),
abolish('#'/2),
abolish(symbol_index/1),
abolish(predicate/2),
abolish(domain/1),
abolish(constsymbol/1),
abolish(subtype/2),
abolish(transword/2),
abolish(already_asked/2),
essln.
%------------------------------------------------------------------
% CONVERT CLAUSES
%==================================================================
convert_clause(S,VS,Q,E) :-
append(P,[C|Rest],Q),member(C,[58,44,46]),!, \+(P = []),
convert(S,P,VS,VS1,A), % [ : , .]
(C = 58,!, E = (A :- B), convert_clause(t,VS1,Rest,B);
C = 44,!, E = (A,B), convert_clause(t,VS1,Rest,B);
C = 46,!, E = A).
convert(c,[[37|N]|P],VS,VS1,(A # C)) :- !,
chars_int(N,0,I),
C is I/100,
convert(h,P,VS,VS1,A).
convert(c,P,VS,VS1,(A # 1)) :- !,
convert(h,P,VS,VS1,A).
convert(h,P,VS,VS1,A) :- !,
convert_atom(P,VS,VS1,NP,P1,AL,_,[0,0,0,0],[_,Nt,No,All]),
(bad_atom(Nt,No,All),!,fail;
(predicate(P1,A1),!; construct(P1,A1)),
(No = 1,!,A = non(A1); quantify([_,Nt,0,0],NP,_,A1,A)),
store_constants(AL)).
convert(t,P,VS,VS1,A) :-
convert_atom(P,VS,VS1,NP,P1,AL,P2,[0,0,0,0],QL),
(predicate(P1,A1),!; construct(P1,A1)),
quantify(QL,NP,P2,A1,A),
store_constants(AL),!.
quantify([_,0,0,0],_,_,A,A) :- !.
quantify([0,0,1,0],_,_,A,not(A)) :- !.
quantify([0,0,0,1],_,_,A,not(non(A))) :- !.
quantify([1,0,0,1],_,P,A,all(A,not(non(B)))) :- !,predicate(P,B).
quantify([1,0,1,0],_,P,A,all(non(A),not(B))) :- !,predicate(P,B).
quantify([_,1,0,0],NP,_,A,non(A)) :- !,
(predicate(NP,_),!;
functor(A,F,N),copy_clause(_,NP,VL,_),
A1 =.. [F|VL],assert(predicate(NP,non(A1)))).
quantify([_,Nt,No,All],_,_,_,_) :-
(bad_atom(Nt,No,All); unknown_concept),!,fail.
convert_atom([Q,[95|W]|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:V1)|P1],[T:V1|AL],[(T,S1:V2)|P2],[E,Nt,No,All],QL) :-
universal(Q),!,name(T,W),
convert_atom(Rest,VS,VS1,NP,P1,AL,P2,[E,Nt,No,1],QL).
convert_atom([Q,[95|W]|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:V1)|P1],[T:V1|AL],[(T,S1:V2)|P2],[E,Nt,No,All],QL) :-
neguniversal(Q),!,name(T,W),
convert_atom(Rest,VS,VS1,NP,P1,AL,P2,[E,Nt,1,All],QL).
convert_atom([Q,[95|W]|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:V1)|P1],[T:V1|AL],[(T,S1:V1)|P2],[E,Nt,No,All],QL) :-
existential(Q),!,name(T,W),
convert_atom(Rest,VS,VS1,NP,P1,AL,P2,[1,Nt,No,All],QL).
convert_atom([Q|Rest],VS,VS1,[Q1|NP],P1,AL,P2,[E,Nt,No,All],QL) :-
negation(Q,Q1),!,
convert_atom(Rest,VS,VS1,NP,P1,AL,P2,[E,1,No,All],QL).
convert_atom([[95|W],[C|L]|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:V1)|P1],[T:V1|AL],[(T,S1:V1)|P2],[E,Nt,No,All],QL) :-
capital(C),!,name(X,[C|L]),name(T,W),
(member((X,T,S1:V1),VS),!, VS2 = VS; VS2 = [(X,T,S1:V1)|VS]),
convert_atom(Rest,VS2,VS1,NP,P1,AL,P2,[1,Nt,No,All],QL).
convert_atom([[95|W],A|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:A1)|P1],[T:A1|AL],[(T,S1:A1)|P2],[E,Nt,No,All],QL) :- !,
aterm(A,VS,E,A1,VS2,E1),name(T,W),
convert_atom(Rest,VS2,VS1,NP,P1,AL,P2,[E1,Nt,No,All],QL).
convert_atom([W|Rest],VS,VS1,[(T,S:V)|NP],
[(T,S1:W1)|P1],[T:W1|AL],[(T,S1:W1)|P2],[E,Nt,No,All],QL) :-
special_term(W,VS,E,T,W1,VS2,E1),
convert_atom(Rest,VS2,VS1,NP,P1,AL,P2,[E1,Nt,No,All],QL).
convert_atom([W|Rest],VS,VS1,[W1|NP],[W1|P1],AL,[W1|P2],QL0,QL) :-
!,name(W1,W),convert_atom(Rest,VS,VS1,NP,P1,AL,P2,QL0,QL).
convert_atom([],VS,VS,[],[],[],[],QL,QL).
convert_query(VS,Q,G) :-
append(P,[C|Rest],Q),member(C,[44,63]),!,\+(P = []),
convert(g,P,VS,VS1,A), % [ , ?]
(C = 44,!, G = (A,B), convert_query(VS1,Rest,B);
C = 63,!, G = A).
convert(g,P,VS,VS1,A) :-
convert_atom(P,VS,VS1,NP,P1,_,P2,[0,0,0,0],QL),
(predicate(P1,A1),!, quantify(QL,NP,P2,A1,A);
unknown_concept,!,fail).
% QUANTIFIERS
% -----------------------------------------------------------------------
universal(Q) :- name(Q1,Q),(trans_word(all,Q1);trans_word(every,Q1)),!.
neguniversal(Q) :- name(Q1,Q),trans_word(no,Q1),!.
existential(Q) :- name(Q1,Q),(trans_word(some,Q1);trans_word(which,Q1)),!.
negation(Q,Q1) :- name(Q1,Q),trans_word(not,Q1),!.
% -----------------------------------------------------------------------
capital(C) :- 65 =< C, C =< 90.
aterm(W,VS,E,W1,VS,E) :- atomname(W,W1),!.
aterm(W,VS,E,W1,VS2,E1) :- special_term(W,VS,E,_,W1,VS2,E1).
atomname([39|W],W1) :- name(W1,W).
atomname([C|W],W1) :- 96 < C, C < 123,name(W1,[C|W]).
special_term(W,VS,E,T,W1,VS,E) :- % integer number
% list_text(W,S),int_text(W1,S),
chars_int(W,W1),!,trans_word(number,T).
special_term([C|W],VS,E,T,W1,VS2,E1) :-
(C = 40,!,trans_word(number,T); % ( for numeric expression
C = 91, trans_word(list,T)), % [ for list
tokenize([C|W],TL),term(W1,[],VL,TL,[]),
(VL = [],!, VS = VS2, E = E1;
check_vars(VL,VS,VS2), E1 = 1).
% list_text([C|W],S),string_term(S,W1),
% list_var_symbols([C|W],0,[],WVS),
% (WVS = [],!, VS = VS2, E = E1;
% var_list(W1,WVL), match_vars(WVS,WVL,VS,VS2), E1 = 1).
check_vars([],VS,VS) :- !.
check_vars([(X,V)|VL],VS,VS2) :-
(member((X,T,S:V),VS),!,check_vars(VL,VS,VS2);
check_vars(VL,[(X,T,S:V)|VS],VS2)).
%match_vars([],[],VS,VS) :- !.
%match_vars([X|XL],[V|VL],VS,VS2) :-
% (member((X,T,S:V),VS),!,match_vars(XL,VL,VS,VS2);
% match_vars(XL,VL,[(X,T,S:V)|VS],VS2)).
%----------------------------------------------------------------
% GET TOKENS FROM A LIST OF CHARACTERS
%================================================================
tokenize([],[]).
tokenize(CharList,[Token|TList]) :-
append(_,[C|List],CharList), \+(C = 32),!,
get_token([C|List],Token,Rest),
tokenize(Rest,TList).
get_token(List,Token,Rest) :-
get_char(List,Lchars,Rest),
name(Token,Lchars).
get_char(L,S,L1) :- separator(L,S,L1),!.
get_char([C|L],[C|Lc],L1) :-
check_start(S,C),
get_word_chars(S,L,Lc,L1).
get_word_chars(S,L,Lc,L1) :-
check_end(S,L,Lc,L1).
get_word_chars(S,[C|L],[C|Lc],L1) :-
legal_char(S,C),
get_word_chars(S,L,Lc,L1).
legal_char(quote,C) :- \+(C = 39).
legal_char(num,C) :- digit(C).
legal_char(symb,C) :- valid_cha(C).
check_start(quote,39).
check_start(num, C) :- digit(C).
check_start(symb,C) :-
valid_cha(C), \+(digit(C)).
check_end(_,[],[],[]) :- !.
check_end(quote,[39|L],[39],L) :- !.
check_end(num, [C|L],[],[C|L]) :- \+(digit(C)),!.
check_end(symb,[C|L],[],[C|L]) :- \+(valid_cha(C)).
separator([C,D,E|L],[C,D,E],L) :- name(S,[C,D,E]),
member(S,['=:=','=\=','\==','@=<','@>=','=..','-->']),!.
separator([C,D|L],[C,D],L) :- name(S,[C,D]),
member(S,[(':-'),'\+','->','\=','==','@<','@>','=<','>=',
'//']),!.
separator([C|L],[C],L) :-
member(C,[44,40,41,58,91,93,124,43,45,42,47,59,61,60,62,94]).
valid_cha(C) :- letter(C); digit(C); C = 95.
letter(C) :- 97 =< C, C =< 122; 65 =< C, C =< 90.
digit(C) :- 48 =< C, C =< 57.
%----------------------------------------------------------------
% CONVERT A LIST OF TOKENS INTO A PROLOG TERM
%================================================================
term(T,VL,VL1) --> formal_term(T,VL,VL1).
term(T,VL,VL1) --> infix_term(T,VL,VL1).
formal_term(T,VL,VL1) --> variable(T,VL,VL1).
formal_term(T,VL,VL1) --> constants(T,VL,VL1).
formal_term(T,VL,VL1) --> list(T,VL,VL1).
formal_term(T,VL,VL1) --> prefix_term(T,VL,VL1).
variable(V,VL,VL1) -->
[X],{variable_name(X,V,VL,VL1)}.
constants(T,VL,VL) -->
[X],{(constsymb(X,T);numbr(X,T))}.
list([],VL,VL) --> ['[',']'].
list([T|L],VL,VL1) --> ['['],
term(T,VL,VL2),tail(L,VL2,VL1).
tail([],VL,VL) --> [']'].
tail([T|L],VL,VL1) -->
[','],term(T,VL,VL2),tail(L,VL2,VL1).
tail(L,VL,VL1) -->
['|'],variable(L,VL,VL1),[']'].
tail(L,VL,VL1) -->
['|'],list(L,VL,VL1),[']'].
prefix_term(T,VL,VL1) -->
functer(F),['('],
arguments(Args,VL,VL1),[')'],
{T =.. [F|Args]}.
functer(X) --> [X],{functsymb(X)}.
arguments([Arg],VL,VL1) -->
term(Arg,VL,VL1).
arguments([A|Args],VL,VL1) -->
term(A,VL,VL2),[','],
arguments(Args,VL2,VL1).
infix_term(T,VL,VL1) --> rightas_term(T,VL,VL1).
infix_term(T,VL,VL1) --> bracket_term(T,VL,VL1).
rightas_term(T,VL,VL1) -->
formal_term(T,VL,VL1).
rightas_term(T,VL,VL1) -->
formal_term(A,VL,VL2),[F],{operator(F)},
rightas_term(B,VL2,VL1),
{T =.. [F,A,B]}.
bracket_term(T,VL,VL1) -->
['('],rightas_term(T,VL,VL1),[')'].
bracket_term(T,VL,VL1) -->
['('],rightas_term(A,VL,VL2),[')',F],{operator(F)},
rightas_term(B,VL2,VL1),
{T =.. [F,A,B]}.
bracket_term(T,VL,VL1) -->
['('],rightas_term(A,VL,VL2),[')',F],{operator(F)},
bracket_term(B,VL2,VL1),
{T =.. [F,A,B]}.
variable_name(X,V,VL,VL1) :-
name(X,[C|L]),
((capital(C); C = 95, \+(L = [])),
(member((X,V),VL),!,VL1 = VL;
VL1 = [(X,V)|VL]);
C = 95,L = [],VL1 = [(X,V)|VL]).
constsymb(X,X) :- atom_name(X).
constsymb(X,T) :- char_string(X,T).
functsymb(X) :- atom_name(X); system(X/N);
member(X,[abs,exp,ln,log,sqrt,acos,asin,
atan,cos,sin,tan]).
atom_name(X) :- name(X,[C|L]),97 =< C, C =< 122.
char_string(X,T) :- name(X,[C|L]),
C = 39, string(L,R), name(T,R).
string([39],[]).
string([H|T],[H|R]) :- string(T,R).
numbr(X,T) :- name(X,[C|L]),
(48 =< C, C =< 57),chars_int([C|L],0,T).
operator(F) :-
member(F,[is,':','+','-','*','/','=','<','>','^',mod]);
member(F,['->','\=','==','@<','@>','=<','>=','//']);
member(F,['=:=','=\=','\==','@=<','@>=','=..','-->']).
%----------------------------------------------------------------
% STORE CLAUSES IN KNOWLEDGE-BASE
%================================================================
store_clause((A # C :- B)) :- !,assert((A # C :- B)).
store_clause((non(A) # C)) :- !,domain(A),assert((non(A) # C)).
store_clause((A # C)) :- domain(A),assert((A # C)).
construct([Find|P1],tobe_filled(A)) :-
trans_word(find,Find),!,
construct(P1,A).
construct(P1,A) :-
copy_clause(P1,P2,VL,TL),
generate_symbol(P), E =.. [P|VL], assert(predicate(P2,E)),
convert(TL,Types), assert((domain(E) :- Types)),
predicate(P1,A).
copy_clause([],[],[],[]) :- !.
copy_clause([(T,S:A)|P1],[(T,R:V)|P2],[R:V|VL],[type(R,T)|TL]) :- !,
copy_clause(P1,P2,VL,TL).
copy_clause([W|P1],[W|P2],VL,TL) :-
copy_clause(P1,P2,VL,TL).
store_constants([]) :- !.
store_constants([T:A|AL]) :-
(atom(A),\+(constsymbol(T:A)),!,
assert(constsymbol(T:A)); true),
store_constants(AL).
generate_symbol(Symb) :-
common_symbol(P),
retract(symbol_index(I)),I1 is I+1,
int_to_chars(I1,[],L),
name(Symb,[P|L]),
assert(symbol_index(I1)).
int_to_chars(0,L,L) :- !.
int_to_chars(I,L,L1) :-
C is 48 + (I mod 10),
I1 is I//10,
int_to_chars(I1,[C|L],L1).
common_symbol(112).
bad_atom(Nt,No,All) :-
Nt+No+All > 1,
nl,write('A:> '),
write_word('Bad clause!'),nl,tab(4),
write_word('A clause cannot have more than one word "not","no","all".').
unknown_concept :-
nl,write('A:> '),
write_word('I dont know this concept. Check your typing'),
nl,tab(4),write_word('If this is a new concept, please teach me').
error_query :- nl,write('A:> '),write_word('Illegal query !').
terminate_message :- nl,tab(4),write_word('No (more) answers !').
%--------------------------------------------------------------------
% EVALUATE GOAL
%====================================================================
evaluate(Goal) :-
prove(Goal,20,Certainty,Proof,[]),
process_result(Goal,Certainty,Proof),!,
clear_workspace.
evaluate(_) :-
terminate_message,
clear_workspace.
process_result(Goal,Certainty,Proof) :-
print_answer(Goal,Certainty),!,
read_response(Response),
process_response(Response,Proof).
clear_workspace :-
abolish(answer/2),assert(answer(nul,nul)),
abolish(save_all/2),assert(save_all(nul,nul)),
abolish(failproof/1),assert(failproof(nul)).
print_answer(Goal,0) :- !,
nl,write('A:> '),
copy(Goal,Goal1),
display_goal(Goal1,no),!.
print_answer(Goal,Certainty) :-
nl,write('A:> '),
write_goal_certainty(Certainty),
copy(Goal,Goal1),
display_goal(Goal1,yes),!.
write_goal_certainty(C) :-
C =:= 1,!;
C1 is C*100,
roundz(C1,C2),!,
% float_text(C1,T,fixed(0)),int_text(C2,T),
write_word('I am'),
write_list([' ',C2,'% ']),write_word('positive that'),
nl,tab(4).
write_rule_certainty(C) :-
(var(C); C =:= 1),!;
C =:= 0,!,write_word('is false');
C1 is C*100,
roundz(C1,C2),!,
% float_text(C1,T,fixed(0)),int_text(C2,T),
write_word(with),
write_list([' ',C2,'% ']),write_word(certainty).
roundz(X,Y) :- Y is round(X,0).
read_response(R) :-
nl,write(' -> '),
read(S),
(trans_word(T,S),
member(T,[ok,more,how]),!, R = T;
write_word(' Type ok., how. or more.'),
read_response(R)).
trans_word(W,W1) :- transword(W,W1),!.
write_word(W) :- trans_word(W,W1),write(W1).
write_list([]) :- !.
write_list([X|T]) :- write(X),write_list(T).
%---------------------------------------------------------------------
% ENGLISH DICTIONARY
%=====================================================================
language(3,transword(X,X)).
%---------------------------------------------------------------------
% FRENCH DICTIONARY
%=====================================================================
language(4,transword(all,tout)).
language(4,transword(all,toute)).
language(4,transword(every,chaque)).
language(4,transword(some,quelque)).
language(4,transword(which,quel)).
language(4,transword(which,quelle)).
language(4,transword(no,'aucun-de')).
language(4,transword(not,ne)).
language(4,transword(not,pas)).
language(4,transword(none,nul)).
language(4,transword(none,nulle)).
language(4,transword(none,aucun)).
language(4,transword(none,aucune)).
language(4,transword(deny,rejetez)).
language(4,transword(is,est)).
language(4,transword(true,vrai)).
language(4,transword(fact,fait)).
language(4,transword(usergiven,'useur-donne')).
language(4,transword(nofact,sansfait)).
language(4,transword(system:true,systeme:vrai)).
language(4,transword(system:false,systeme:faux)).
language(4,transword(nonterminate,nontermine)).
language(4,transword(ok,ok)).
language(4,transword(more,encore)).
language(4,transword(how,comment)).
language(4,transword(find,trouver)).
language(4,transword(base,base)).
language(4,transword(with,avec)).
language(4,transword(certainty,certain)).
language(4,transword(number,nombre)).
language(4,transword(eq,eg)).
language(4,transword(dif,dif)).
language(4,transword(lt,mq)).
language(4,transword(gt,pq)).
language(4,transword(le,me)).
language(4,transword(ge,pe)).
language(4,transword(lta,mqa)).
language(4,transword(gta,pqa)).
language(4,transword(lea,mea)).
language(4,transword(gea,pea)).
language(4,transword(in,dans)).
language(4,transword(fail,manque)).
language(4,transword(bye,aurevoir)).
language(4,transword(list,montrez)).
language(4,transword(list,liste)).
language(4,transword(reload,rechargez)).
language(4,transword(load,chargez)).
language(4,transword(load,load)).
language(4,transword('reading..........','lisant..........')).
language(4,transword(save,reservez)).
language(4,transword('Because','Parce que')).
language(4,transword('IF','SI')).
language(4,transword('THEN','ALORS')).
language(4,transword('is true','est vrai')).
language(4,transword('is false','est mauvais')).
language(4,transword(' Type ok., how. or more.',
' Repondez ok., comment. ou encore.')).
language(4,transword(stop,stop)).
language(4,transword('Illegal query !','Question illegal !')).
language(4,transword('No (more) answers !','Pas (encore) de reponse !')).
language(4,transword('No more explanations',
'Pas davantage d''explications')).
language(4,transword('No more explanations for this',
'Pas davantage d''explications pour ceci')).
language(4,transword('Give a percentage on your certainty',
'Donnez un pourcentage de certain')).
language(4,transword('I am','Je suis')).
language(4,transword('positive that','certain que')).
language(4,transword('has the form','a de la forme')).
language(4,transword('Bad clause!','Mauvais clause!')).
language(4,
transword('A clause cannot have more than one word "not","no","all".',
'Clause ne peut pas avoir plus qu''un mot "ne-pas","aucun","tout" .')).
language(4,transword('I dont know this concept. Check your typing',
'Je ne sais pas ce concept. Verifiez votre composition')).
language(4,transword('If this is a new concept, please teach me',
'S''il est un nouveau concept, enseignez moi')).
language(4,transword('using the substitution','par la substitution')).
language(4,transword('evaluating negation shows',
'evaluation de negation montre que')).
language(4,transword('evaluating goal shows',
'evaluation de terme montre que')).
language(4,transword('uninstantiated','non-instancie')).
language(4,transword('using the instantiation','par l''instanciation')).
language(4,transword('and the substitution','et la substitution')).
language(4,transword('is variable-pure','pur variable')).
language(4,transword('is unrestricted','est sans duplication')).
language(4,transword('is a variable','est un variable')).
language(4,transword('the domain of','le domaine de')).
language(4,transword('by instantiating','par l''instanciation')).
% -----------------------------------------------------------------------
% VIETNAMESE DICTIONARY
% =======================================================================
language(15,transword(all,'tat-ca')).
language(15,transword(every,moi)).
language(15,transword(some,vai)).
language(15,transword(which,tim)).
language(15,transword(no,chang)).
language(15,transword(not,khong)).
language(15,transword(none,'chang-gi')).
language(15,transword(deny,'phu-nhan')).
language(15,transword(is,la)).
language(15,transword(true,that)).
language(15,transword(fact,'du-kien')).
language(15,transword(usergiven,'duoc-cung-cap')).
language(15,transword(nofact,'khong-du-kien')).
language(15,transword(system:true,hethong:dung)).
language(15,transword(system:false,hethong:sai)).
language(15,transword(nonterminate,'khong-ngung')).
language(15,transword(ok,cn)).
language(15,transword(more,nua)).
language(15,transword(how,lamsao)).
language(15,transword(find,tim)).
language(15,transword(base,'co-he')).
language(15,transword(with,voi)).
language(15,transword(certainty,'xac-suat')).
language(15,transword(number,so)).
language(15,transword(eq,bg)).
language(15,transword(dif,kh)).
language(15,transword(lt,nh)).
language(15,transword(gt,lh)).
language(15,transword(le,nb)).
language(15,transword(ge,lb)).
language(15,transword(lta,nha)).
language(15,transword(gta,lha)).
language(15,transword(lea,nba)).
language(15,transword(gea,lba)).
language(15,transword(in,trong)).
language(15,transword(fail,hong)).
language(15,transword(bye,het)).
language(15,transword(list,'liet-ke')).
language(15,transword(list,liet)).
language(15,transword(reload,molai)).
language(15,transword(load,mo)).
language(15,transword(load,load)).
language(15,transword('reading..........','dang mo..........')).
language(15,transword(save,cat)).
language(15,transword('Because','Boi vi')).
language(15,transword('IF','NEU')).
language(15,transword('THEN','THI')).
language(15,transword('is true','la dung')).
language(15,transword('is false','la sai')).
language(15,transword(' Type ok., how. or more.',
' Tra loi cn., lamsao. hoac nua.')).
language(15,transword(stop,ngung)).
language(15,transword('Illegal query !','Cau hoi bat hop le !')).
language(15,transword('No (more) answers !','Khong (con) giai-dap !')).
language(15,transword('No more explanations',
'Khong con giai thich nao')).
language(15,transword('No more explanations for this',
'Khong con giai thich nao')).
language(15,transword('Give a percentage on your certainty',
'Cho biet xac-suat phan tram')).
language(15,transword('I am','Toi xac-dinh')).
language(15,transword('positive that','rang')).
language(15,transword('has the form','co dang')).
language(15,transword('Bad clause!','Cau sai luat!')).
language(15,
transword('A clause cannot have more than one word "not","no","all".',
'Moi cau chi duoc dung mot trong cac chu "khong","chang","tat-ca".')).
language(15,transword('I dont know this concept. Check your typing',
'Toi khong ro cau nay. Xin kiem lai')).
language(15,transword('If this is a new concept, please teach me',
'Neu la khai-niem moi, thi hay chi toi')).
language(15,transword('using the substitution','dung thay the')).
language(15,transword('evaluating negation shows',
'xac-dinh phu-nhan chung to')).
language(15,transword('evaluating goal shows','xac-dinh muc-tieu chung to')).
language(15,transword('uninstantiated','khong thay doi')).
language(15,transword('using the instantiation','dung phep thay the')).
language(15,transword('and the substitution','va phep thay the')).
language(15,transword('is variable-pure','co bien-so thuan')).
language(15,transword('is unrestricted','khong trung lap')).
language(15,transword('is a variable','la mot bien-so')).
language(15,transword('the domain of','vung xac-dinh cua')).
language(15,transword('by instantiating','thay hang-so vao')).
%---------------------------------------------------------------------
% BUILTIN PREDICATES
% ====================================================================
builtin((predicate([Phrase,B],tvar_list(A,B)) :-
trans_word('using the substitution',Phrase))).
builtin((predicate([Phrase|PNA],eval_non(A,B)) :-
domain(A),
(predicate(PNA,non(A)),!;
predicate(PA,A),trans_word(deny,W),PNA = [W|PA]),
trans_word('evaluating negation shows',Phrase))).
builtin((predicate([Phrase|PA],eval(A)) :-
domain(A),predicate(PA,A),
trans_word('evaluating goal shows',Phrase))).
builtin((predicate([Phrase|PA],not(A)) :-
domain(A),predicate(PA,A),
trans_word(not,Phrase))).
builtin((predicate([Phrase|PA],not(call(A))) :-
domain(A),predicate(PA,A),
trans_word(not,Phrase))).
builtin((predicate([L,Phrase],uninstantiated(L)) :-
trans_word('uninstantiated',Phrase))).
builtin((predicate([Phrase,L],instantiate(A,L,VL)) :-
trans_word('using the instantiation',Phrase))).
builtin((predicate([Find|Phrase],tobe_filled(A)) :-
domain(A),predicate(Phrase,A),
trans_word(find,Find))).
builtin((predicate([Phrase],!) :- trans_word(stop,Phrase))).
builtin((predicate([Fail],fail) :- trans_word(fail,Fail))).
builtin((predicate([L,Phrase],tvar_pure(L)) :-
trans_word('is variable-pure',Phrase))).
builtin((predicate([L,Phrase],unrestricted(L,0)) :-
trans_word('is unrestricted',Phrase))).
builtin((predicate([Phrase,A],domain(A)) :-
trans_word('the domain of',Phrase))).
builtin((predicate([Phrase,L],instant(L,VL)) :-
trans_word('by instantiating',Phrase))).
builtin((predicate([A,Phrase],var(A)) :-
trans_word('is a variable',Phrase))).
builtin((predicate([(T,A),Is,(T,B)],(A = B)) :- trans_word(is,Is))).
builtin((predicate([(T,A),Op,(T,B)],(A is B)) :- (Op == '='))).
builtin((predicate([(T,A),Eq,(T,B)],(A =:= B)) :- trans_word(eq,Eq))).
builtin((predicate([(T,A),Dif,(T,B)],(A =\= B)) :- trans_word(dif,Dif))).
builtin((predicate([(T,A),Lt,(T,B)],(A < B)) :- trans_word(lt,Lt))).
builtin((predicate([(T,A),Gt,(T,B)],(A > B)) :- trans_word(gt,Gt))).
builtin((predicate([(T,A),Le,(T,B)],(A =< B)) :- trans_word(le,Le))).
builtin((predicate([(T,A),Ge,(T,B)],(A >= B)) :- trans_word(ge,Ge))).
builtin((predicate([(T,A),Lta,(T,B)],(A @< B)) :- trans_word(lta,Lta))).
builtin((predicate([(T,A),Gta,(T,B)],(A @> B)) :- trans_word(gta,Gta))).
builtin((predicate([(T,A),Lea,(T,B)],(A @=< B)) :- trans_word(lea,Lea))).
builtin((predicate([(T,A),Gea,(T,B)],(A @>= B)) :- trans_word(gea,Gea))).
builtin((predicate([(T,A),In,(list,B)],member(A,B)) :- trans_word(in,In))).
builtin((domain(A) :- nonvar(A),functor(A,F,N),(system(F/N);
member(F,[tvar_list,eval_non,eval,instantiate,
uninstantiated,member,tobe_filled])),!)).
builtin(constsymbol('$':'@')).
builtin(subtype('#','%')).
builtin(already_asked('@','#')).
%---------------------------------------------------------------------
% ESSLN META-INTERPRETER
% ====================================================================
prove(Goal,Depth,Certainty,Proof,Rules) :-
prove_branch(Goal,Depth,Certainty,Proof,Rules),
check_result(Goal,Depth,Certainty,Proof).
prove(Goal,Depth,0,FailProof,Rules) :-
collect_failproof(Goal,Depth,FailProof).
prove_branch(true,D,1,fact,Rules) :- !.
prove_branch(A,0,0,nonterminate,Rules) :- !.
prove_branch(call(A),D,C,Proof,Rules) :- !,
prove_branch(A,D,C,Proof,Rules).
prove_branch(not(A),D,C,(not(A) # C :- Proof),Rules) :- !,
copy(A,A1),collect_proof(A1,D,Rules,C,List),!,
convert(List,Proof).
prove_branch(all(A,B),D,C,(all(A,B) # C :- Proof),Rules) :- !,
prove_all(A,B,D,C,Proof,Rules).
prove_branch((A,B),D,C,(ProofA,ProofB),Rules) :- !,
prove_branch(A,D,CA,ProofA,Rules),
prove_conj(CA,B,D,C,ProofB,Rules).
prove_branch(A,D,C,(A # C :- system:R),Rules) :-
syst(A),!,(A, C = 1, R = true; not(A), C = 0, R = false).
prove_branch(A,D,C,(A # C :- Proof),Rules) :-
\+(find_clause((A # C),B)),!,
find_out(A,C,Proof,Rules).
prove_branch(A,D,C,(A # C :- Proof),Rules) :-
threshold(C0),
find_clause((A # RC),B),D1 is D-1,
detect_cut(B,B1,B2,Cut),
(Cut = yes,prove_branch(B1,D1,C1,Proof1,[(A # RC :- B)|Rules]),
(C1 < C0, C is RC*C1,return_proof(Proof1,B2,Proof);
C1 >= C0,!,prove_branch(B2,D1,C2,Proof2,[(A # RC :- B)|Rules]),
C is RC*C1*C2,conjunct(Proof1,Proof2,Proof));
Cut = no,prove_branch(B,D1,CB,Proof,[(A # RC :- B)|Rules]),
C is RC*CB).
detect_cut(B,B1,B2,yes) :- cutin(B,B1,B2),!.
detect_cut(_,_,_,no).
cutin(!,!,true) :- !.
cutin((!,B),!,B) :- !.
cutin((A,!),(A,!),true) :- !.
cutin((A,B),(A,As),Bs) :- cutin(B,As,Bs).
return_proof(Proof1,B,Proof) :-
B = true,!, Proof1 = Proof;
conjunct(Proof1,(B : nottried),Proof).
conjunct(A,fact,A) :- !.
conjunct((A,As),L,(A,Bs)) :- !,conjunct(As,L,Bs).
conjunct((A),L,(A,L)).
collect_proof(A,D,Rules,0,List) :-
threshold(T),asserta(bag(1,[],D)),
prove(A,D,C,P,Rules),
once(retract(bag(C0,L,D))),
C1 is C0* (1-C),asserta(bag(C1,[P|L],D)),
C1 < 1-T, retract(bag(_,List,D)),remove(answer(A,D)),!.
collect_proof(A,D,_,C,List) :-
retract(bag(C,List,D)),remove(answer(A,D)).
convert([P],P) :- !.
convert([P|L],(P,NP)) :-
convert(L,NP).
prove_all(A,B,D,C,Proof,Rules) :-
prove(A,D,CA,ProofA,Rules),
check_all(CA,ProofA,B,D,C,Proof,Rules).
prove_all(A,B,D,_,_,_) :-
remove(answer(A,D)),remove(save_all(B,D)),fail.
check_all(0,ProofA,B,D,0,ProofA,Rules) :- !.
check_all(_,_,B,D,C,ProofB,Rules) :-
\+((save_all(B1,D),instanc(B,B1))),
asserta(save_all(B,D)),
prove_branch(B,D,C,(B # C :- ProofB),Rules).
prove_conj(C,B,D,0,(B : nottried),Rules) :-
threshold(T), C < T,!.
prove_conj(CA,B,D,C,ProofB,Rules) :-
prove_branch(B,D,CB,ProofB,Rules),
C is CA*CB.
check_result(G,D,C,Proof) :-
threshold(C0), C < C0,!,
\+((failproof((G1,D):_),instanc(G,G1))),
assert(failproof((G,D):Proof)),fail.
check_result(G,D,C,Proof) :-
collect_failbranches(G,D,_),
(answer(G1,D1),D1 < D,retract(answer(G1,D1)),fail;
\+((answer(G1,D),instanc(G,G1))),save_answer(G,D)).
collect_failproof(G,D,FailProof) :-
collect_failbranches(G,D,FailList),
\+(answer(G,D)),convert(FailList,FailProof).
collect_failbranches(G,D,[FailBranch|Rest]) :-
copy(G,G1),retract(failproof((G1,D):FailBranch)),!,
collect_failbranches(G,D,Rest).
collect_failbranches(_,_,[]).
find_out(A,C,usergiven,Rules) :-
tobe_filled(A) # 1,!,
(already_asked(A,C),!; ask_user(A,C,Rules)).
find_out(A,0,nofact,_).
find_clause((A # RC),B) :- clause((A # RC),B).
%find_clause((A # RC),B) :-
% code_world(X,api),
% clause((A # RC),B),
% code_world(_,X).
save_answer(Goal,Depth) :-
trim_answer(Goal,Goal1),assert(answer(Goal1,Depth)).
trim_answer(all(A,B),all(_,B)) :- !.
trim_answer((A,B),(A1,B1)) :- !,
trim_answer(A,A1),trim_answer(B,B1).
trim_answer(A,A).
syst(A) :- functor(A,F,N),
(system(F/N),!;
member(F,['!',member,append,var_list,tvar_list,
uninstantiated,instantiate])).
copy(A,B) :- assert(zzzz(A)),retract(zzzz(B)).
maxdepth(20).
threshold(0.3).
remove(A) :- copy(A,B),retract(B),!,remove(A).
remove(_).
once(P) :- call(P),!.
%---------------------------------------------------------------------
% USER INTERFACE
% ====================================================================
% QUERYING USER
% --------------------------------------------------------------------
ask_user(Goal,C,Rules) :-
display_question(Goal),
read(Answer),
process_answer(Answer,Goal,C,Rules).
display_question(Goal) :-
trans_word(which,Q),
copy(Goal,Goal1),
nl,print_goal(Goal1,Q),write('? ').
process_answer(why,Goal,C,[Rule|Rules]) :- !,
display_rule(Rule),nl,
ask_user(Goal,C,Rules).
process_answer(why,Goal,C,[]) :- !,
nl,write(' > '),
write_word('No more explanations'),nl,
ask_user(Goal,C,[]).
process_answer(X,Goal,C,_) :-
var_list(Goal,[V]), V = X,
nl,tab(4),write_word('Give a percentage on your certainty'),
write(' : '),read(C1), C is C1/100,
assert(already_asked(Goal,C)).
% ANSWERING USER
% --------------------------------------------------------------------
process_response(ok,_) :- !.
process_response(more,_) :- !,fail.
process_response(how,(Proof1,Proof2)) :- !,
process_response(how,Proof1),
read_response(Response),
process_response(Response,Proof2).
process_response(how,(A # C :- Proof)) :- !,
recollect_body(Proof,Body),
display_proof((A # C :- Body)),
read_response(Response),!,
process_response(Response,Proof).
process_response(how,End) :-
nl,tab(4),write_word('No more explanations for this'),
read_response(Response),
process_response(Response,End).
recollect_body(B,(B,1)) :-
member(B,[fact,system:true,usergiven]),!.
recollect_body(B,(B,0)) :-
member(B,[nofact,system:false,nonterminate]),!.
recollect_body((B:nottried),(B:nottried,0)) :- !.
recollect_body((B # C :- D),(B,C)) :- !.
recollect_body(((B # C :- D),Rest),((B,Bs),(C,Cs))) :-
recollect_body(Rest,(Bs,Cs)).
%---------------------------------------------------------------------
% EXPLANATION GENERATOR
% ====================================================================
% DISPLAY RULE
% --------------------------------------------------------------------
display_rule((A # C :- true)) :- !,
copy(A,A1),
nl,write(' > '),write_word('Because'),
nl,tab(6),display_rule_body(A1,65,_),
nl,tab(4),write_word('is true'),
write_rule_certainty(C).
display_rule((A # C :- B)) :-
copy((A,B),(A1,B1)),
nl,write(' > '),write_word('Because'),
nl,tab(4),write_word('IF'),
nl,tab(6),display_rule_body(B1,65,NextChar),
nl,tab(4),write_word('THEN'),
nl,tab(6),display_rule_body(A1,NextChar,_),
write_rule_certainty(C).
display_rule_body(all(A,not(non(B))),Char,NextChar) :- !,
tvar_list(A,VL),bind_var_char(VL,Char,NextChar),
univ_quantify(yes,Q),print_goal(B,Q).
display_rule_body(all(non(A),not(B)),Char,NextChar) :- !,
tvar_list(A,VL),bind_var_char(VL,Char,NextChar),
univ_quantify(no,Q),print_goal(B,Q).
display_rule_body(not(non(A)),Char,Char) :- !,
univ_quantify(yes,Q),print_goal(A,Q).
display_rule_body(not(A),Char,Char) :- !,
univ_quantify(no,Q),print_goal(A,Q).
display_rule_body((A,B),Char,NextChar) :- !,
display_rule_body(A,Char,Char1),
nl,tab(6),display_rule_body(B,Char1,NextChar).
display_rule_body(A,Char,NextChar) :-
tvar_list(A,VL),bind_var_char(VL,Char,NextChar),
print_goal(A,_).
% DISPLAY PROOF
% --------------------------------------------------------------------
display_proof((A # C :- (B,1))) :-
member(B,[fact,system:true,usergiven]),!,
nl,write(' > '),write_word('Because'),
nl,tab(6),copy(A,A1),display_goal(A1,yes),
nl,tab(4),write_word(is),write(' '),write_word(B),
write(' '),write_rule_certainty(C).
display_proof((A # 0 :- (B,0))) :-
member(B,[nofact,system:false,nonterminate]),!,
nl,write(' > '),write_word('Because'),
nl,tab(6),copy(A,A1),display_goal(A1,some),
nl,tab(4),write_word(is),write(' '),write_word(B).
display_proof((A # C :- Body)) :-
nl,write(' > '),write_word('Because'),
nl,tab(4),write_word('IF'),
nl,tab(6),display_proof_body(Body),
nl,tab(4),write_word('THEN'),
nl,tab(6),display_proof_body((A,C)).
display_proof_body(((B,Bs),(C,Cs))) :- !,
display_proof_body((B,C)),
nl,tab(6),display_proof_body((Bs,Cs)).
display_proof_body((B:nottried,C)) :- !,
write('...').
display_proof_body((B,C)) :-
(C = 0,!,Q = some; Q = yes),
copy(B,B1),
display_goal(B1,Q),
write_rule_certainty(C).
% DISPLAY GOALS
% --------------------------------------------------------------------
display_goal(all(A,not(non(B))),S) :- !,
univ_quantify(S,Q),univ_quantify(yes,Q1),
tvar_list(A,VL),bind_vars(VL,Q),
print_goal(B,Q1).
display_goal(all(non(A),not(B)),S) :- !,
univ_quantify(S,Q),univ_quantify(no,Q1),
tvar_list(A,VL),bind_vars(VL,Q),
print_goal(B,Q1).
display_goal(not(non(A)),S) :- !,
(S = no,!,univ_quantify(some,Q),print_goal(non(A),Q);
univ_quantify(yes,Q), print_goal(A,Q)).
display_goal(not(A),S) :- !,
(S = no,!,univ_quantify(some,Q),print_goal(A,Q);
ground(A),!,print_goal(non(A),_);
univ_quantify(no,Q), print_goal(A,Q)).
display_goal(non(A),S) :- !,
(S = no,!,univ_quantify(yes,Q),print_goal(A,Q);
univ_quantify(S,Q), print_goal(non(A),Q)).
display_goal((A,B),no) :- !,
(ground((A,B)),!,write_word(no); write_word(none)).
display_goal((A,B),yes) :- !,
display_goal(A,yes),
nl,tab(4),display_goal(B,yes).
display_goal(A,S) :-
(S = no,ground(A),!,print_goal(non(A),_);
univ_quantify(S,Q),print_goal(A,Q)).
univ_quantify(yes,Q) :- trans_word(all,Q).
univ_quantify(no,Q) :- trans_word(no,Q).
univ_quantify(some,Q) :- trans_word(some,Q).
% PRINT GOALS
% --------------------------------------------------------------------
print_goal(non(call(A)),Q) :- !,print_goal(non(A),Q).
print_goal(non(A),Q) :- !,
domain(A),
(predicate(PNA,non(A)),!,print_phrase(PNA,Q);
predicate(PA,A),negate_quantify(Q,Q1,W),
print_phrase([W|PA],Q1)).
print_goal(A,Q) :-
domain(A),
predicate(Phrase,A),!,
print_phrase(Phrase,Q).
print_goal(call(A),Q) :- !,
print_goal(A,Q).
print_goal(A,Q) :-
write(Q),write(' '),write(A).
print_phrase([],_) :- !.
print_phrase([(T,S:X)|Rest],Q) :- !,
(var(X),!,write_list([Q,' ',S,' ']);
quantifier(X),!,write_list([X,' ',S,' ']);
write_list([T,' ',X,' '])),
print_phrase(Rest,Q).
print_phrase([W|Rest],Q) :-
write_list([W,' ']),
print_phrase(Rest,Q).
negate_quantify(Q,Q1,W) :-
trans_word(deny,W),
(trans_word(some,Q),trans_word(all,Q1);
trans_word(all,Q),trans_word(some,Q1)).
quantifier(X) :- trans_word(W,X),member(W,[all,no,some]).
%---------------------------------------------------------------------
% META-PROGRAMMING TOOLS
% ====================================================================
% BIND VARIABLES
% --------------------------------------------------------------------
bind_var_char([],Char,Char) :- !.
bind_var_char([T:X|Xs],Char,NextChar) :-
name(X,[Char]),Char1 is Char + 1,
bind_var_char(Xs,Char1,NextChar).
bind_vars([],_) :- !.
bind_vars([T:S|Xs],S) :- bind_vars(Xs,S).
ground(A) :- copy(A,B), A == B.
bind_var([],_) :- !.
bind_var(['$@#'(N)|Vs],N) :- N1 is N+1,bind_var(Vs,N1).
instanc(A,B) :-
ground(A),!,A = B.
instanc(A,B) :-
functor(A,F,N),functor(B,F,N),
var_list(A,VL),bind_var(VL,1),A = B.
% -------------------------------------------------------------------
% FIND THE VARIABLES OF A GOAL
% ===================================================================
var_list(A,[]) :- ground(A),!.
var_list(A,L) :- collect_var(A,Q-[]),
% setof(X,member(X,Q),L).
elim_dup(Q,[],L).
collect_var(A,Q-Q) :- constant(A),!.
collect_var(A,[A|Q]-Q) :- var(A), !.
collect_var(A,Q) :- A =.. [P|Args],collect_vars(Args,Q).
collect_vars([],Q-Q) :- !.
collect_vars([A|As],Q-Qt) :-
collect_var(A,Q-Qs),collect_vars(As,Qs-Qt).
constant(A) :- atom(A); integer(A); float(A).
elim_dup([],_,[]).
elim_dup([X|Xs],L,L1) :- occurs(X,L),!,elim_dup(Xs,L,L1).
elim_dup([X|Xs],L,[X|L1]) :- elim_dup(Xs,[X|L],L1).
occurs(T:X,_) :- nonvar(X).
occurs(X,[Y|Ys]) :- X == Y; occurs(X,Ys).
%--------------------------------------------------------------------
% EXTRACT VARIABLE SYMBOLS FROM A FORMULA
% ===================================================================
list_var_symbols(L,Q,VT,VS) :-
append(A,[B,C|D],L),
(quote_found(Q,B,Q1),!,
list_var_symbols([C|D],Q1,VT,VS);
var_found(Q,B,C),!,
append(A1,[C1|D1],[C|D]),not(valid(C1)),!,
name(V,A1),
(member(V,VT),\+(V = '_'), VS = VS1,!; VS = [V|VS1]),
list_var_symbols([C1|D1],0,[V|VT],VS1)).
list_var_symbols(_,_,_,[]).
quote_found(0,B,B) :- member(B,[34,36,39]),!.
quote_found(Q,Q,0).
var_found(0,B,C) :- \+(valid(B)),var_start(C).
var_start(C) :- (65 =< C,C =< 90);C = 95.
valid(C) :- (65 =< C, C =< 90); % A - Z
(97 =< C, C =< 122); % a - z
(48 =< C, C =< 57); % 0 - 9
C = 95; C = 45. % underscore; hyphen
member(X,[X|_]).
member(X,[_|T]) :- member(X,T).
append([],L,L).
append([H|T],L,[H|R]) :- append(T,L,R).
%---------------------------------------------------------------------
% ESSLN LOGICAL NEGATION EVALUATOR
% ====================================================================
builtin((non(A) # 1 :- tvar_list(A,L),eval_non(A,L))).
builtin((eval_non(A,L) # 1 :- not(A),!)).
builtin((eval_non(A,L) # 1 :- eval(A),uninstantiated(L),!,fail)).
builtin((eval_non(A,L) # 1 :- instantiate(A,L,VL),eval_non(A,VL))).
builtin((eval(A) # 1 :- A,!)).
uninstantiated(L) :- tvar_pure(L),unrestricted(L,0).
tvar_pure([]) :- !.
tvar_pure([T:V|TVs]) :- var(V),tvar_pure(TVs).
unrestricted([],_) :- !.
unrestricted([T:N|TVs],N) :- N1 is N+1,unrestricted(TVs,N1).
instantiate(A,L,VL) :- domain(A),instant(L,VL).
instant([X|Xs],Xs) :- get_term(X,Xs).
instant([X|Xs],[X|VL]) :- instant(Xs,VL).
get_term(T:V,TVs) :- constsymbol(T:V).
get_term(X,Xs) :- get_var(X,Xs).
get_var(T:V,[T:V|TVs]).
get_var(X,[Y|Xs]) :- get_var(X,Xs).
tvar_list(A,[]) :- ground(A),!.
tvar_list(A,L) :- A =.. [P|Args],
% setof(T:X,(member(T:X,Args),var(X)),L).
elim_dup(Args,[],L).
%====================================================================
% PRINT PROOF
print_proof(Proof) :-
printp(Proof,1),
get0(C),get0(D),get0(E).
printp((A,B),N) :- !,
nl,write('<'), printq(A,N), write('>'),
printp(B,N).
printp(A,N) :-
nl,write('<'), printq(A,N), write('>').
printq((A,B),N) :- !,
printq(A,N),nl,write(' '),printq(B,N).
printq((A :- B),N) :- !,
write_space(N),write(A),write(' :- '),
get0(C),N1 is N+1,
nl,write(' '),printq(B,N1).
printq(A,N) :-
write_space(N),write(A),
get0(C).
write_space(0) :- !.
write_space(N) :-
write(' '),N1 is N-1,write_space(N1).
% --------------------------------------------------------------------
% DISPLAY ESSLN'S BANNER
% ====================================================================
display_banner :-
% cls,
banner,
get0(C),(C = 101,!,fail; true).
banner :-
nl,nl,
tab(4),put(218),place(65,196),put(191),nl,
blankline,
halfline(l,15),put(194),place(7,196),put(191),tab(13),put(194),
halfline(r,27),
halfline(l,15),put(179),tab(21),put(179),tab(6),put(194),
place(5,196),put(191),halfline(r,14),
halfline(l,15),put(179),tab(6),put(218),place(6,196),tab(8),
put(179),tab(6),put(179),tab(5),put(179),halfline(r,14),
halfline(l,15),put(195),place(4,196),put(180),put(32),put(179),
tab(6),put(218),place(6,196),put(32),put(179),tab(6),
put(179),tab(5),put(179),halfline(r,14),
halfline(l,15),put(179),tab(6),put(192),place(5,196),put(191),
put(179),tab(7),put(179),tab(6),
put(179),tab(5),put(179),halfline(r,14),
halfline(l,15),put(179),tab(12),put(179),put(192),place(5,196),
put(191),put(32),put(179),tab(6),
put(179),tab(5),put(179),halfline(r,14),
halfline(l,15),put(193),place(7,196),put(217),tab(4),
put(179),tab(6),put(179),put(32),put(193),
place(5,196),put(217),put(193),
tab(5),put(193),halfline(r,14),
halfline(l,19),place(9,196),put(217),tab(6),put(179),
halfline(r,29),
halfline(l,26),place(9,196),put(217),halfline(r,29),
blankline,
halfline(l,16),write('A MULTILINGUAL EXPERT SYSTEM SHELL'),
halfline(r,15),
halfline(l,17),write('THAT SUPPORTS QUANTIFIED QUERIES'),
halfline(r,16),
blankline,
halfline(l,12),write('Copyright : Van Le, University of Canberra'),
halfline(r,11),
tab(4),put(192),place(65,196),put(217),nl,
tab(5),write('Press any key to start, "e" to exit').
blankline :-
tab(4),put(179),tab(65), put(179),nl.
halfline(_,0).
halfline(l,N) :- tab(4),put(179),tab(N).
halfline(r,N) :- tab(N),put(179),nl.
place(0,_).
place(N,C) :- put(C), M is N - 1, place(M,C).
%-------------------------------------------------------------
display_languages :-
% cls,
nl,nl,
tab(16),write('PLEASE CHOOSE A LANGUAGE FOR OUR CONVERSATION'),
nl,nl,nl,
tab(16),write('1. Algerian'),
tab(20),write(' 9. Philippino'),nl,
tab(16),write('2. Dutch'),
tab(23),write('10. Portuguese'),nl,
tab(16),write('3. English'),
tab(21),write('11. Romanian'),nl,
tab(16),write('4. French'),
tab(22),write('12. Senegalese'),nl,
tab(16),write('5. Indonesian'),
tab(18),write('13. Spanish'),nl,
tab(16),write('6. Italian'),
tab(21),write('14. Swedish'),nl,
tab(16),write('7. Moroccain'),
tab(19),write('15. Vietnamese'),nl,
tab(16),write('8. Norwegian'),
tab(19),write('16. Other'),nl,nl,
tab(16),write('Your language of choice: ').
learn_new(Language) :-
tab(16),write('This language is not available in this package.'),
nl,tab(16),write('Please use English, French or Vietnamese.'),
pause(2000),choose_language.
pause(0).
pause(N) :-
N > 0, N1 is N-1,
pause(N1).
% ====================================================================
% ============================ END ESSLN =============================
% ====================================================================
| pschachte/groundness | benchmarks/essln.pl | Perl | apache-2.0 | 56,078 |
#!/usr/bin/perl
use Reader;
use Graph;
$runClosure = 1;
$runReduction = 1;
$indir = 'DATA/IN';
$outdir = 'DATA/OUT';
$doc = 'ABC19980108.1830.0711.tml';
$doc = 'ABC19980114.1830.0611.tml';
#$doc = 'ABC19980304.1830.1636.tml';
#$doc = 'APW19980227.0489.tml';
#$doc = 'wsj_0006.tml';
$in = @ARGV ? shift @ARGV : "$indir/$doc";
$out = @ARGV ? shift @ARGV : "$outdir/$doc";
$compositions = 'rule_creation/compositions_short.txt';
if ((-d $in) and (-d $out)) { &processDir($in, $out); }
elsif (-f $in) { &processFile($in, $out); }
else { print "Warning: couldn't process $in\n"; }
sub processDir
{
my ($indir, $outdir) = @_;
opendir DIR, $indir or die "ERROR: cannot open directory $indir\n";
foreach $file (readdir DIR) {
next if $file eq 'ABC19980304.1830.1636.tml';
next if $file eq 'APW19980213.1320.tml';
next if $file eq 'APW19980227.0489.tml';
&processFile("$indir/$file", "$outdir/$file") if (-f "$indir/$file");
}
}
sub processFile
{
my ($infile, $outfile) = @_;
print "$infile\n";
my $debug = 1;
$reader = Reader->new($infile, $compositions);
$reader->readAnnotation();
$reader->readCompositions();
$graph = Graph->new($infile);
$graph->initialize($reader);
$reader->cleanup;
$graph->pp(0,0,0) if $debug;
print ">> GRAPH initialization " if $debug;
$graph->printStats if $debug;
print ">> GRAPH closure " if $debug;
$graph->closeMe;
if ($graph->inconsistencyFound) {
print "INCONSISTENT GRAPH\n";
return; }
$graph->printStats if $debug;
$graph->reduce;
$reader->updateTLinks($graph->edges);
$reader->printFile($outfile);
}
| tarsqi/ttk | deprecated/sputlink/sputlink.pl | Perl | apache-2.0 | 1,665 |
#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG
#
# Copyright 2003,2016 IBM International Business Machines Corp.
#
# 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.
#
# IBM_PROLOG_END_TAG
use Getopt::Long;
#Preliminary checks for opensm and Mellanox OFED
$opensm_path="/usr/sbin/opensm";
$opensm_service_path="/etc/init.d/opensmd";
$opensm_pid="/var/run/opensm.pid";
$opensm = 0;
$opensmd = 0;
$quiet = 0;
$device="";
$port=0;
$all = 0;
GetOptions("q"=>\$quiet, # Be quiet, only relevent info dumped.
"a"=>\$all, # query all Mellanox device.
"d=s"=>\$device, # if specific device needs to be queried.
"p=s"=>\$port); # if specific device's port state needs to be queried.
print("Command line invocation : quiet=$query, device=$device, port=$port \n") if(!$quiet);
if(-e $opensm_pid) { #OpenSM Already running
$opensmd = 1;
} elsif (-e $opensm_service_path) { # Try starting OpenSM Service
print("OpenSMD Daemon present, will start in daemon mode \n") if(!$quiet);
$rc = `service opensmd start`;
sleep(60);
if( -e $opensm_pid) {
print("opensm daemon successfully started \n") if(!$quiet);
$opensmd = 1;
} else {
print("opensm daemon failed to start, Refer /var/log/opensm.log for more information. \n") if(!$quiet);
$opensmd = 0;
}
} else {
$opensmd = 0;
print("OpenSM service not present \n") if(!$quiet);
}
if ( -e $opensm_path) { # Check if open sm binary is present.
$opensm = 1;
} else { # Cannot do anything w/o opensm, exit ...
$opensm = 0;
print("OpenSM not installed \n") if(!$quiet);
exit(1);
}
#Now start quering devices
@ib_devices=&get_ib_devices();
if($all) {
exit(0);
}
foreach $ib_device (@ib_devices) {
$ib_device=&trim($ib_device);
local($i);
$path="/sys/class/infiniband/$ib_device";
if(!(-d $path)) {
print("Device not configured ib_device=$ib_device \n") if(!$quiet);
exit(2);
}
@port = &get_port_numbers($ib_device);
for($i=0; $i < &num_ports($ib_device); $i++ ) {
$port[$i] = &trim($port[$i]);
print("Querying for dev=$ib_device, port=$port[$i] \n") if(!$quiet);
$state=&get_port_state($ib_device, $port[$i]);
#Get GID for
$guid=&get_node_guid($ib_device);
if($state =~/DOWN/i) {
print("No port to port connection seems to be presnet. Device=$ib_device, port=$port[$i], state=$state \n") if(!$quiet);
exit(3);
} elsif($state =~/INIT/) {
if($opensm == 1) { # if OpenSMD is not running then this is expected
#try running opensm binary to get port to active state.
$rc = &run_opensm_on_ports($ib_device, $port[$i], $guid);
if(rc != 0) {
print(" Check for incompatible cables. Device=$ib_device, port=$port[$i], state=$state\n") if(!$quiet);
exit(4);
}
} else {
print("Port to port connection detected, but incompatible cables used. Device=$ib_device, port=$port[$i], state=$state \n") if(!$quiet);
}
} elsif($state =~ /ACTIVE/) {
print("Ports ACTIVE, good to run DMA & MMIO's. Device=$ib_device, port=$port[$i], state=$state \n") if(!$quiet);
} else {
print("Unknown port state. Device=$ib_device, port=$port[$i], state=$state \n") if(!$quiet);
}
}
}
exit(0);
############################################################################################################################
# Function Definition
############################################################################################################################
sub run_opensm_on_ports() {
local($ib_device, $port, $guid) = @_;
$retry=0;
do {
print ("Running command : $opensm_path -g $guid -o, retry=$retry \n") if(!$quiet);
`$opensm_path -g $guid -o`;
$state=&get_port_state($ib_device, $port);
if($state =~ /ACTIVE/) {
print("Port ACTIVE, good to run DMA & MMIO's. Device=$ib_device, port=$port, state=$state \n") if(!$quiet);
return(0);
}
$retry++;
sleep($retry);
} while($retry < 5);
$state=&get_port_state($ib_device, $port);
if($state =~ /ACTIVE/) {
print("Port ACTIVE, good to run DMA & MMIO's. Device=$ib_device, port=$port, state=$state \n") if(!$quiet);
return(0);
} else {
print("OpenSM could not bring ports to active state. Device=$ib_device, port=$port, state=$state\n") if(!$quiet);
return(5);
}
return(0);
}
sub get_port_state() {
local($dev, $port)=@_;
$dev=&trim($dev);
$port=&trim($port);
$path="/sys/class/infiniband/$dev/ports/$port/state";
$state=`cat $path | cut -d : -f 2 `;
$state=&trim($state);
print("$state \n");
return($state);
}
sub get_node_guid() {
local($dev) = @_;
$dev=&trim($dev);
$path="/sys/class/infiniband/$dev/node_guid";
$guid=`cat $path`;
# remove delimiter to get complete qualified string
@array=split(/:/,$guid);
$guid_string="0x". join('', @array);
print("Device=$dev, GUID = $guid_string \n") if(!$quiet);
$guid_string=&trim($guid_string);
return($guid_string);
}
sub num_ports() {
local($dev)=@_;
$dev=&trim($dev);
$path="/sys/class/infiniband/$dev/ports/";
$num_ports=`ls $path | wc -l`;
if($port > 0) {
#port to be queried specified from command line, query for that port only
$num_ports = 1;
}
return($num_ports);
}
sub get_port_numbers() {
local($dev)=@_;
$dev=&trim($dev);
if($port > 0) {
$port = &trim($port);
$path="/sys/class/infiniband/$dev/ports/$port";
if(!(-d $path)) {
print(" Input port=$port for dev=$dev, Device doesnot exists \n") if(!$quiet);
exit(1);
}
$port_number[0]=$port;
} else {
$path="/sys/class/infiniband/$dev/ports/";
@port_number=`ls $path`;
}
print("Device=$dev, port_number=@port_number \n") if(!$quiet);
return(@port_number);
}
sub get_ib_devices() {
@available_devices="";
$num_devices = 0;
if($device =~ /mlx/) {
$configured_ib_devices[$num_devices] = &trim($device);
$path="/sys/class/infiniband/$configured_ib_devices[$num_devices]";
if(!(-d $path)) {
print(" $configured_ib_devices[$num_devices]. Device doesnot exists \n") if(!$quiet);
exit(1);
}
} else {
@configured_ib_devices = `ibstat -l`;
}
$num_devices = 0;
foreach $ib_dev (@configured_ib_devices) {
chomp($configured_ib_devices);
#should be of form mlx
if($ib_dev =~ /mlx/) {
$ib_dev=&trim($ib_dev);
$available_devices[$num_devices]=$ib_dev;
$num_devices = $num_devices + 1;
} else {
print("Unknown device = $ib_dev. ignoring \n") if(!$quiet);
}
}
print("Discovered following devices = @available_devices \n") if(!$quiet || $all);
return(@available_devices);
}
sub trim {
local($string) = @_;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
| open-power/HTX | bin/hxediag/ib_info.pl | Perl | apache-2.0 | 7,348 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
ArrayAdaptor - A generic array adaptor for HDF5 files
=cut
use strict;
use warnings;
use Getopt::Long;
use List::MoreUtils qw/ zip /;
use File::Copy qw/ copy /;
use File::Temp qw/ tempfile /;
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::HDF5::EQTLAdaptor;
$| = 1; # Autoflushes all print statements
Bio::EnsEMBL::HDF5::set_log(2); # Small talk from the C layer
main();
sub main {
my $options = get_options();
my $registry = 'Bio::EnsEMBL::Registry';
$registry->load_registry_from_db(
-host => $options->{host},
-user => $options->{user},
-pass => $options->{pass},
-port => $options->{port},
-db_version => 73,
);
my $eqtl_adaptor = Bio::EnsEMBL::HDF5::EQTLAdaptor->new(
-filename => $options->{hdf5},
-core_db_adaptor => $registry->get_DBAdaptor('human', 'core'),
-var_db_adaptor => $registry->get_DBAdaptor('human', 'variation'),
);
my $results = $eqtl_adaptor->fetch( {
gene => $options->{gene},
tissue => $options->{tissue},
snp => $options->{snp},
statistic => $options->{statistic},
chromosome => $options->{chromosome},
position => $options->{position},
});
print scalar(@$results)."\n";
print join("\t", qw/tissue snp gene statistic value chromosome position/)."\n";
foreach my $result (@$results) {
foreach my $column (qw/tissue snp gene statistic value chromosome position/) {
if (defined $options->{$column}) {
print "*$options->{$column}\t";
} else {
print "$result->{$column}\t";
}
}
print "\n";
}
$eqtl_adaptor->close;
}
sub get_options {
my %options = ();
GetOptions(\%options, "help=s", "host|h=s", "port|p=s", "user|u=s", "pass|p=s", "tissue=s", "gene=s", "snp=s", "statistic=s", "hdf5=s", "sqlite3|d=s");
if (defined $options{tissues}
&& defined $options{files}
&& (scalar @{$options{tissues}} != scalar @{$options{files}})) {
die("You should provide as many tissue names as filenames!");
}
return \%options;
}
| Ensembl/ensembl-hdf5 | scripts/query_eqtl_table.pl | Perl | apache-2.0 | 3,026 |
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#
# vim: set ts=2 sw=2 tw=0:
# vim: set expandtab:
package Rex::Virtualization::LibVirt::clone;
use strict;
use warnings;
our $VERSION = '0.56.1'; # VERSION
use Rex::Logger;
use Rex::Commands::Run;
use Rex::Helper::Run;
use XML::Simple;
use Data::Dumper;
sub execute {
my ( $class, $vmname, $newname ) = @_;
unless ($vmname) {
die("You have to define the vm name!");
}
unless ($newname) {
die("You have to define the new vm name!");
}
i_run
"/usr/bin/virt-clone --connect qemu:///system -o '$vmname' -n '$newname' --auto-clone";
}
1;
| gitpan/Rex | lib/Rex/Virtualization/LibVirt/clone.pm | Perl | apache-2.0 | 613 |
#!/usr/bin/perl
use strict;
use Cwd;
use File::Spec;
use File::Basename;
use Cwd 'abs_path';
=head
=cut
# directory of where this script is called
my $cwd = dirname($0);
sub usage {
print "\nUsage: " . basename($0) . " [ INPUT-DIR ] [ OUTPUT-FILE ] ";
}
if ( @ARGV != 2 ) {
usage;
print "\n\n\tPlease ensure to have 2 agruments:\n\t\tinput directory of emaf files\n\t\toutput training file name\n\n";
exit (1);
}
my ($INPUT_DIR) = abs_path($ARGV[0]);
my ($OUTPUT_FILE) = $ARGV[1];
#java -jar /.mounts/labs/hudsonlab/public/qtrinh/svn/isown/bin/REFORMVCF_v1.0.jar -vcfFolder ./ -output ./Project_final_Sept2016.emaf
#java -jar /.mounts/labs/hudsonlab/public/qtrinh/svn/isown/bin/ARFFgenerator_v1.0.jar -input Project_final_Sept2016.emaf -output ./myarfffile.arff
printf "\nReformat files in '$INPUT_DIR' to emaf ... \n\n";
system "java -jar ${cwd}/../bin/REFORMVCF_v1.0.jar -vcfFolder $INPUT_DIR -output ${OUTPUT_FILE}.emaf";
printf "\nGenerate training data set for '$INPUT_DIR' ... \n\n";
system "java -jar ${cwd}/../bin/ARFFgenerator_v1.0.jar -input ${OUTPUT_FILE}.emaf -output ${OUTPUT_FILE}";
printf "\n\nDone\n\n";
| ikalatskaya/ISOWN | bin/generate_training_data_set.pl | Perl | apache-2.0 | 1,148 |
#!/usr/bin/env perl
#
# huebro.pl - Monitors, logs and restores Philips Hue light bulb states after a power failure.
#
# Copyright 2015 - Jan Fredrik Leversund <kluzz@radical.org>
#
# 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.
#
########################## USER CONFIGURABLE SECTION ########################
# How many lights must be in the default state before we assume a power failure happened?
# Keep in mind this only works with lights of the type "Extended color light". You can check
# this using this script's 'current' command.
use constant MAGIC_NUMBER => 1;
# URL for the local bridge. If the script runs slowly, use the IP address instead of hostname.
use constant BRIDGE => 'http://192.168.2.16';
# The default is suitable for unix; you might want to change it on other platforms.
use constant HOMEDIR => "$ENV{HOME}/.huebro";
########################## END OF USER CONFIGURABLE SECTION ########################
# You probably don't need to change these
use constant KEYFILE => 'huebro.key';
use constant DBFILE => "huebro.db";
use constant LOGFILE => "huebro.log";
# This is the default state for a newly powered bulb
use constant DEF_TYPE => 'Extended color light';
use constant DEF_COLORMODE => 'ct';
use constant DEF_CT => 369;
use constant DEF_BRI => 254;
# Current version
use constant VERSION => "1.1.1";
# Just grab a time stamp
use constant TIME => time;
use constant HELP => q{
Usage: huebro.pl [-d] <command>
-v - Be verbose about what happens (writes log to STDOUT).
-d - Switch on debugging output. Usually very annoying.
Commands:
reg - Push the link button on the bridge, then run this command to
register the application.
unreg - Un-register this application from the bridge.
check - Check and log the light states, determining if a power failure
has occurred, reverting the lights to a previous state if
necessary. Run this at suitable intervals using cron or some
other form of scheduler.
current - Show the current state of all lights, according to the bridge.
previous - Show the previous state of all lights, according to the
database.
lookup - Prints a lookup table containing light id and name, suitable
for use with Splunk, etc.
version - Show the program version.
};
use Data::Dumper;
use DBI;
use LWP::UserAgent;
use JSON;
use Getopt::Std;
use Time::HiRes qw(usleep nanosleep);
use POSIX;
use common::sense;
# Read command line switches
my %opts = ();
getopts('dv', \%opts);
my $DEBUG = $opts{d};
my $VERBOSE = $opts{v};
# Make sure our storage directory exists.
mkdir HOMEDIR unless -d HOMEDIR;
die "Unable to create directory " . HOMEDIR . ": $!\n" unless -d HOMEDIR;
# Open the log file
my $lf = HOMEDIR . '/' . LOGFILE;
open(LOG, '>>:utf8', $lf)
or die "Unable to open log file " . $lf . ": $!\n";
# Unicode output
binmode(STDOUT, ":utf8");
# Read the API key, if possible.
my $KEY = read_key();
# Set up the user agent
my $ua = LWP::UserAgent->new;
$ua->timeout(5);
$ua->env_proxy;
# Open/create the database file
my $dbh = DBI->connect("dbi:SQLite:dbname=" . HOMEDIR . "/" . DBFILE, "", "")
or die "Unable to open or create the database file " . HOMEDIR . "/" . DBFILE . ": $!\n";
$dbh->{sqlite_unicode} = 1;
# Make sure the database is set up properly
check_database($dbh);
# Prepare all database statements.
my $sth = prepare_statements();
# Command selector
if ($ARGV[0] eq 'check')
{
command_check();
}
elsif ($ARGV[0] eq 'reg')
{
command_reg();
}
elsif ($ARGV[0] eq 'unreg')
{
command_unreg();
}
elsif ($ARGV[0] eq 'current')
{
command_current();
}
elsif ($ARGV[0] eq 'previous')
{
command_previous();
}
elsif ($ARGV[0] eq 'lookup')
{
command_lookup();
}
elsif ($ARGV[0] eq 'version')
{
command_version();
}
else
{
die HELP;
}
sub read_key
{
open(my $fh, "<", HOMEDIR . "/" . KEYFILE)
or return undef;
my $key = <$fh>;
$key =~ s/[\r\n]+//g;
$key;
}
sub write_key
{
my $key = shift;
open(my $fh, ">", HOMEDIR . "/" . KEYFILE)
or die "Unable to open key file for writing: $!\n";
print $fh "$key\n";
close($fh);
}
sub check_key
{
unless (defined $KEY)
{
logthis("No API key found! Use the 'reg' command to register with the bridge.");
exit 1;
}
}
sub command_check
{
check_key();
logthis("Attempting to fetch light info from bridge %s...", BRIDGE);
my ($code, $json) = get(sprintf("%s/api/%s/lights", BRIDGE, $KEY));
if (ref($json) eq 'ARRAY' and defined $json->[0]{error})
{
print Dumper($json) if $DEBUG;
logthis("Fetching light info from bridge %s failed: %s", BRIDGE, $json->[0]{error}{description});
return;
}
logthis("Done.");
my $curr_lights = parse_lights($json);
print Dumper($curr_lights) if $DEBUG;
# Do we need to restore a previous state?
my $needs_restore = check_lights($curr_lights);
logthis("Magic number of lights in default state has been reached (%d); state restoration required.", MAGIC_NUMBER) if $needs_restore;
# Grab a snapshot of the previous lights and states
my $prev_lights = previous_lights();
# Start a new transaction
$dbh->begin_work;
# Any new lights?
my $new_lights = 0;
foreach my $uid (keys %{$curr_lights})
{
unless (exists $prev_lights->{$uid})
{
# Add a new light.
my $rowid = insert_light($curr_lights->{$uid});
insert_meta($curr_lights->{$uid}, $rowid);
insert_state($curr_lights->{$uid}, $rowid);
$new_lights++;
}
}
# If any new lights were inserted, refresh the previous snapshot.
$prev_lights = previous_lights() if $new_lights;
if ($needs_restore)
{
restore_lights($curr_lights, $prev_lights);
}
else
{
new_snapshot($curr_lights, $prev_lights);
}
# Commit the work
$dbh->commit or die $dbh->errstr;
logthis("No changes since last check.") unless $new_lights or $needs_restore;
}
sub command_reg
{
my ($code, $json) = post(BRIDGE . '/api', {devicetype => "Hue#Bro"});
if (defined $json->[0]{error})
{
logthis("Registration attempt on bridge %s failed: %s", BRIDGE, $json->[0]{error}{description});
}
else
{
write_key($json->[0]{success}{username});
logthis("Successfully registered with bridge %s.", BRIDGE);
}
print Dumper($json) if $DEBUG;
}
sub command_unreg
{
check_key();
my ($code, $json) = post(sprintf('%s/api/%s/config/whitelist/%s', BRIDGE, $KEY, $KEY), {}, 'DELETE');
if (defined $json->[0]{error})
{
logthis("Unregistration attempt from bridge %s failed: %s", BRIDGE, $json->[0]{error}{description});
}
else
{
logthis("Unregistered with bridge %s.\n", BRIDGE);
}
print Dumper($json) if $DEBUG;
}
sub command_current
{
check_key();
my ($code, $json) = get(sprintf("%s/api/%s/lights", BRIDGE, $KEY));
if (ref($json) eq 'ARRAY' and defined $json->[0]{error})
{
print Dumper($json) if $DEBUG;
printf("Fetching light info from bridge %s failed: %s", BRIDGE, $json->[0]{error}{description});
return;
}
my $lights = parse_lights($json);
foreach my $uid (sort { $lights->{$a} <=> $lights->{$b} } keys %{$lights})
{
my $l = $lights->{$uid};
print_light(
$l->{id},
$l->{name},
$uid,
$l->{modelid},
$l->{type},
$l->{swversion},
$l->{state}{reachable} ? "yes" : "no",
$l->{state}{on} ? "yes" : "no",
$l->{state}{colormode},
$l->{state}{ct},
$l->{state}{xy}[0],
$l->{state}{xy}[1],
$l->{state}{hue},
$l->{state}{sat},
$l->{state}{bri},
$l->{state}{effect},
$l->{state}{alert}
);
}
}
sub command_previous
{
my $lights = previous_lights();
foreach my $uid (sort { $lights->{$a}{meta}{id} <=> $lights->{$b}{meta}{id} } keys %{$lights})
{
my $l = $lights->{$uid};
print_light(
$l->{meta}{id},
$l->{meta}{name},
$uid,
$l->{modelid},
$l->{type},
$l->{meta}{swversion},
$l->{state}{reachable} ? "yes" : "no",
$l->{state}{on} ? "yes" : "no",
$l->{state}{colormode},
$l->{state}{ct},
$l->{state}{x},
$l->{state}{y},
$l->{state}{hue},
$l->{state}{sat},
$l->{state}{bri},
$l->{state}{effect},
$l->{state}{alert}
);
}
}
sub command_lookup
{
check_key();
my ($code, $json) = get(sprintf("%s/api/%s/lights", BRIDGE, $KEY));
if (ref($json) eq 'ARRAY' and defined $json->[0]{error})
{
print Dumper($json) if $DEBUG;
printf("Fetching light info from bridge %s failed: %s", BRIDGE, $json->[0]{error}{description});
return;
}
my $lights = parse_lights($json);
print "id,name\n";
foreach my $uid (sort { $lights->{$a} <=> $lights->{$b} } keys %{$lights})
{
my $l = $lights->{$uid};
print $l->{id} . "," . $l->{name} . "\n";
}
}
sub print_light
{
printf(q{
-[%2d]----------------------------------------
Name: %s
Unique Id: %s
Model Id: %s
Type: %s
SW Version: %s
Reachable: %s
On: %s
Colormode: %s
Colortemp: %s
X, Y: %s, %s
Hue: %s
Saturation: %s
Brightness: %s
Effect: %s
Alert: %s
}, @_);
}
sub command_version
{
print "Version: " . VERSION . "\n";
}
sub restore_lights
{
check_key();
my $curr = shift;
my $prev = shift;
foreach my $uid (sort keys %{$curr})
{
my $c = $curr->{$uid};
my $p = $prev->{$uid};
my $cs = $c->{state};
my $ps = $p->{state};
my $cmd = {};
# The idea here is to reach the desired state using a minimum amount of state changes.
# Only switch light on or off if needed
if ($cs->{on} and not $ps->{on})
{
$cmd->{on} = JSON::false;
}
elsif (not $cs->{on} and $ps->{on})
{
$cmd->{on} = JSON::true;
}
# Only attempt a color change if the light is supposed to be on
if ($ps->{on})
{
# Is the color mode "XY"?
if ($ps->{colormode} eq 'xy')
{
# Do we need to change the xy?
if ($cs->{xy}[0] ne $ps->{x} or $cs->{xy}[1] ne $ps->{y})
{
$cmd->{xy} = [$ps->{x} * 1, $ps->{y} * 1];
}
}
# Is the color mode "Color Temperature"
elsif ($ps->{colormode} eq 'ct')
{
# Do we need to change the ct?
if ($cs->{ct} ne $ps->{ct})
{
$cmd->{ct} = $ps->{ct} * 1;
}
}
# Is the color mode "Hue/Saturation"
else
{
# Do we need to change the hue?
if ($cs->{hue} ne $ps->{hue})
{
$cmd->{hue} = $ps->{hue} * 1;
}
# Do we need to change the saturation?
if ($cs->{sat} ne $ps->{sat})
{
$cmd->{sat} = $ps->{sat} * 1;
}
}
# Do we need to change the brightness?
if ($cs->{bri} ne $ps->{bri})
{
$cmd->{bri} = $ps->{bri} * 1;
}
# Do we need to change the effect?
if ($cs->{effect} ne $ps->{effect})
{
$cmd->{effect} = $ps->{effect};
}
# Do we need to change the alert?
if ($cs->{alert} ne $ps->{alert})
{
$cmd->{alert} = $ps->{alert};
}
}
# Only make a state change if there's actually anything that needs changing
if (scalar keys %{$cmd})
{
my ($code, $json) = post(sprintf("%s/api/%s/lights/%d/state", BRIDGE, $KEY, $c->{id}), $cmd, "PUT");
if (defined $json->[0]{error})
{
printf("Error: %s\n", $json->[0]{error}{description});
}
else
{
printf("Success!\n") if $DEBUG;
}
logthis(
'Restoring state: uniqueid="%s" id=%d on="%s" colormode="%s" ct="%s" xy=[%.4f,%.4f] hue=%d sat=%d bri=%d effect="%s" alert="%s"',
$c->{uniqueid},
$c->{id},
$ps->{on} ? "true" : "false",
$ps->{colormode},
$ps->{ct},
$ps->{x},
$ps->{y},
$ps->{hue},
$ps->{sat},
$ps->{bri},
$ps->{effect},
$ps->{alert}
);
# The recommended max amount of state changes per second is 10.
usleep(100*1000);
}
}
}
sub new_snapshot
{
my $curr = shift;
my $prev = shift;
foreach my $uid (sort keys %{$curr})
{
my $c = $curr->{$uid};
my $p = $prev->{$uid};
my $cs = $c->{state};
my $ps = $p->{state};
# First, check meta info
if (
$c->{name} ne $p->{meta}{name} or
$c->{swversion} ne $p->{meta}{swversion}
)
{
insert_meta($c, $p->{rowid});
printf("New meta:\n%s\n", Dumper($c)) if $DEBUG;
}
# Second, check light state
if (
$cs->{on} ne $ps->{on} or
$cs->{reachable} ne $ps->{reachable} or
$cs->{colormode} ne $ps->{colormode} or
$cs->{ct} ne $ps->{ct} or
$cs->{xy}[0] ne $ps->{x} or
$cs->{xy}[1] ne $ps->{y} or
$cs->{hue} ne $ps->{hue} or
$cs->{sat} ne $ps->{sat} or
$cs->{bri} ne $ps->{bri} or
$cs->{effect} ne $ps->{effect} or
$cs->{alert} ne $ps->{alert}
)
{
insert_state($c, $p->{rowid});
printf("Old state:\n%s\n", Dumper($ps)) if $DEBUG;
printf("New state:\n%s\n", Dumper($cs)) if $DEBUG;
}
}
}
sub parse_lights
{
my $json = shift;
my $parsed = {};
while (my ($id, $light) = each %{$json})
{
$light->{state}{on} = $light->{state}{on} ? 1 : 0;
$light->{state}{reachable} = $light->{state}{reachable} ? 1 : 0;
$light->{id} = $id;
$parsed->{$light->{uniqueid}} = $light;
}
$parsed;
}
sub check_lights
{
my $lights = shift;
# How many light are set to default?
my $default_count = 0;
while (my ($uniqueid, $light) = each %{$lights})
{
if (
$light->{type} eq DEF_TYPE and
$light->{state}{colormode} eq DEF_COLORMODE and
$light->{state}{ct} eq DEF_CT and
$light->{state}{bri} eq DEF_BRI and
$light->{state}{on} and # We don't count bulbs that are off.
$light->{state}{reachable} # We don't count unreachable bulbs.
)
{
# This is a newly powered bulb, in it's default setting.
print "Default: " . $light->{name} . "\n" if $DEBUG;
$default_count++;
}
}
print "Defaulting bulbs: $default_count\nMagic number: " . MAGIC_NUMBER . "\n" if $DEBUG;
# Return true if we need to restore state.
$default_count >= MAGIC_NUMBER;
}
# The log writer
sub logthis
{
my $t = strftime "%FT%TZ", gmtime;
my $l = sprintf("[%s] " . shift . "\n", $t, @_);
print LOG $l;
print $l if $VERBOSE;
}
sub get
{
my $url = shift;
my $req = HTTP::Request->new('GET', $url);
$req->content_type('application/json');
my $res = $ua->request($req);
die $res->status_line unless $res->is_success;
($res->code, decode_json($res->content));
}
sub post
{
my $url = shift;
my $content = shift;
my $method = shift;
$method = "POST" unless $method;
my $req = HTTP::Request->new($method, $url);
$req->content_type('application/json');
$req->content(encode_json($content));
my $res = $ua->request($req);
die $res->status_line unless $res->is_success;
($res->code, decode_json($res->content));
}
sub check_database
{
my $sth = $dbh->table_info(undef, 'main', undef, 'TABLE');
my $info = $sth->fetchall_arrayref();
unless (scalar @{$info})
{
create_tables($dbh);
}
}
sub create_tables
{
$dbh->begin_work;
$dbh->do(q{
create table
light
(
light_id integer primary key,
uniqueid text not null unique,
modelid text not null,
type text not null,
time integer not null
)
}) or die $dbh->errstr;
$dbh->do(q{
create table
meta
(
meta_id integer primary key,
light_id integer not null,
id integer not null,
name text not null,
swversion integer not null,
time integer not null,
foreign key (light_id) references light(light_id)
)
}) or die $dbh->errstr;
$dbh->do(q{
create table
state
(
state_id integer primary key,
light_id integer not null,
reachable integer not null,
"on" integer not null,
colormode text,
ct text,
x real,
y real,
hue integer,
sat integer,
bri integer,
effect text,
alert text,
time integer not null,
foreign key (light_id) references light(light_id)
)
}) or die $dbh->errstr;
$dbh->do(q{
create view
latest_state as
select
light.uniqueid,
state.*
from
light,
state
where
light.light_id = state.light_id
group by
state.light_id
having
max(state.time)
}) or die $dbh->errstr;
$dbh->do(q{
create view
latest_meta as
select
light.uniqueid,
meta.*
from
light,
meta
where
light.light_id = meta.light_id
group by
meta.light_id
having
max(meta.time)
}) or die $dbh->errstr;
$dbh->commit or die $dbh->errstr;
}
sub prepare_statements
{
my %sth = ();
$sth{insert_light} = $dbh->prepare(q{
insert into
light
(
uniqueid,
modelid,
type,
time
)
values
(
?,
?,
?,
?
)
}) or die $dbh->errstr;
$sth{insert_meta} = $dbh->prepare(q{
insert into
meta
(
light_id,
id,
name,
swversion,
time
)
values
(
?,
?,
?,
?,
?
)
}) or die $dbh->errstr;
$sth{insert_state} = $dbh->prepare(q{
insert into
state
(
light_id,
reachable,
"on",
colormode,
ct,
x,
y,
hue,
sat,
bri,
effect,
alert,
time
)
values
(
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)
}) or die $dbh->errstr;
$sth{select_lights} = $dbh->prepare(q{
select
light_id,
uniqueid,
modelid,
type
from
light
}) or die $dbh->errstr;
$sth{select_meta} = $dbh->prepare(q{
select
*
from
latest_meta
}) or die $dbh->errstr;
$sth{select_states} = $dbh->prepare(q{
select
*
from
latest_state
}) or die $dbh->errstr;
\%sth;
}
sub insert_light
{
my $light = shift;
$sth->{insert_light}->execute(
$light->{uniqueid},
$light->{modelid},
$light->{type},
TIME
) or die $dbh->errstr;
logthis('New light: uniqueid="%s" modelid="%s" type="%s"', $light->{uniqueid}, $light->{modelid}, $light->{type});
my $id = $dbh->last_insert_id("","","","") or die $dbh->errstr;
$id;
}
sub insert_meta
{
my $light = shift;
my $rowid = shift;
$sth->{insert_meta}->execute(
$rowid,
$light->{id},
$light->{name},
$light->{swversion},
TIME
) or die $dbh->errstr;
logthis('New meta: uniqueid="%s" id=%d name="%s" swversion="%s"', $light->{uniqueid}, $light->{id}, $light->{name}, $light->{swversion});
}
sub insert_state
{
my $light = shift;
my $rowid = shift;
$sth->{insert_state}->execute(
$rowid,
$light->{state}{reachable},
$light->{state}{on},
$light->{state}{colormode},
$light->{state}{ct},
$light->{state}{xy}[0],
$light->{state}{xy}[1],
$light->{state}{hue},
$light->{state}{sat},
$light->{state}{bri},
$light->{state}{effect},
$light->{state}{alert},
TIME
) or die $dbh->errstr;
logthis(
'New state: uniqueid="%s" id=%d on="%s" colormode="%s" ct=%s xy=[%.4f,%.4f] hue=%d sat=%d bri=%d effect="%s" alert="%s"',
$light->{uniqueid},
$light->{id},
$light->{state}{on} ? "true" : "false",
$light->{state}{colormode},
$light->{state}{ct},
$light->{state}{xy}[0],
$light->{state}{xy}[1],
$light->{state}{hue},
$light->{state}{sat},
$light->{state}{bri},
$light->{state}{effect},
$light->{state}{alert}
);
}
sub previous_lights
{
my %l = ();
$sth->{select_lights}->execute or die $sth->errstr;
while (my @row = $sth->{select_lights}->fetchrow_array)
{
$l{$row[1]} = {
rowid => $row[0],
modelid => $row[2],
type => $row[3]
};
}
$sth->{select_meta}->execute or die $sth->errstr;
while (my $row = $sth->{select_meta}->fetchrow_hashref)
{
$l{$row->{uniqueid}}{meta} = $row;
}
$sth->{select_states}->execute or die $sth->errstr;
while (my $row = $sth->{select_states}->fetchrow_hashref)
{
$l{$row->{uniqueid}}{state} = $row;
}
print Dumper(\%l) if $DEBUG;
\%l;
}
| kluzzebass/huebro | huebro.pl | Perl | apache-2.0 | 19,747 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::azure::storage::storageaccount::mode::accountusedcapacity;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
sub prefix_metric_output {
my ($self, %options) = @_;
return "Resource '" . $options{instance_value}->{display} . "' " . $options{instance_value}->{stat} . " ";
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'metric', type => 1, cb_prefix_output => 'prefix_metric_output', message_multiple => "All capacity metrics are ok", skipped_code => { -10 => 1 } },
];
foreach my $aggregation ('total') {
foreach my $metric ('UsedCapacity') {
my $metric_label = lc($metric);
my $entry = { label => $metric_label . '-' . $aggregation, set => {
key_values => [ { name => $metric_label . '_' . $aggregation }, { name => 'display' }, { name => 'stat' } ],
output_template => $metric . ': %s %s',
output_change_bytes => 1,
perfdatas => [
{ label => $metric_label . '_' . $aggregation, value => $metric_label . '_' . $aggregation ,
template => '%s', unit => 'B', label_extra_instance => 1, instance_use => 'display',
min => 0 },
],
}
};
push @{$self->{maps_counters}->{metric}}, $entry;
}
}
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"resource:s@" => { name => 'resource' },
"resource-group:s" => { name => 'resource_group' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (!defined($self->{option_results}->{resource})) {
$self->{output}->add_option_msg(short_msg => "Need to specify either --resource <name> with --resource-group option or --resource <id>.");
$self->{output}->option_exit();
}
$self->{az_resource} = $self->{option_results}->{resource};
$self->{az_resource_group} = $self->{option_results}->{resource_group} if (defined($self->{option_results}->{resource_group}));
$self->{az_resource_type} = 'storageAccounts';
$self->{az_resource_namespace} = 'Microsoft.Storage';
$self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 3600;
$self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : "PT1H";
$self->{az_aggregations} = ['Total'];
if (defined($self->{option_results}->{aggregation})) {
$self->{az_aggregations} = [];
foreach my $stat (@{$self->{option_results}->{aggregation}}) {
if ($stat ne '') {
push @{$self->{az_aggregations}}, ucfirst(lc($stat));
}
}
}
foreach my $metric ('UsedCapacity') {
push @{$self->{az_metrics}}, $metric;
}
}
sub manage_selection {
my ($self, %options) = @_;
my %metric_results;
foreach my $resource (@{$self->{az_resource}}) {
my $resource_group = $self->{az_resource_group};
my $resource_name = $resource;
if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.Storage\/storageAccounts\/(.*)$/) {
$resource_group = $1;
$resource_name = $2;
}
($metric_results{$resource_name}, undef, undef) = $options{custom}->azure_get_metrics(
resource => $resource_name,
resource_group => $resource_group,
resource_type => $self->{az_resource_type},
resource_namespace => $self->{az_resource_namespace},
metrics => $self->{az_metrics},
aggregations => $self->{az_aggregations},
timeframe => $self->{az_timeframe},
interval => $self->{az_interval},
);
foreach my $metric (@{$self->{az_metrics}}) {
my $metric_name = lc($metric);
$metric_name =~ s/ /_/g;
foreach my $aggregation (@{$self->{az_aggregations}}) {
next if (!defined($metric_results{$resource_name}->{$metric_name}->{lc($aggregation)}) && !defined($self->{option_results}->{zeroed}));
$self->{metric}->{$resource_name . "_" . lc($aggregation)}->{display} = $resource_name;
$self->{metric}->{$resource_name . "_" . lc($aggregation)}->{stat} = lc($aggregation);
$self->{metric}->{$resource_name . "_" . lc($aggregation)}->{$metric_name . "_" . lc($aggregation)} = defined($metric_results{$resource_name}->{$metric_name}->{lc($aggregation)}) ? $metric_results{$resource_name}->{$metric_name}->{lc($aggregation)} : 0;
}
}
}
if (scalar(keys %{$self->{metric}}) <= 0) {
$self->{output}->add_option_msg(short_msg => 'No metrics. Check your options or use --zeroed option to set 0 on undefined values');
$self->{output}->option_exit();
}
}
1;
__END__
=head1 MODE
Check storage account resources used capacity metric.
Example:
Using resource name :
perl centreon_plugins.pl --plugin=cloud::azure::storage::storageaccount::plugin --custommode=azcli --mode=account-used-capacity
--resource=MYFILER --resource-group=MYHOSTGROUP --aggregation='total' --critical-usedcapacity-total='10' --verbose
Using resource id :
perl centreon_plugins.pl --plugin=cloud::azure::storage::storageaccount::plugin --custommode=azcli --mode=account-used-capacity
--resource='/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Storage/storageAccounts/xxx'
--aggregation='total' --critical-usedcapacity-total='10' --verbose
Default aggregation: 'total' / Only total is valid.
=over 8
=item B<--resource>
Set resource name or id (Required).
=item B<--resource-group>
Set resource group (Required if resource's name is used).
=item B<--warning-usedcapacity-total>
Thresholds warning
=item B<--critical-usedcapacity-total>
Thresholds critical
=back
=cut
| Tpo76/centreon-plugins | cloud/azure/storage/storageaccount/mode/accountusedcapacity.pm | Perl | apache-2.0 | 7,212 |
package OpenXPKI::Server::Workflow::Activity::Tools::AppendCertificateMetadata;
use strict;
use base qw( OpenXPKI::Server::Workflow::Activity );
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Exception;
use OpenXPKI::Debug;
use OpenXPKI::Serialization::Simple;
use OpenXPKI::Server::Database; # to get AUTO_ID
use Data::Dumper;
use Workflow::Exception qw(configuration_error workflow_error);
sub execute {
##! 1: 'start'
my ($self, $workflow) = @_;
my $context = $workflow->context();
my $params = $self->param();
my $ser = OpenXPKI::Serialization::Simple->new();
my $cert_identifier = $self->param('cert_identifier');
##! 16: ' cert_identifier' . $cert_identifier
# one of error, overwrite, merge, skip
my $mode = $self->param('mode') || 'error';
if ($mode !~ /(error|overwrite|skip|merge)/) {
configuration_error('Invalid mode ' . $mode);
}
##! 16: ' parameters: ' . Dumper $params
my $dbi = CTX('dbi');
KEY:
foreach my $key (keys %{$params}) {
if ($key !~ /^meta_/) {
next KEY;
}
##! 16: 'Key ' . $key
my $value = $self->param($key);
if (! defined $value || $value eq '') {
$self->log->debug('Skipping $key as value is empty');
next KEY;
}
my $attr = CTX('api2')->get_cert_attributes(
identifier => $cert_identifier,
attribute => $key
);
my $item = $attr->{$key};
if (!$item) {
$dbi->insert(
into => 'certificate_attributes',
values => {
attribute_key => AUTO_ID,
identifier => $cert_identifier,
attribute_contentkey => $key,
attribute_value => $value,
}
);
CTX('log')->application()->info("Append (set) certificate metadata $key with $value");
} elsif ($mode eq 'skip') {
CTX('log')->application()->info("Key already exists, skip certificate metadata with $key with $value");
} elsif ($mode eq 'overwrite') {
if (scalar @{$item} > 1) {
OpenXPKI::Exception->throw (
message => "Append Certificate Metadata item is not scalar but overwrite expected",
params => { KEY => $key }
);
}
$dbi->update(
table => 'certificate_attributes',
set => {
attribute_value => $value,
},
where => {
attribute_contentkey => $key,
}
);
CTX('log')->application()->info("Overwrite certificate metadata $key with $value");
} elsif ($mode eq 'merge') {
if ((grep { $_ eq $value } @{$item}) == 0) {
$dbi->insert(
into => 'certificate_attributes',
values => {
attribute_key => AUTO_ID,
identifier => $cert_identifier,
attribute_contentkey => $key,
attribute_value => $value,
}
);
CTX('log')->application()->info("Append (merge) certificate metadata $key with $value");
} else {
CTX('log')->application()->info("Value already exists, skip certificate metadata with $key with $value");
}
} else {
OpenXPKI::Exception->throw (
message => "Append Certificate Metadata item exists",
params => { KEY => $key }
);
}
}
return 1;
}
1;
__END__
=head1 Name
OpenXPKI::Server::Workflow::Activity::Tools::AppendCertificateMetadata
=head1 Description
Add arbitrary key/value items as certificate metadata
=head2 Configuration
class: OpenXPKI::Server::Workflow::Activity::Tools::AppendCertificateMetadata
param:
cert_identifier: 0utS7yqMTAy2DLIufyJvoc2GSCs
mode: overwrite
meta_new_attribute: my_value
This will attach a new metadata item with the key meta_new_attribute and
value my_value for the given identifier. This information does not depend
on any metadata settings in the certificates profile!
=head2 Mode
=over
=item error
If the used key is already present, an exception is thrown. This is the default.
=item skip
The new value is discarded, the old one will remain in the table.
=item overwrite
The old value is replaced by the new one, expects that only one value exists.
If multiple values have been found, an exception is thrown.
=item merge
Add the new value if it does not already exists, will also work if the key
is defined more than once.
=back
| oliwel/openxpki | core/server/OpenXPKI/Server/Workflow/Activity/Tools/AppendCertificateMetadata.pm | Perl | apache-2.0 | 4,851 |
#!/usr/local/ActivePerl-5.8/bin/perl
require "../ServiceConfig.pl";
#add create new service
$service = Service->new( RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288",
rrdStep => "300",
serviceName => "tcp");
#add metric 0
$obj = Metric->new( rrdIndex => 0,
metricName => "bytesIn",
friendlyName => "Recieved Bytes",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
metricValue => "null",
warnThreshold => 10000000,
critThreshold => 25000000,
thresholdUnit => "Bytes/Sec",
lowThreshold => "0",
highThreshold => "100000000");
$service->addMetric($obj);
#add metric 1
$obj = Metric->new( rrdIndex => 1,
metricName => "bytesOut",
friendlyName => "Transmitted Bytes",
status => "nostatus",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
metricValue => "null",
warnThreshold => 10000000,
critThreshold => 25000000,
thresholdUnit => "Bytes/Sec",
lowThreshold => "0",
highThreshold => "100000000");
$service->addMetric($obj);
#print out this service
print ("Ref: ref($service)\n");
$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
$rrdStep = $service->getRRDStep();
$lastUpdate = $service->getLastUpdate();
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
print ("rrdStep: $rrdStep\n");
print ("Last Update: $lastUpdate\n");
#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$metricObject = $service->{metricArray}->[$counter];
$rrdIndex = $metricObject->getRRDIndex();
$rrdDST = $metricObject->getRRDDST();
$rrdHeartbeat = $metricObject->getRRDHeartbeat();
$rrdMin = $metricObject->getRRDMin();
$rrdMax = $metricObject->getRRDMax();
$metricName = $metricObject->getMetricName();
$friendlyName = $metricObject->getFriendlyName();
$status = $metricObject->getStatus();
$hasEvents = $metricObject->getHasEvents();
$metricValue = $metricObject->getMetricValue();
$warnThreshold = $metricObject->getWarnThreshold();
$critThreshold = $metricObject->getCritThreshold();
$thresholdUnit = $metricObject->getThresholdUnit();
$lowThreshold = $metricObject->getLowThreshold();
$highThreshold = $metricObject->getHighThreshold();
print ("rrdIndex: $rrdIndex\n");
print ("rrdDST: $rrdDST\n");
print ("rrdHeartbeat: $rrdHeartbeat\n");
print ("rrdMin: $rrdMin\n");
print ("rrdMax: $rrdMax\n");
print ("metricName: $metricName\n");
print ("friendlyName: $friendlyName\n");
print ("status: $status\n");
print ("hasEvents: $hasEvents\n");
print ("metricValue: $metricValue\n");
print ("warnThreshold: $warnThreshold\n");
print ("critThreshold: $critThreshold\n");
print ("threshUnit: $thresholdUnit\n");
print ("lowThreshold: $lowThreshold\n");
print ("highThreshold: $highThreshold\n\n");
}
#Store the service
$service->store("$perfhome/etc/configs/WindowsNT/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
| ktenzer/perfstat | misc/serialize/create/WindowsNT/tcp.pl | Perl | apache-2.0 | 3,222 |
#!/usr/bin/perl
#
# install.pl - Compile and install dotfiles
#
# Copyright (c) 2013 nandhp <nandhp@gmail.com>
# License: Simplified (2-clause) BSD, see COPYING.BSD
use File::Find;
use File::Spec;
use File::Basename;
use Text::ParseWords;
use Data::Dumper;
use warnings;
use strict;
my $COMMENTS = "#;!%'";
my $BASE = File::Spec->rel2abs(File::Spec->curdir());
my $LIBDIR = File::Spec->rel2abs('lib');
my $QUPP = File::Spec->rel2abs('qupp.pl', $LIBDIR);
my $BUILD = File::Spec->rel2abs('.build', $BASE);
my $INSTALLFILE = File::Spec->rel2abs('.install', $BUILD);
my $HOME = $ENV{HOME};
die "$HOME does not exist" unless -d $HOME;
mkdir($BUILD, 0700) or die "mkdir $BUILD: $!" unless -d $BUILD;
chmod(0700, $BUILD) or die "chmod $BUILD: $!";
my $APP = $0;
foreach ( @ARGV ? @ARGV : qw(help) ) {
if ( $_ eq '--as-make' ) {
$APP = 'make';
}
elsif ( $_ eq 'build' ) {
build();
print STDERR "OK, now try $APP diff or $APP install\n";
}
elsif ( $_ eq 'diff' ) {
diff();
print STDERR "OK, now try $APP noact or $APP install\n";
}
elsif ( $_ eq 'noact' ) {
install(0);
print STDERR "OK, now try $APP install\n";
}
elsif ( $_ eq 'install' ) {
install(1);
print STDERR "OK, installation complete\n";
}
else {
die "Usage: $APP <build|diff|noact|install>\n";
}
}
sub build {
my @diffs = ();
my @dirs = ();
my @files = ();
my $process_file = sub {
my $path = $File::Find::name;
my $origfile = File::Spec->abs2rel($path, $BASE);
# Determine if we should process the file
return unless -f $path;
if ( $origfile =~ /(.*)(^|\/)\.install$/ and $1 !~ m/(^|\/)\./ ) {
# FIXME: Replace with ?run, implemented below
push @dirs, ['sh', '-e', '-c',
'cd "$(dirname "$1")"; ./"$(basename "$1")"', '-',
$origfile];
push @diffs, ['i', $origfile];
return;
}
return if $origfile =~ /(^|\/)[#.]|(\.pm|~)$/;
open F, '<', $path or die "open $path: $!";
my $line = <F>;
$line = <F> while $line and $line =~ m/^#!|^<(\?xml|!DOCTYPE|!--)/i;
close F;
return if !$line or $line !~ m/^[$COMMENTS]+\?/;
(my $file = $origfile) =~ s/[^-+_a-zA-Z0-9.,]/_/g;
# Process the file
my $outfile = "$BUILD/$file";
open F, '-|', $QUPP, '-I', $LIBDIR, '-M', 'dotfileutils',
$path or die "qupp $path: $!";
open OUT, '>', $outfile or die "open $outfile: $!";
my $cmdno = 0;
LINE:
while (<F>) {
unless ( m/^([$COMMENTS]{1,2})\?\s*(.*?)\s*$/ ) {
print OUT;
next;
}
my ($commentchar, $commandline) = ($1, $2);
$commandline =~ s/-\*-.*-\*-//; # Emacs mode configuration
if ( $commandline =~ m/^\s*quiet/ ) {
$cmdno++;
next;
}
if ( $cmdno == 0 ) {
my $now = localtime;
print OUT "$commentchar $_\n" foreach
('DO NOT EDIT THIS FILE',
"Autogenerated from .../$origfile at $now")
}
$cmdno++;
my @command = shellwords($commandline);
next unless @command;
my $cmd = $command[0];
if ( $cmd eq 'install' ) {
# Handle an install command; is it for a directory or
# do we need to insert the source filename?
# Tilde (and wildcard) expansion on destination
push @command, do_glob(pop @command);
# FIXME: Requires no space between option and argument (-m0700)
# FIXME: Requires all options before nonoptions
for ( my $i = 1; $i < @command; $i++ ) {
if ( $command[$i] =~ /^-[a-z]*d|^--directory$/ ) {
push @dirs, \@command;
push @diffs, ['d', $command[-1]];
next LINE;
}
elsif ( $command[$i] eq '--' ) {
splice(@command, $i, 1);
redo;
}
}
splice(@command, 1, 0, '-m0644', '-b');
splice(@command, @command-1, 0, '--', $outfile);
push @diffs, ['f', $command[-1], $outfile];
push @files, \@command;
next LINE;
}
elsif ( $cmd eq 'ln' ) {
# Sometimes we need symlinks, too
my @newcmd = ('ln', '-f', '--');
my $ok = 0;
my $last = undef;
foreach ( @command[1..$#command] ) {
if ( m/^-s/ ) { $newcmd[1] .= 's'; next }
$ok=99 if m/^-/;
push @newcmd, do_glob($_, undef);
$last = do_glob($_);
$ok++;
}
defined($last) or $ok = 99;
$newcmd[-1] = $last;
$ok = 99 if $newcmd[1] ne '-fs';
die "$path: ln: Usage: ln -s <target> <linkname>; " .
"got @newcmd" unless $ok == 2;
die "$path: ln: Won't overwrite non-symlink $newcmd[-1]"
if -e $newcmd[-1] and !-l $newcmd[-1];
push @files, \@newcmd;
push @diffs, ['l', $newcmd[-1], $newcmd[-2]];
}
# FIXME: better way to run one-off commands
elsif ( $cmd eq 'shell' ) {
(my $shellcmd = $commandline) =~ s/^\s*shell\s+//i;
push @files, ['sh', '-c', $shellcmd, '', $origfile, $outfile];
push @diffs, ['i', $origfile, "Run $shellcmd"];
}
elsif ( $cmd eq 'run' ) {
chmod 0700, $outfile or die "chmod $outfile: $!";
push @dirs, ['sh', '-e', '-c',
'cd "$(dirname "$1")"; "$2"', '-',
$origfile, $outfile];
push @diffs, ['i', $outfile];
}
else {
warn "$path: $cmd not recognized.\n";
}
}
close OUT or die "close $outfile: $!";
close F or die "qupp $path failed: " . ($!||"Unreported error");
};
find({wanted => $process_file, no_chdir => 1}, $BASE);
open F, '>', $INSTALLFILE or die "Can't write installfile: $!";
print F Data::Dumper->Dump([\@dirs,\@files,\@diffs],
[qw(*dirs *files *diffs)]);
close F;
}
sub read_installfile {
open F, '<', $INSTALLFILE or die "Can't read installfile: $!";
my $buf = join('', <F>);
close F;
return $buf;
}
sub diff {
my (@dirs, @files, @diffs); eval read_installfile();
for my $info ( @diffs ) {
my ($type, @data) = @$info;
my $rc = 0;
print "=== $data[0]\n";
if ( $type eq 'f' ) {
if ( -e $data[0] ) {
system('diff', "-I^[$COMMENTS]* Autogenerated from ",
'-u', '--', @data);
}
else {
print "Create file $data[0]\n";
}
}
elsif ( $type eq 'l' ) {
if ( -l $data[0] ) {
my $old = readlink $data[0];
if ( $old ne $data[1] ) {
print "Change symlink from $old to $data[1]\n";
}
}
elsif ( !-e $data[0] ) {
print "Create symlink to $data[1]\n";
}
else {
die "$data[1]: ln: Won't overwrite non-symlink $data[0]";
}
}
elsif ( $type eq 'd' ) {
if ( -d $data[0] ) { }
elsif ( -e $data[0] ) {
print "Replace existing file with a directory\n";
}
else {
print "Create directory\n";
}
}
elsif ( $type eq 'i' ) {
print $data[1] ? "$data[1]\n" : "Run script $data[0]\n";
}
else {
die "Unknown diff type $type";
}
}
}
sub install {
my ($doit) = @_;
my (@dirs, @files, @diffs); eval read_installfile();
for my $cmd ( @dirs, @files ) {
print join(' ', @$cmd), "\n";
next unless $doit;
my $rc = system(@$cmd);
$rc == 0 or die "@$cmd: exit status $rc (-1=>$!)";
}
}
sub do_glob {
my ($file, $base) = @_;
$base = $HOME if @_ < 2;
$file =~ s/^~/$HOME/;
return defined($base) ? File::Spec->rel2abs($file, $base) : $file;
}
| nandhp/dotfiles | lib/install.pl | Perl | bsd-2-clause | 8,707 |
package Yahoo::SysBuilder::Modules;
use strict;
use warnings 'all';
use YAML qw();
use POSIX qw();
use Yahoo::SysBuilder::Utils qw(read_file is_xen_paravirt);
sub new {
my $class = shift;
my $version = ( POSIX::uname() )[2]; # release
my %config = (
'pcimap' => "/lib/modules/$version/modules.pcimap",
'pcitable' => '/usr/share/hwdata/pcitable',
'devices' => undef,
'modprobe' => \&_modprobe,
@_
);
unless ( defined $config{devices} ) {
my @devices = `/sbin/lspci -n`;
$config{devices} = \@devices;
}
return bless \%config, $class;
}
sub detect_modules {
my $self = shift;
if ( is_xen_paravirt() ) {
return ( ['xenblk'], ['xennet'] );
}
my $pci_ids = $self->_pci_mappings;
my $devices = $self->{devices};
my ( @scsi_modules, @net_modules );
for (@$devices) {
s/Class //;
my ( $class, $id ) = (split)[ 1, 2 ];
$class =~ s/:$//;
my $num_class = hex($class);
if ( $num_class >= 0x100 and $num_class < 0x200 ) {
if ($id =~ m/1af4:100/) {
return(['virtio_pci','virtio_blk'],['virtio_net']);
}
push @scsi_modules, _module_for( $pci_ids, $id, "Storage" );
}
elsif ( $num_class == 0x200 ) {
push @net_modules, _module_for( $pci_ids, $id, "Network" );
}
}
return ( \@scsi_modules, \@net_modules );
}
# loading the right modules
sub load {
my $self = shift;
my $modules_file = shift;
my ( $scsi_modules, $net_modules ) = $self->detect_modules;
my %modules = (
'scsi' => $scsi_modules,
'net' => $net_modules,
);
if ($modules_file) {
YAML::DumpFile( $modules_file, \%modules );
}
# load the modules
my %seen;
my $modprobe = $self->{modprobe};
for (@$scsi_modules) {
$modprobe->( "storage", $_ ) unless $seen{$_}++;
}
if (@$scsi_modules) {
$modprobe->( "scsi disks", "sd_mod" );
}
for (@$net_modules) {
$modprobe->( "network", $_ ) unless $seen{$_}++;
}
}
sub _pci_mappings {
my $self = shift;
my $pcimap = $self->{pcimap};
my $pcitable = $self->{pcitable};
my %pciid_module;
if ( open my $fh, "<", $pcitable ) {
while (<$fh>) {
next if /^#/;
my ( $vendor, $device, $module ) = split;
for ( $vendor, $device ) {
s/0x//;
}
$module =~ s/"//g;
my $id = "$vendor:$device";
$pciid_module{$id} = $module;
}
close $fh;
}
open my $fh, "<", $pcimap
or die "Can't load $pcimap: $!";
while (<$fh>) {
next if /^#/;
my ( $mod, $vendor, $device ) = split;
for ( $vendor, $device ) {
s/0x0000//;
}
my $id = "$vendor:$device";
$pciid_module{$id} = $mod;
}
close $fh;
# see bz3056559, bz3237176, and bz4584812 -- unknown scsi hardware on DL160G6-sata in AHCI mode
# hack to get around missing line in modules.pcimap on rhel4
$pciid_module{'8086:3a22'} ||= 'ahci';
$pciid_module{'8086:3b22'} ||= 'ahci';
return \%pciid_module;
}
sub _module_for {
my ( $pci_ids, $id, $type ) = @_;
my $module = $pci_ids->{$id};
return $module if defined $module;
# look for class:0xffffffff instead
my $wildcard = join( ':', ( split( ':', $id ) )[0], '0xffffffff' );
$module = $pci_ids->{$wildcard};
return $module if defined $module;
return "Unknown-$id";
}
sub _modprobe {
my ( $type, $module ) = @_;
return if $module =~ /^Unknown/;
print "----> Loading $type module: $module\n";
system("modprobe $module");
}
1;
| eam/ysysbuilder | lib/Yahoo/SysBuilder/Modules.pm | Perl | bsd-3-clause | 3,787 |
#ExStart:1
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;
use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;
use AsposeEmailCloud::EmailApi;
use AsposeEmailCloud::ApiClient;
use AsposeEmailCloud::Configuration;
use AsposeEmailCloud::Object::EmailProperty;
my $configFile = '../Config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);
my $data_path = '../../../Data/';
my $out_path = $configProps->{'out_folder'};
$AsposeEmailCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeEmailCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeEmailCloud::Configuration::debug = 1;
$AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'};
# Instantiate Aspose.Storage and Aspose.Email API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();
my $emailApi = AsposeEmailCloud::EmailApi->new();
# Set input file name
my $name = 'email_test.eml';
my $propertyName = "Subject";
my @emailProperty = AsposeEmailCloud::Object::EmailProperty->new('Name' => 'Subject', 'Value' => 'This is a new subject');
# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);
# Invoke Aspose.Email Cloud SDK API to update an email property by name
$response = $emailApi->PutSetEmailProperty(name=> $name, propertyName=>$propertyName, body=>@emailProperty);
if($response->{'Status'} eq 'OK'){
my $emailProperty = $response->{'EmailProperty'};
print "\nName : " . $emailProperty->{'Name'} . " Value: " . $emailProperty->{'Value'};
}
#ExEnd:1 | aspose-email/Aspose.Email-for-Cloud | Examples/Perl/Email-Properties/SetMessageProperty.pl | Perl | mit | 1,790 |
=head1 NAME
libavdevice - multimedia device handling library
=head1 DESCRIPTION
The libavdevice library provides a generic framework for grabbing from
and rendering to many common multimedia input/output devices, and
supports several input and output devices, including Video4Linux2,
VfW, DShow, and ALSA.
=head1 SEE ALSO
ffmpeg(1), ffplay(1), ffprobe(1), ffserver(1),
ffmpeg-devices(1),
libavutil(3), libavcodec(3), libavformat(3)
=head1 AUTHORS
The FFmpeg developers.
For details about the authorship, see the Git history of the project
(git://source.ffmpeg.org/ffmpeg), e.g. by typing the command
B<git log> in the FFmpeg source directory, or browsing the
online repository at E<lt>B<http://source.ffmpeg.org>E<gt>.
Maintainers for the specific components are listed in the file
F<MAINTAINERS> in the source code tree.
| devlato/kolibrios-llvm | contrib/sdk/sources/ffmpeg/doc/libavdevice.pod | Perl | mit | 841 |
/* Part of INCLP(R)
Author: Leslie De Koninck
E-mail: Leslie.DeKoninck@cs.kuleuven.be
WWW: http://www.swi-prolog.org
Copyright (c) 2006-2011, K.U. Leuven
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(benchmarks,
[
broyden_banded/1,
feigenbaum/1,
moore_jones/1,
more_cosnard/1
]).
:- use_module(library(inclpr),
[
{}/1,
change_incremental/1,
change_standard_domain/1,
get_domain/2,
solve/0
]).
broyden_banded(N) :-
change_standard_domain(i(-1.0e08,1.0e08)),
change_incremental(false),
broyden_banded(N,Call,Names,Vars),
time(Call),
write_domains(Names,Vars).
feigenbaum(N) :-
change_standard_domain(i(0.0,1.0e02)),
change_incremental(false),
feigenbaum(N,Call,Names,Vars),
time((Call,forall(solve,write_domains(Names,Vars)))).
more_cosnard(N) :-
change_standard_domain(i(-1.0,0.0)),
change_incremental(false),
more_cosnard(N,Call,Names,Vars),
time(Call),
write_domains(Names,Vars).
moore_jones(N) :-
change_standard_domain(i(0.0,1.0)),
change_incremental(false),
moore_jones(N,Call,Names,Vars),
time(Call),
write_domains(Names,Vars).
% Broyden-Banded Example Internal Predicates
broyden_banded(N,{Conj},Names,Vars) :-
length(Vars,N),
create_names(N,Names),
numlist(1,N,Nums),
maplist(br(N,Vars),Nums,Constraints),
list_to_conj(Constraints,Conj).
br(N,Vars,I,(Xi*(2+5*Xi**2)+1-Sum)=0) :-
nth1(I,Vars,Xi),
br_indices(I,N,Indices),
maplist(br_summand(Vars),Indices,Summands),
list_to_sum(Summands,Sum).
br_summand(Vars,I,Xj*(1+Xj)) :-
nth1(I,Vars,Xj).
br_indices(I,N,Indices) :-
LL is max(1,I-5),
LU is I-1,
( LL =< LU
-> numlist(LL,LU,L)
; L = []
),
RL is I+1,
RU is min(N,I+1),
( RL =< RU
-> numlist(RL,RU,R)
; R = []
),
append(L,R,Indices).
% Feigenbaum Example Internal Predicates
feigenbaum(N,{Conj},Names,Vars) :-
length(Vars,N),
create_names(N,Names),
Vars = [H|_],
fb(Vars,H,Constraints),
list_to_conj(Constraints,Conj).
fb([X],E,[-3.84*X^2+3.84*X-E=0]).
fb([X,Y|T],E,[-3.84*X^2+3.84*X-Y=0|CT]) :-
fb([Y|T],E,CT).
% More'-Cosnard Internal Predicates
more_cosnard(N,{Conj},Names,Vars) :-
length(Vars,N),
create_names(N,Names),
numlist(1,N,Nums),
maplist(mc(Vars,Nums,N),Vars,Nums,Constraints),
list_to_conj(Constraints,Conj).
mc(Vars,Nums,N,Var,Num,Function = 0) :-
length(LeftVars,Num),
length(LeftNums,Num),
append(LeftVars,RightVars,Vars),
append(LeftNums,RightNums,Nums),
M is N+1,
maplist(mc_left(M),LeftVars,LeftNums,LeftTerms),
maplist(mc_right(M),RightVars,RightNums,RightTerms),
list_to_sum(LeftTerms,LeftSum),
list_to_sum(RightTerms,RightSum),
T is Num/M,
TM is 1-T,
A is 1/(2*M),
Function = Var + A*(TM*LeftSum+T*RightSum).
mc_left(M,Var,Num,Term) :-
T is Num/M,
TP is T+1,
Term = T*(Var+TP)^3.
mc_right(M,Var,Num,Term) :-
T is Num/M,
TM is 1-T,
TP is T+1,
Term = TM*(Var+TP)^2.
% Moore-Jones Internal Predicates
moore_jones(N,{Conj},Names,Vars) :-
length(Vars,N),
create_names(N,Names),
numlist(1,N,Nums),
maplist(mj(Vars,N),Nums,Constraints),
list_to_conj(Constraints,Conj).
mj(Vars,N,Num,Function = 0) :-
repeat,
( C1 is random(N) + 1,
C1 =\= Num,
C2 is random(N) + 1,
C2 =\= Num,
C2 =\= C1,
C3 is random(N) + 1,
C3 =\= Num,
C3 =\= C1,
C3 =\= C2
),
!,
B is 0.25*random(1000000000)/1000000000,
A is (1-B)*random(1000000000)/1000000000,
nth1(Num,Vars,Xi),
nth1(C1,Vars,Xi1),
nth1(C2,Vars,Xi2),
nth1(C3,Vars,Xi3),
Function = Xi - A - B*Xi1*Xi2*Xi3.
% Auxiliary Predicates
create_names(N,Names) :-
length(Names,N),
nb_digits(N,Max),
create_names(Names,1,Max).
create_names([],_,_).
create_names([H|T],N,Max) :-
atom_concat('X',N,Temp),
M is N + 1,
nb_digits(N,Digits),
Diff is Max - Digits,
add_spaces(Diff,Temp,H),
create_names(T,M,Max).
nb_digits(X,N) :- N is floor(log(X)/log(10))+1.
add_spaces(0,Atom,Atom) :- !.
add_spaces(N,Temp,Atom) :-
N > 0,
atom_concat(' ',Temp,New),
M is N - 1,
add_spaces(M,New,Atom).
write_domains(Names,Vars) :-
maplist(write_domain,Names,Vars),
nl.
write_domain(Name,Var) :-
get_domain(Var,i(L,U)),
writef('%12R =< %w =< %12R\n',[L,Name,U]).
list_to_sum([],0).
list_to_sum([H|T],Sum) :-
List = [H|T],
length(List,N),
list_to_sum(N,List,[],Sum).
list_to_sum(1,[H|T],T,H) :- !.
list_to_sum(2,[H1,H2|T],T,H1+H2) :- !.
list_to_sum(N,List,Tail,LeftSum+RightSum) :-
LeftN is N >> 1,
RightN is N - LeftN,
list_to_sum(LeftN,List,Temp,LeftSum),
list_to_sum(RightN,Temp,Tail,RightSum).
list_to_conj([],true).
list_to_conj([H|T],Conj) :- list_to_conj(T,H,Conj).
list_to_conj([],Element,Element).
list_to_conj([H|T],Element,(Element,Conj)) :-
list_to_conj(T,H,Conj). | TeamSPoon/logicmoo_workspace | docker/rootfs/usr/local/share/swipl/doc/packages/examples/inclpr/benchmarks.pl | Perl | mit | 6,017 |
# 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
#
# https://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 Avro::DataFileWriter;
use strict;
use warnings;
use constant DEFAULT_BLOCK_MAX_SIZE => 1024 * 64;
use Object::Tiny qw{
fh
writer_schema
codec
metadata
block_max_size
sync_marker
};
use Avro::BinaryEncoder;
use Avro::BinaryDecoder;
use Avro::DataFile;
use Avro::Schema;
use Carp;
use Compress::Zstd;
use Error::Simple;
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error);
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError);
our $VERSION = '++MODULE_VERSION++';
sub new {
my $class = shift;
my $datafile = $class->SUPER::new(@_);
## default values
$datafile->{block_max_size} ||= DEFAULT_BLOCK_MAX_SIZE;
$datafile->{sync_marker} ||= $class->random_sync_marker;
$datafile->{metadata} ||= {};
$datafile->{codec} ||= 'null';
$datafile->{_current_size} = 0;
$datafile->{_serialized_objects} = [];
$datafile->{_compressed_block} = '';
croak "Please specify a writer schema" unless $datafile->{writer_schema};
croak "writer_schema is invalid"
unless eval { $datafile->{writer_schema}->isa("Avro::Schema") };
throw Avro::DataFile::Error::InvalidCodec($datafile->{codec})
unless Avro::DataFile->is_codec_valid($datafile->{codec});
return $datafile;
}
## it's not really good random, but it should be good enough
sub random_sync_marker {
my $class = shift;
my @r;
for (1..16) {
push @r, int rand(1<<8);
}
my $marker = pack "C16", @r;
return $marker;
}
sub print {
my $datafile = shift;
my $data = shift;
my $writer_schema = $datafile->{writer_schema};
my $enc_ref = '';
Avro::BinaryEncoder->encode(
schema => $writer_schema,
data => $data,
emit_cb => sub {
$enc_ref .= ${ $_[0] };
},
);
$datafile->buffer_or_print(\$enc_ref);
}
sub buffer_or_print {
my $datafile = shift;
my $string_ref = shift;
my $codec = $datafile->codec;
my $ser_objects = $datafile->{_serialized_objects};
push @$ser_objects, $string_ref;
if ($codec eq 'deflate') {
my $uncompressed = join('', map { $$_ } @$ser_objects);
rawdeflate \$uncompressed => \$datafile->{_compressed_block}
or croak "rawdeflate failed: $RawDeflateError";
$datafile->{_current_size} =
bytes::length($datafile->{_compressed_block});
}
elsif ($codec eq 'bzip2') {
my $uncompressed = join('', map { $$_ } @$ser_objects);
my $compressed;
bzip2 \$uncompressed => \$compressed
or croak "bzip2 failed: $Bzip2Error";
$datafile->{_compressed_block} = $compressed;
$datafile->{_current_size} = bytes::length($datafile->{_compressed_block});
}
elsif ($codec eq 'zstandard') {
my $uncompressed = join('', map { $$_ } @$ser_objects);
$datafile->{_compressed_block} = compress(\$uncompressed);
$datafile->{_current_size} = bytes::length($datafile->{_compressed_block});
}
else {
$datafile->{_current_size} += bytes::length($$string_ref);
}
if ($datafile->{_current_size} > $datafile->{block_max_size}) {
## ok, time to flush!
$datafile->_print_block;
}
return;
}
sub header {
my $datafile = shift;
my $metadata = $datafile->metadata;
my $schema = $datafile->writer_schema;
my $codec = $datafile->codec;
for (keys %$metadata) {
warn "metadata '$_' is reserved" if /^avro\./;
}
my $encoded_header = '';
Avro::BinaryEncoder->encode(
schema => $Avro::DataFile::HEADER_SCHEMA,
data => {
magic => Avro::DataFile->AVRO_MAGIC,
meta => {
%$metadata,
'avro.schema' => $schema->to_string,
'avro.codec' => $codec,
},
sync => $datafile->{sync_marker},
},
emit_cb => sub { $encoded_header .= ${ $_[0] } },
);
return $encoded_header;
}
sub _print_header {
my $datafile = shift;
$datafile->{_header_printed} = 1;
my $fh = $datafile->{fh};
print $fh $datafile->header;
return 1;
}
sub _print_block {
my $datafile = shift;
unless ($datafile->{_header_printed}) {
$datafile->_print_header;
}
my $ser_objects = $datafile->{_serialized_objects};
my $object_count = scalar @$ser_objects;
my $length = $datafile->{_current_size};
my $prefix = '';
for ($object_count, $length) {
Avro::BinaryEncoder->encode_long(
undef, $_, sub { $prefix .= ${ $_[0] } },
);
}
my $sync_marker = $datafile->{sync_marker};
my $fh = $datafile->{fh};
## alternatively here, we could do n calls to print
## but we'll say that this all write block thing is here to overcome
## any memory issues we could have with deferencing the ser_objects
if ($datafile->codec ne 'null') {
print $fh $prefix, $datafile->{_compressed_block}, $sync_marker;
}
else {
print $fh $prefix, (map { $$_ } @$ser_objects), $sync_marker;
}
## now reset our internal buffer
$datafile->{_serialized_objects} = [];
$datafile->{_current_size} = 0;
$datafile->{_compressed_block} = '';
return 1;
}
sub flush {
my $datafile = shift;
$datafile->_print_block if $datafile->{_current_size};
}
sub close {
my $datafile = shift;
$datafile->flush;
my $fh = $datafile->{fh} or return;
close $fh;
}
sub DESTROY {
my $datafile = shift;
$datafile->flush;
return 1;
}
package Avro::DataFile::Error::InvalidCodec;
use parent 'Error::Simple';
1;
| apache/avro | lang/perl/lib/Avro/DataFileWriter.pm | Perl | apache-2.0 | 6,424 |
package OpenXPKI::Server::Workflow::Activity::Tools::Approve;
use strict;
use base qw( OpenXPKI::Server::Workflow::Activity );
use OpenXPKI::Server::Context qw( CTX );
use OpenXPKI::Exception;
use OpenXPKI::Serialization::Simple;
use OpenXPKI::Debug;
use Workflow::Exception qw(configuration_error);
use English;
use Data::Dumper;
use Digest::SHA qw( sha1_hex );
use Encode qw(encode decode);
sub execute
{
my $self = shift;
my $workflow = shift;
my $serializer = OpenXPKI::Serialization::Simple->new();
## get needed information
my $context = $workflow->context();
my $user = CTX('session')->data->user;
my $role = CTX('session')->data->role;
my $pki_realm = CTX('session')->data->pki_realm;
# not supported / used at the moment
if (defined $context->param('_check_hash')) {
# compute SHA1 hash over the serialization of the context,
# skipping volatile entries
my $current_context;
CONTEXT:
foreach my $key (sort keys %{ $context->param() }) {
next CONTEXT if ($key =~ m{ \A _ }xms);
next CONTEXT if ($key =~ m{ \A wf_ }xms);
$current_context->{$key} = $context->param($key);
}
##! 16: 'current_context: ' . Dumper $current_context;
my $serialized_context = OpenXPKI::Serialization::Simple->new()->serialize($current_context);
##! 16: 'serialized current context: ' . Dumper $serialized_context
my $context_hash = sha1_hex($serialized_context);
##! 16: 'context_hash: ' . $context_hash
if ($context_hash ne $context->param('_check_hash')) {
# this means that the context changed, do not approve
# and throw an exception
OpenXPKI::Exception->throw(
message => 'I18N_OPENXPKI_SERVER_WORKFLOW_ACTIVITY_TOOLS_APPROVE_CONTEXT_HASH_CHECK_FAILED',
params => {
REQUESTED_HASH => $context->param('_check_hash'),
CURRENT_HASH => $context_hash,
},
);
}
}
## get already present approvals
my @approvals = ();
my $approvals = $context->param ('approvals');
if (defined $approvals) {
##! 16: 'approvals defined, deserialize them'
@approvals = @{ $serializer->deserialize($approvals) };
##! 16: 'approvals: ' . Dumper \@approvals
}
# moved to condition, does no longer work this way as creator is not necessariyl in context
if ($self->param('check_creator')) {
configuration_error('The check_creator option is no longer supported - use conditions instead');
}
# not used and needs rework
=pod
if (defined $context->param('_signature')) {
# we have a signature
##! 16: 'signature present'
my $sig = $context->param('_signature');
if ($sig !~ m{\A .* \n\z}xms) {
##! 64: 'sig does not end with \n, add it'
$sig .= "\n";
}
my $sig_text = $context->param('_signature_text');
##! 64: 'sig: ' . $sig
##! 64: 'sig_text: ' . $sig_text
my $pkcs7 = "-----BEGIN PKCS7-----\n"
. $sig
. "-----END PKCS7-----\n";
##! 32: 'pkcs7: ' . $pkcs7
my $default_token = CTX('api')->get_default_token();
my @signer_chain = @{ $default_token->command({
COMMAND => 'pkcs7_get_chain',
PKCS7 => $pkcs7,
}) };
##! 64: 'signer_chain: ' . Dumper \@signer_chain
my $x509_signer = OpenXPKI::Crypto::X509->new(
TOKEN => $default_token,
DATA => $signer_chain[0]
);
my $sig_identifier = $x509_signer->get_identifier();
my $signer_subject = $x509_signer->get_subject();
if (! defined $sig_identifier || $sig_identifier eq '') {
OpenXPKI::Exception->throw(
message => 'I18N_OPENXPKI_SERVER_WORKFLOW_ACTIVITY_TOOLS_APPROVE_COULD_NOT_DETERMINE_SIGNER_CERTIFICATE_IDENTIFIER',
log => {
priority => 'info',
facility => 'system',
},
);
}
CTX('log')->application()->info('Signed approval for workflow ' . $workflow->id() . " by user $user, role $role");
CTX('log')->audit('approval')->info('Signed approval for workflow ' . $workflow->id() . " by user $user, role $role");
# look for already present approvals by someone with the same
# certificate and role
if ($self->param('multi_role_approval') &&
(! grep {$_->{session_user} eq $user &&
$_->{session_role} eq $role} @approvals)) {
##! 64: 'multi role approval enabled and (user, role) pair not found in present approvals'
push @approvals, {
'session_user' => $user,
'session_role' => $role,
'signature' => $sig,
'plaintext' => $sig_text,
'signer_identifier' => $sig_identifier,
'signer_subject' => $signer_subject,
},
}
elsif (! $self->param('multi_role_approval') &&
! grep {$_->{session_user} eq $user} @approvals) {
##! 64: 'multi role approval disabled and user not found in present approvals'
push @approvals, {
'session_user' => $user,
'session_role' => $role,
'signature' => $sig,
'plaintext' => $sig_text,
'signer_identifier' => $sig_identifier,
'signer_subject' => $signer_subject,
},
}
}
# Unsigned Approvals
else {
=cut
my $mode = $self->param('mode') || 'session';
# read the approval info from the activity parameter
if ($mode eq 'generated') {
my $comment = $self->param('comment');
configuration_error('The comment parameter is mandatory in generated mode') unless ($comment);
push @approvals, {
'mode' => 'generated',
'comment' => $comment,
};
} elsif ($mode eq 'session') {
# look for already present approval by this user with this role
if ($self->param('multi_role_approval') &&
(! grep {$_->{session_user} eq $user &&
$_->{session_role} eq $role} @approvals)) {
##! 64: 'multi role approval enabled and (user, role) pair not found in present approvals'
push @approvals, {
'mode' => 'session',
'session_user' => $user,
'session_role' => $role,
};
}
elsif (! $self->param('multi_role_approval') &&
! grep {$_->{session_user} eq $user} @approvals) {
##! 64: 'multi role approval disabled and user not found in present approvals'
push @approvals, {
'mode' => 'session',
'session_user' => $user,
'session_role' => $role,
};
}
CTX('log')->application()->info('Unsigned approval for workflow ' . $workflow->id() . " by user $user, role $role");
CTX('log')->audit('approval')->info('operator approval given', {
wfid => $workflow->id(),
user => $user,
role => $role
});
} else {
configuration_error('Unsuported mode given');
}
##! 64: 'approvals: ' . Dumper \@approvals
$approvals = $serializer->serialize(\@approvals);
##! 64: 'approvals serialized: ' . Dumper $approvals
CTX('log')->application()->debug('Total number of approvals ' . scalar @approvals);
$context->param ('approvals' => $approvals);
return 1;
}
1;
__END__
=head1 Name
OpenXPKI::Server::Workflow::Activity::Tools::Approve
=head1 Description
This class implements simple possibility to store approvals as a
serialized array. This allows for easy evaluation of needed approvals
in the condition class Condition::Approved.
The activity has several operational modes, that are determined by the
I<mode> parameter.
=head2 Session Based Approval
This is the default mode, it adds the user and role from the current
session to the list of approvals. Only one approval by the same user is
allowed, if the action is called by the same user mutliple times, the
activity will not update the list of approvals.
If you set the I<mutli_role_approval> parameter to a true value, a user
can approve one time with each role he can impersonate.
=head2 Generated Approval
Adds the information passed via the I<comment> parameter as approval.
Note that there is no duplicate check like in the session approval, if
you call this multiple times you will end up with multiple valid
approvals.
The comment is mandatory, if not given the action will exit with a
workflow configuration error.
=head1 Configuration
=head2 Activity Parameters
=over
=item mode
Operation mode, possible values are I<session> or I<generated>
=item mutli_role_approval
Boolean, allow multiple approvals by same user with differen roles
=item comment
The approval comment to add for generated approvals, mandatory in
generated mode.
=back
=head2 Context Parameters
=over
=item approvals
The serialized array of given approvals, each item is a hash holding the
approval information.
=back
| stefanomarty/openxpki | core/server/OpenXPKI/Server/Workflow/Activity/Tools/Approve.pm | Perl | apache-2.0 | 9,514 |
package Google::Ads::AdWords::v201406::UrlList;
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 %urls_of :ATTR(:get<urls>);
__PACKAGE__->_factory(
[ qw( urls
) ],
{
'urls' => \%urls_of,
},
{
'urls' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
},
{
'urls' => 'urls',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201406::UrlList
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
UrlList from the namespace https://adwords.google.com/api/adwords/cm/v201406.
Wrapper POJO for a list of URLs. The list can be cleared if a request contains a UrlList with an empty urls list.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * urls
=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/UrlList.pm | Perl | apache-2.0 | 1,340 |
=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 SeqStoreConverter::vega::VBasicConverter;
use strict;
use warnings;
use SeqStoreConverter::BasicConverter;
use vars qw(@ISA);
@ISA = qw(SeqStoreConverter::BasicConverter);
sub remove_supercontigs {
my $self = shift;
my $target = $self->target();
my $dbh = $self->dbh();
$self->debug("Vega specific - removing supercontigs from $target");
$dbh->do("DELETE FROM $target.meta ".
"WHERE meta_value like '%supercontig%'");
$dbh->do("DELETE FROM $target.coord_system ".
"WHERE name like 'supercontig'");
$dbh->do("DELETE $target.a ".
"FROM $target.assembly a, $target.seq_region sr ".
"WHERE sr.coord_system_id = 2 ".
"and a.asm_seq_region_id = sr.seq_region_id");
$dbh->do("DELETE FROM $target.seq_region ".
"WHERE coord_system_id = 2");
}
sub copy_other_vega_tables {
my $self = shift;
$self->copy_tables(
# vega tables
"gene_synonym",
"transcript_info",
"current_gene_info",
"current_transcript_info",
"author",
"gene_name",
"transcript_class",
"gene_remark",
"gene_info",
"evidence",
"transcript_remark",
"clone_remark",
"clone_info",
"clone_info_keyword",
"assembly_tag",
);
eval { $self->copy_current_clone_info; };
warn $@ if $@;
}
sub copy_current_clone_info {
my $self=shift;
my $source = $self->source();
my $target = $self->target();
my $sth = $self->dbh()->prepare
("INSERT INTO $target.current_clone_info(clone_id,clone_info_id) SELECT * FROM $source.current_clone_info");
$sth->execute();
$sth->finish();
}
sub update_clone_info {
my $self = shift;
return;
}
sub copy_internal_clone_names {
my $self = shift;
return;
}
sub copy_assembly_exception {
my $self = shift;
# copy assembly_exception table
$self->debug('Vega specific - copying assembly_exception table');
$self->copy_tables('assembly_exception');
my $source = $self->source();
my $target = $self->target();
my $dbh = $self->dbh();
# fix seq_region_id in assembly_exception
$self->debug('Vega specific - Updating seq_region_id in assembly_exception table');
$dbh->do(qq(
UPDATE $target.assembly_exception, $target.tmp_chr_map
SET assembly_exception.seq_region_id = tmp_chr_map.new_id
WHERE assembly_exception.seq_region_id = tmp_chr_map.old_id
));
$dbh->do(qq(
UPDATE $target.assembly_exception, $target.tmp_chr_map
SET assembly_exception.exc_seq_region_id = tmp_chr_map.new_id
WHERE assembly_exception.exc_seq_region_id = tmp_chr_map.old_id
));
# fix seq_region.length if necessary (this is the case if you have an
# assembly_exception at the end of a chromosome)
my $sth1 = $dbh->prepare(qq(
UPDATE $target.seq_region SET length = ? WHERE seq_region_id = ?
));
my $sth2 = $dbh->prepare(qq(
SELECT
sr.seq_region_id,
sr.length,
max(ae.seq_region_end)
FROM
$target.seq_region sr,
$target.assembly_exception ae
WHERE sr.seq_region_id = ae.seq_region_id
GROUP BY ae.seq_region_id
));
$sth2->execute;
while (my ($sr_id, $sr_length, $max_ae_length) = $sth2->fetchrow_array) {
if ($max_ae_length > $sr_length) {
$self->debug(" Updating seq_region.length for $sr_id (old $sr_length, new $max_ae_length)");
$sth1->execute($max_ae_length, $sr_id);
}
}
}
# reset gene, transcript, gene_description and external_db tables back to 30
sub back_patch_schema {
my $self = shift;
$self->debug ("Patching gene, transcript, gene_description and external_db tables back to sch-30");
my $target = $self->target;
my $dbh = $self->dbh;
$dbh->do("DROP TABLE $target.gene");
$dbh->do( qq(CREATE TABLE $target.gene (
`gene_id` int(10) unsigned NOT NULL auto_increment,
`type` varchar(40) NOT NULL default '',
`analysis_id` int(11) default NULL,
`seq_region_id` int(10) unsigned NOT NULL default '0',
`seq_region_start` int(10) unsigned NOT NULL default '0',
`seq_region_end` int(10) unsigned NOT NULL default '0',
`seq_region_strand` tinyint(2) NOT NULL default '0',
`display_xref_id` int(10) unsigned default NULL,
PRIMARY KEY (`gene_id`),
KEY `seq_region_idx` (`seq_region_id`,`seq_region_start`),
KEY `xref_id_index` (`display_xref_id`),
KEY `analysis_idx` (`analysis_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
));
$dbh->do("DROP TABLE $target.transcript");
$dbh->do( qq(CREATE TABLE $target.transcript (
`transcript_id` int(10) unsigned NOT NULL auto_increment,
`gene_id` int(10) unsigned NOT NULL default '0',
`seq_region_id` int(10) unsigned NOT NULL default '0',
`seq_region_start` int(10) unsigned NOT NULL default '0',
`seq_region_end` int(10) unsigned NOT NULL default '0',
`seq_region_strand` tinyint(2) NOT NULL default '0',
`display_xref_id` int(10) unsigned default NULL,
PRIMARY KEY (`transcript_id`),
KEY `seq_region_idx` (`seq_region_id`,`seq_region_start`),
KEY `gene_index` (`gene_id`),
KEY `xref_id_index` (`display_xref_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
));
$dbh->do( qq(CREATE TABLE $target.gene_description (
`gene_id` int(10) unsigned NOT NULL default '0',
`description` text,
PRIMARY KEY (`gene_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
));
$dbh->do("DROP TABLE $target.external_db");
$dbh->do( qq(CREATE TABLE $target.external_db (
`external_db_id` int(11) NOT NULL default '0',
`db_name` varchar(100) NOT NULL default '',
`release` varchar(40) NOT NULL default '',
`status` enum('KNOWNXREF','KNOWN','XREF','PRED','ORTH','PSEUDO') NOT NULL default 'KNOWNXREF',
PRIMARY KEY (`external_db_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
));
}
| mjg17/ensembl | misc-scripts/surgery/SeqStoreConverter/vega/VBasicConverter.pm | Perl | apache-2.0 | 7,197 |
#------------------------------------------------------------------------------
# File: DarwinCore.pm
#
# Description: Darwin Core XMP tags
#
# Revisions: 2013-01-28 - P. Harvey Created
#
# References: 1) http://rs.tdwg.org/dwc/index.htm
#------------------------------------------------------------------------------
package Image::ExifTool::DarwinCore;
use strict;
use vars qw($VERSION);
use Image::ExifTool::XMP;
$VERSION = '1.01';
my %dateTimeInfo = (
# NOTE: Do NOT put "Groups" here because Groups hash must not be common!
Writable => 'date',
Shift => 'Time',
PrintConv => '$self->ConvertDateTime($val)',
PrintConvInv => '$self->InverseDateTime($val,undef,1)',
);
# Darwin Core tags
%Image::ExifTool::DarwinCore::Main = (
GROUPS => { 0 => 'XMP', 1 => 'XMP-dwc', 2 => 'Other' },
NAMESPACE => 'dwc',
WRITABLE => 'string',
NOTES => q{
Tags defined in the Darwin Core (dwc) XMP namespace. See
L<http://rs.tdwg.org/dwc/index.htm> for the official specification.
},
Event => {
Name => 'DCEvent', # (avoid conflict with XMP-iptcExt:Event)
FlatName => 'Event',
Struct => {
STRUCT_NAME => 'DarwinCore Event',
NAMESPACE => 'dwc',
day => { Writable => 'integer', Groups => { 2 => 'Time' } },
earliestDate => { %dateTimeInfo, Groups => { 2 => 'Time' } },
endDayOfYear => { Writable => 'integer', Groups => { 2 => 'Time' } },
eventID => { },
eventRemarks => { Writable => 'lang-alt' },
eventTime => { %dateTimeInfo, Groups => { 2 => 'Time' } },
fieldNotes => { },
fieldNumber => { },
habitat => { },
latestDate => { %dateTimeInfo, Groups => { 2 => 'Time' } },
month => { Writable => 'integer', Groups => { 2 => 'Time' } },
samplingEffort => { },
samplingProtocol => { },
startDayOfYear => { Writable => 'integer', Groups => { 2 => 'Time' } },
verbatimEventDate => { Groups => { 2 => 'Time' } },
year => { Writable => 'integer', Groups => { 2 => 'Time' } },
},
},
# tweak a few of the flattened tag names
EventEventID => { Name => 'EventID', Flat => 1 },
EventEventRemarks => { Name => 'EventRemarks', Flat => 1 },
EventEventTime => { Name => 'EventTime', Flat => 1 },
GeologicalContext => {
FlatName => '', # ('GeologicalContext' is too long)
Struct => {
STRUCT_NAME => 'DarwinCore GeologicalContext',
NAMESPACE => 'dwc',
bed => { },
earliestAgeOrLowestStage => { },
earliestEonOrLowestEonothem => { },
earliestEpochOrLowestSeries => { },
earliestEraOrLowestErathem => { },
earliestPeriodOrLowestSystem=> { },
formation => { },
geologicalContextID => { },
group => { },
highestBiostratigraphicZone => { },
latestAgeOrHighestStage => { },
latestEonOrHighestEonothem => { },
latestEpochOrHighestSeries => { },
latestEraOrHighestErathem => { },
latestPeriodOrHighestSystem => { },
lithostratigraphicTerms => { },
lowestBiostratigraphicZone => { },
member => { },
},
},
GeologicalContextBed => { Name => 'GeologicalContextBed', Flat => 1 },
GeologicalContextFormation => { Name => 'GeologicalContextFormation', Flat => 1 },
GeologicalContextGroup => { Name => 'GeologicalContextGroup', Flat => 1 },
GeologicalContextMember => { Name => 'GeologicalContextMember', Flat => 1 },
Identification => {
FlatName => '', # ('Identification' is redundant)
Struct => {
STRUCT_NAME => 'DarwinCore Identification',
NAMESPACE => 'dwc',
dateIdentified => { %dateTimeInfo, Groups => { 2 => 'Time' } },
identificationID => { },
identificationQualifier => { },
identificationReferences => { },
identificationRemarks => { },
identificationVerificationStatus => { },
identifiedBy => { },
typeStatus => { },
},
},
MeasurementOrFact => {
FlatName => '', # ('MeasurementOrFact' is redundant and too long)
Struct => {
STRUCT_NAME => 'DarwinCore MeasurementOrFact',
NAMESPACE => 'dwc',
measurementAccuracy => { Format => 'real' },
measurementDeterminedBy => { },
measurementDeterminedDate => { %dateTimeInfo, Groups => { 2 => 'Time' } },
measurementID => { },
measurementMethod => { },
measurementRemarks => { },
measurementType => { },
measurementUnit => { },
measurementValue => { },
},
},
Occurrence => {
Struct => {
STRUCT_NAME => 'DarwinCore Occurrence',
NAMESPACE => 'dwc',
associatedMedia => { },
associatedOccurrences => { },
associatedReferences => { },
associatedSequences => { },
associatedTaxa => { },
behavior => { },
catalogNumber => { },
disposition => { },
establishmentMeans => { },
individualCount => { },
individualID => { },
lifeStage => { },
occurrenceDetails => { },
occurrenceID => { },
occurrenceRemarks => { },
occurrenceStatus => { },
otherCatalogNumbers => { },
preparations => { },
previousIdentifications => { },
recordedBy => { },
recordNumber => { },
reproductiveCondition => { },
sex => { },
},
},
OccurrenceOccurrenceRemarks => { Name => 'OccurrenceRemarks', Flat => 1 },
OccurrenceOccurrenceDetails => { Name => 'OccurrenceDetails', Flat => 1 },
OccurrenceOccurrenceID => { Name => 'OccurrenceID', Flat => 1 },
OccurrenceOccurrenceStatus => { Name => 'OccurrenceStatus', Flat => 1 },
Record => {
Struct => {
STRUCT_NAME => 'DarwinCore Record',
NAMESPACE => 'dwc',
basisOfRecord => { },
collectionCode => { },
collectionID => { },
dataGeneralizations => { },
datasetID => { },
datasetName => { },
dynamicProperties => { },
informationWithheld => { },
institutionCode => { },
institutionID => { },
ownerInstitutionCode => { },
},
},
ResourceRelationship => {
FlatName => '', # ('ResourceRelationship' is redundant and too long)
Struct => {
STRUCT_NAME => 'DarwinCore ResourceRelationship',
NAMESPACE => 'dwc',
relatedResourceID => { },
relationshipAccordingTo => { },
relationshipEstablishedDate => { %dateTimeInfo, Groups => { 2 => 'Time' } },
relationshipOfResource => { },
relationshipRemarks => { },
resourceID => { },
resourceRelationshipID => { },
},
},
Taxon => {
Struct => {
STRUCT_NAME => 'DarwinCore Taxon',
NAMESPACE => 'dwc',
acceptedNameUsage => { },
acceptedNameUsageID => { },
class => { },
family => { },
genus => { },
higherClassification => { },
infraspecificEpithet => { },
kingdom => { },
nameAccordingTo => { },
nameAccordingToID => { },
namePublishedIn => { },
namePublishedInID => { },
namePublishedInYear => { },
nomenclaturalCode => { },
nomenclaturalStatus => { },
order => { },
originalNameUsage => { },
originalNameUsageID => { },
parentNameUsage => { },
parentNameUsageID => { },
phylum => { },
scientificName => { },
scientificNameAuthorship => { },
scientificNameID => { },
specificEpithet => { },
subgenus => { },
taxonConceptID => { },
taxonID => { },
taxonRank => { },
taxonRemarks => { },
taxonomicStatus => { },
verbatimTaxonRank => { },
vernacularName => { Writable => 'lang-alt' },
},
},
TaxonTaxonConceptID => { Name => 'TaxonConceptID', Flat => 1 },
TaxonTaxonID => { Name => 'TaxonID', Flat => 1 },
TaxonTaxonRank => { Name => 'TaxonRank', Flat => 1 },
TaxonTaxonRemarks => { Name => 'TaxonRemarks', Flat => 1 },
dctermsLocation => {
Name => 'DCTermsLocation',
Groups => { 2 => 'Location' },
FlatName => 'DC', # ('dctermsLocation' is too long)
Struct => {
STRUCT_NAME => 'DarwinCore DCTermsLocation',
NAMESPACE => 'dwc',
continent => { },
coordinatePrecision => { },
coordinateUncertaintyInMeters => { },
country => { },
countryCode => { },
county => { },
decimalLatitude => { },
decimalLongitude => { },
footprintSpatialFit => { },
footprintSRS => { },
footprintWKT => { },
geodeticDatum => { },
georeferencedBy => { },
georeferencedDate => { },
georeferenceProtocol => { },
georeferenceRemarks => { },
georeferenceSources => { },
georeferenceVerificationStatus => { },
higherGeography => { },
higherGeographyID => { },
island => { },
islandGroup => { },
locality => { },
locationAccordingTo => { },
locationID => { },
locationRemarks => { },
maximumDepthInMeters => { },
maximumDistanceAboveSurfaceInMeters => { },
maximumElevationInMeters => { },
minimumDepthInMeters => { },
minimumDistanceAboveSurfaceInMeters => { },
minimumElevationInMeters => { },
municipality => { },
pointRadiusSpatialFit => { },
stateProvince => { },
verbatimCoordinates => { },
verbatimCoordinateSystem => { },
verbatimDepth => { },
verbatimElevation => { },
verbatimLatitude => { },
verbatimLocality => { },
verbatimLongitude => { },
verbatimSRS => { },
waterBody => { },
},
},
);
1; #end
__END__
=head1 NAME
Image::ExifTool::DarwinCore - Darwin Core XMP tags
=head1 SYNOPSIS
This module is used by Image::ExifTool
=head1 DESCRIPTION
This file contains tag definitions for the Darwin Core XMP namespace.
=head1 AUTHOR
Copyright 2003-2014, 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://rs.tdwg.org/dwc/index.htm>
=back
=head1 SEE ALSO
L<Image::ExifTool::TagNames/XMP Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| gitzain/SortPhotos | Image-ExifTool/lib/Image/ExifTool/DarwinCore.pm | Perl | mit | 13,246 |
# <@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>
package Mail::SpamAssassin::Plugin::HTMLEval;
use strict;
use warnings;
use bytes;
use re 'taint';
use Mail::SpamAssassin::Plugin;
use Mail::SpamAssassin::Locales;
use Mail::SpamAssassin::Util qw(untaint_var);
use vars qw(@ISA);
@ISA = qw(Mail::SpamAssassin::Plugin);
# constructor: register the eval rule
sub new {
my $class = shift;
my $mailsaobject = shift;
# some boilerplate...
$class = ref($class) || $class;
my $self = $class->SUPER::new($mailsaobject);
bless ($self, $class);
# the important bit!
$self->register_eval_rule("html_tag_balance");
$self->register_eval_rule("html_image_only");
$self->register_eval_rule("html_image_ratio");
$self->register_eval_rule("html_charset_faraway");
$self->register_eval_rule("html_tag_exists");
$self->register_eval_rule("html_test");
$self->register_eval_rule("html_eval");
$self->register_eval_rule("html_text_match");
$self->register_eval_rule("html_title_subject_ratio");
$self->register_eval_rule("html_text_not_match");
$self->register_eval_rule("html_range");
$self->register_eval_rule("check_iframe_src");
return $self;
}
sub html_tag_balance {
my ($self, $pms, undef, $rawtag, $rawexpr) = @_;
$rawtag =~ /^([a-zA-Z0-9]+)$/; my $tag = $1;
$rawexpr =~ /^([\<\>\=\!\-\+ 0-9]+)$/; my $expr = $1;
return 0 unless exists $pms->{html}{inside}{$tag};
$pms->{html}{inside}{$tag} =~ /^([\<\>\=\!\-\+ 0-9]+)$/;
my $val = $1;
return eval "\$val $expr";
}
sub html_image_only {
my ($self, $pms, undef, $min, $max) = @_;
return (exists $pms->{html}{inside}{img} &&
exists $pms->{html}{length} &&
$pms->{html}{length} > $min &&
$pms->{html}{length} <= $max);
}
sub html_image_ratio {
my ($self, $pms, undef, $min, $max) = @_;
return 0 unless (exists $pms->{html}{non_space_len} &&
exists $pms->{html}{image_area} &&
$pms->{html}{image_area} > 0);
my $ratio = $pms->{html}{non_space_len} / $pms->{html}{image_area};
return ($ratio > $min && $ratio <= $max);
}
sub html_charset_faraway {
my ($self, $pms) = @_;
return 0 unless exists $pms->{html}{charsets};
my @locales = Mail::SpamAssassin::Util::get_my_locales($pms->{conf}->{ok_locales});
return 0 if grep { $_ eq "all" } @locales;
my $okay = 0;
my $bad = 0;
for my $c (split(' ', $pms->{html}{charsets})) {
if (Mail::SpamAssassin::Locales::is_charset_ok_for_locales($c, @locales)) {
$okay++;
}
else {
$bad++;
}
}
return ($bad && ($bad >= $okay));
}
sub html_tag_exists {
my ($self, $pms, undef, $tag) = @_;
return exists $pms->{html}{inside}{$tag};
}
sub html_test {
my ($self, $pms, undef, $test) = @_;
return $pms->{html}{$test};
}
sub html_eval {
my ($self, $pms, undef, $test, $rawexpr) = @_;
my $expr;
if ($rawexpr =~ /^[\<\>\=\!\-\+ 0-9]+$/) {
$expr = untaint_var($rawexpr);
}
# workaround bug 3320: wierd perl bug where additional, very explicit
# untainting into a new var is required.
my $tainted = $pms->{html}{$test};
return unless defined($tainted);
my $val = $tainted;
# just use the value in $val, don't copy it needlessly
return eval "\$val $expr";
}
sub html_text_match {
my ($self, $pms, undef, $text, $regexp) = @_;
for my $string (@{ $pms->{html}{$text} }) {
if (defined $string && $string =~ /${regexp}/) {
return 1;
}
}
return 0;
}
sub html_title_subject_ratio {
my ($self, $pms, undef, $ratio) = @_;
my $subject = $pms->get('Subject');
if ($subject eq '') {
return 0;
}
my $max = 0;
for my $string (@{ $pms->{html}{title} }) {
if ($string) {
my $ratio = length($string) / length($subject);
$max = $ratio if $ratio > $max;
}
}
return $max > $ratio;
}
sub html_text_not_match {
my ($self, $pms, undef, $text, $regexp) = @_;
for my $string (@{ $pms->{html}{$text} }) {
if (defined $string && $string !~ /${regexp}/) {
return 1;
}
}
return 0;
}
sub html_range {
my ($self, $pms, undef, $test, $min, $max) = @_;
return 0 unless exists $pms->{html}{$test};
$test = $pms->{html}{$test};
# not all perls understand what "inf" means, so we need to do
# non-numeric tests! urg!
if (!defined $max || $max eq "inf") {
return ($test eq "inf") ? 1 : ($test > $min);
}
elsif ($test eq "inf") {
# $max < inf, so $test == inf means $test > $max
return 0;
}
else {
# if we get here everything should be a number
return ($test > $min && $test <= $max);
}
}
sub check_iframe_src {
my ($self, $pms) = @_;
foreach my $v ( values %{$pms->{html}->{uri_detail}} ) {
return 1 if $v->{types}->{iframe};
}
return 0;
}
1;
| gitpan/Mail-SpamAssassin | lib/Mail/SpamAssassin/Plugin/HTMLEval.pm | Perl | apache-2.0 | 5,458 |
package Moose::Meta::Method::Accessor::Native::String::prepend;
BEGIN {
$Moose::Meta::Method::Accessor::Native::String::prepend::AUTHORITY = 'cpan:STEVAN';
}
{
$Moose::Meta::Method::Accessor::Native::String::prepend::VERSION = '2.0602';
}
use strict;
use warnings;
use Moose::Role;
with 'Moose::Meta::Method::Accessor::Native::Writer' => {
-excludes => [
qw(
_minimum_arguments
_maximum_arguments
_inline_optimized_set_new_value
)
]
};
sub _minimum_arguments { 1 }
sub _maximum_arguments { 1 }
sub _potential_value {
my $self = shift;
my ($slot_access) = @_;
return '$_[0] . ' . $slot_access;
}
sub _inline_optimized_set_new_value {
my $self = shift;
my ($inv, $new, $slot_access) = @_;
return $slot_access . ' = $_[0] . ' . $slot_access . ';';
}
no Moose::Role;
1;
| leighpauls/k2cro4 | third_party/perl/perl/vendor/lib/Moose/Meta/Method/Accessor/Native/String/prepend.pm | Perl | bsd-3-clause | 873 |
#!/usr/bin/env perl
#
#
# Script to convert GERALD export files to SAM format.
#
#
#
########## License:
#
# The MIT License
#
# Original SAMtools version 0.1.2 copyright (c) 2008-2009 Genome Research Ltd.
# Modifications from version 0.1.2 to 2.0.0 copyright (c) 2010 Illumina, Inc.
#
# 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.
#
#
#
########## ChangeLog:
#
# Version: 2.0.0 (15FEB2010)
# Script updated by Illumina in conjunction with CASAVA 1.7.0 release.
# Major changes are as follows:
# - The CIGAR string has been updated to include all gaps from ELANDv2 alignments.
# - The ELAND single read alignment score is always stored in the optional "SM" field
# and the ELAND paired read alignment score is stored in the optional "AS" field
# when it exists.
# - The MAPQ value is set to the higher of the two alignment scores, but no greater
# than 254, i.e. min(254,max(SM,AS))
# - The SAM "proper pair" bit (0x0002) is now set for read pairs meeting ELAND's
# expected orientation and insert size criteria.
# - The default quality score translation is set for export files which contain
# Phread+64 quality values. An option, "--qlogodds", has been added to
# translate quality values from the Solexa+64 format used in export files prior
# to Pipeline 1.3
# - The export match descriptor is now reverse-complemented when necessary such that
# it always corresponds to the forward strand of the reference, to be consistent
# with other information in the SAM record. It is now written to the optional
# 'XD' field (rather than 'MD') to acknowledge its minor differences from the
# samtools match descriptor (see additional detail below).
# - An option, "--nofilter", has been added to include reads which have failed
# primary analysis quality filtration. Such reads will have the corresponding
# SAM flag bit (0x0200) set.
# - Labels in the export 'contig' field are preserved by setting RNAME to
# "$export_chromosome/$export_contig" when then contig label exists.
#
#
# Contact: lh3
# Version: 0.1.2 (03JAN2009)
#
#
#
########## Known Conversion Limitations:
#
# - Export records for reads that map to a position < 1 (allowed in export format), are converted
# to unmapped reads in the SAM record.
# - Export records contain the reserved chromosome names: "NM" and "QC". "NM" indicates that the
# aligner could not map the read to the reference sequence set, and "QC" means that the
# aligner did not attempt to map the read due to some technical limitation. Both of these
# alignment types are collapsed to the single unmapped alignment state in the SAM record.
# - The export match descriptor is slightly different than the samtools match descriptor. For
# this reason it is stored in the optional SAM field 'XD' (and not 'MD'). Note that the
# export match descriptor differs from the samtools version in two respects: (1) indels
# are explicitly closed with the '$' character and (2) insertions must be enumerated in
# the match descriptor. For example a 35-base read with a two-base insertion is described
# as: 20^2$14
#
#
#
my $version = "2.0.0";
use strict;
use warnings;
use File::Spec qw(splitpath);
use Getopt::Long;
use List::Util qw(min max);
use constant {
EXPORT_INDEX => 6,
EXPORT_READNO => 7,
EXPORT_READ => 8,
EXPORT_QUAL => 9,
EXPORT_CHROM => 10,
EXPORT_CONTIG => 11,
EXPORT_POS => 12,
EXPORT_STRAND => 13,
EXPORT_MD => 14,
EXPORT_SEMAP => 15,
EXPORT_PEMAP => 16,
EXPORT_PASSFILT => 21,
};
use constant {
SAM_QNAME => 0,
SAM_FLAG => 1,
SAM_RNAME => 2,
SAM_POS => 3,
SAM_MAPQ => 4,
SAM_CIGAR => 5,
SAM_MRNM => 6,
SAM_MPOS => 7,
SAM_ISIZE => 8,
SAM_SEQ => 9,
SAM_QUAL => 10,
};
# function prototypes for Richard's code
sub match_desc_to_cigar($);
sub match_desc_frag_length($);
sub reverse_compl_match_descriptor($);
sub write_header($;$;$);
&export2sam;
exit;
sub export2sam {
my $cmdline = $0 . " " . join(" ",@ARGV);
my $arg_count = scalar @ARGV;
my @spval = File::Spec->splitpath($0);
my $progname = $spval[2];
my $is_logodds_qvals = 0; # if true, assume files contain logodds (i.e. "solexa") quality values
my $is_nofilter = 0;
my $read1file;
my $read2file;
my $print_version = 0;
my $help = 0;
my $result = GetOptions( "qlogodds" => \$is_logodds_qvals,
"nofilter" => \$is_nofilter,
"read1=s" => \$read1file,
"read2=s" => \$read2file,
"version" => \$print_version,
"help" => \$help );
my $usage = <<END;
$progname converts GERALD export files to SAM format.
Usage: $progname --read1=FILENAME [ options ] | --version | --help
--read1=FILENAME read1 export file (mandatory)
--read2=FILENAME read2 export file
--nofilter include reads that failed the pipeline/RTA purity filter
--qlogodds assume export file(s) use logodds quality values as reported
by pipeline prior to v1.3 (default: phred quality values)
END
my $version_msg = <<END;
$progname version: $version
END
if((not $result) or $help or ($arg_count==0)) {
die($usage);
}
if(@ARGV) {
print STDERR "\nERROR: Unrecognized arguments: " . join(" ",@ARGV) . "\n\n";
die($usage);
}
if($print_version) {
die($version_msg);
}
if(not defined($read1file)) {
print STDERR "\nERROR: read1 export file must be specified\n\n";
die($usage);
}
my ($fh1, $fh2, $is_paired);
open($fh1, $read1file) or die("\nERROR: Can't open read1 export file: $read1file\n\n");
$is_paired = defined $read2file;
if ($is_paired) {
open($fh2, $read2file) or die("\nERROR: Can't open read2 export file: $read2file\n\n");
}
# quality value conversion table
my @conv_table;
if($is_logodds_qvals){ # convert from solexa+64 quality values (pipeline pre-v1.3):
for (-64..64) {
$conv_table[$_+64] = int(33 + 10*log(1+10**($_/10.0))/log(10)+.499);
}
} else { # convert from phred+64 quality values (pipeline v1.3+):
for (-64..-1) {
$conv_table[$_+64] = undef;
}
for (0..64) {
$conv_table[$_+64] = int(33 + $_);
}
}
# write the header
print write_header( $progname, $version, $cmdline );
# core loop
my $export_line_count = 0;
while (<$fh1>) {
$export_line_count++;
my (@s1, @s2);
&export2sam_aux($_, $export_line_count, \@s1, \@conv_table, $is_paired, 1, $is_nofilter);
if ($is_paired) {
my $read2line = <$fh2>;
if(not $read2line){
die("\nERROR: read1 and read2 export files do not contain the same number of reads.\n Extra reads observed in read1 file at line no: $export_line_count.\n\n");
}
&export2sam_aux($read2line, $export_line_count, \@s2, \@conv_table, $is_paired, 2, $is_nofilter);
if (@s1 && @s2) { # then set mate coordinate
if($s1[SAM_QNAME] ne $s2[SAM_QNAME]){
die("\nERROR: Non-paired reads in export files on line: $export_line_count.\n Read1: $_ Read2: $read2line\n");
}
my $isize = 0;
if ($s1[SAM_RNAME] ne '*' && $s1[SAM_RNAME] eq $s2[SAM_RNAME]) { # then calculate $isize
my $x1 = ($s1[SAM_FLAG] & 0x10)? $s1[SAM_POS] + length($s1[SAM_SEQ]) : $s1[SAM_POS];
my $x2 = ($s2[SAM_FLAG] & 0x10)? $s2[SAM_POS] + length($s2[SAM_SEQ]) : $s2[SAM_POS];
$isize = $x2 - $x1;
}
foreach ([\@s1,\@s2,$isize],[\@s2,\@s1,-$isize]){
my ($sa,$sb,$is) = @{$_};
if ($sb->[SAM_RNAME] ne '*') {
$sa->[SAM_MRNM] = ($sb->[SAM_RNAME] eq $sa->[SAM_RNAME]) ? "=" : $sb->[SAM_RNAME];
$sa->[SAM_MPOS] = $sb->[SAM_POS];
$sa->[SAM_ISIZE] = $is;
$sa->[SAM_FLAG] |= 0x20 if ($sb->[SAM_FLAG] & 0x10);
} else {
$sa->[SAM_FLAG] |= 0x8;
}
}
}
}
print join("\t", @s1), "\n" if (@s1);
print join("\t", @s2), "\n" if (@s2 && $is_paired);
}
close($fh1);
if($is_paired) {
while(my $read2line = <$fh2>){
$export_line_count++;
die("\nERROR: read1 and read2 export files do not contain the same number of reads.\n Extra reads observed in read2 file at line no: $export_line_count.\n\n");
}
close($fh2);
}
}
sub export2sam_aux {
my ($line, $line_no, $s, $ct, $is_paired, $read_no, $is_nofilter) = @_;
chomp($line);
my @t = split("\t", $line);
@$s = ();
my $isPassFilt = ($t[EXPORT_PASSFILT] eq 'Y');
return if(not ($isPassFilt or $is_nofilter));
# read name
$s->[SAM_QNAME] = $t[1]? "$t[0]_$t[1]:$t[2]:$t[3]:$t[4]:$t[5]" : "$t[0]:$t[2]:$t[3]:$t[4]:$t[5]";
# initial flag (will be updated later)
$s->[SAM_FLAG] = 0;
if($is_paired) {
if($t[EXPORT_READNO] != $read_no){
die("\nERROR: read$read_no export file contains record with read number: " .$t[EXPORT_READNO] . " on line: $line_no\n\n");
}
$s->[SAM_FLAG] |= 1 | 1<<(5 + $read_no);
}
$s->[SAM_FLAG] |= 0x200 if (not $isPassFilt);
# read & quality
my $is_export_rev = ($t[EXPORT_STRAND] eq 'R');
if ($is_export_rev) { # then reverse the sequence and quality
$s->[SAM_SEQ] = reverse($t[EXPORT_READ]);
$s->[SAM_SEQ] =~ tr/ACGTacgt/TGCAtgca/;
$s->[SAM_QUAL] = reverse($t[EXPORT_QUAL]);
} else {
$s->[SAM_SEQ] = $t[EXPORT_READ];
$s->[SAM_QUAL] = $t[EXPORT_QUAL];
}
my @convqual = ();
foreach (unpack('C*', $s->[SAM_QUAL])){
my $val=$ct->[$_];
if(not defined $val){
my $msg="\nERROR: can't interpret export quality value: " . $_ . " in read$read_no export file, line: $line_no\n";
if( $_ < 64 ) { $msg .= " Use --qlogodds flag to translate logodds (solexa) quality values.\n"; }
die($msg . "\n");
}
push @convqual,$val;
}
$s->[SAM_QUAL] = pack('C*',@convqual); # change coding
# coor
my $has_coor = 0;
$s->[SAM_RNAME] = "*";
if ($t[EXPORT_CHROM] eq 'NM' or $t[EXPORT_CHROM] eq 'QC') {
$s->[SAM_FLAG] |= 0x4; # unmapped
} elsif ($t[EXPORT_CHROM] =~ /(\d+):(\d+):(\d+)/) {
$s->[SAM_FLAG] |= 0x4; # TODO: should I set BAM_FUNMAP in this case?
push(@$s, "H0:i:$1", "H1:i:$2", "H2:i:$3")
} elsif ($t[EXPORT_POS] < 1) {
$s->[SAM_FLAG] |= 0x4; # unmapped
} else {
$s->[SAM_RNAME] = $t[EXPORT_CHROM];
$s->[SAM_RNAME] .= "/" . $t[EXPORT_CONTIG] if($t[EXPORT_CONTIG] ne '');
$has_coor = 1;
}
$s->[SAM_POS] = $has_coor? $t[EXPORT_POS] : 0;
# print STDERR "t[14] = " . $t[14] . "\n";
my $matchDesc = '';
$s->[SAM_CIGAR] = "*";
if($has_coor){
$matchDesc = ($is_export_rev) ? reverse_compl_match_descriptor($t[EXPORT_MD]) : $t[EXPORT_MD];
if($matchDesc =~ /\^/){
# construct CIGAR string using Richard's function
$s->[SAM_CIGAR] = match_desc_to_cigar($matchDesc); # indel processing
} else {
$s->[SAM_CIGAR] = length($s->[SAM_SEQ]) . "M";
}
}
# print STDERR "cigar_string = $cigar_string\n";
$s->[SAM_FLAG] |= 0x10 if ($has_coor && $is_export_rev);
if($has_coor){
my $semap = ($t[EXPORT_SEMAP] ne '') ? $t[EXPORT_SEMAP] : 0;
my $pemap = 0;
if($is_paired) {
$pemap = ($t[EXPORT_PEMAP] ne '') ? $t[EXPORT_PEMAP] : 0;
# set `proper pair' bit if non-blank, non-zero PE alignment score:
$s->[SAM_FLAG] |= 0x02 if ($pemap > 0);
}
$s->[SAM_MAPQ] = min(254,max($semap,$pemap));
} else {
$s->[SAM_MAPQ] = 0;
}
# mate coordinate
$s->[SAM_MRNM] = '*';
$s->[SAM_MPOS] = 0;
$s->[SAM_ISIZE] = 0;
# aux
push(@$s, "BC:Z:$t[EXPORT_INDEX]") if ($t[EXPORT_INDEX]);
if($has_coor){
# The export match descriptor differs slightly from the samtools match descriptor.
# In order for the converted SAM files to be as compliant as possible,
# we put the export match descriptor in optional field 'XD' rather than 'MD':
push(@$s, "XD:Z:$matchDesc");
push(@$s, "SM:i:$t[EXPORT_SEMAP]") if ($t[EXPORT_SEMAP] ne '');
push(@$s, "AS:i:$t[EXPORT_PEMAP]") if ($is_paired and ($t[EXPORT_PEMAP] ne ''));
}
}
#
# the following code is taken from Richard Shaw's sorted2sam.pl file
#
sub reverse_compl_match_descriptor($)
{
# print "\nREVERSING THE MATCH DESCRIPTOR!\n";
my ($match_desc) = @_;
my $rev_compl_match_desc = reverse($match_desc);
$rev_compl_match_desc =~ tr/ACGT\^\$/TGCA\$\^/;
# Unreverse the digits of numbers.
$rev_compl_match_desc = join('',
map {($_ =~ /\d+/)
? join('', reverse(split('', $_)))
: $_} split(/(\d+)/,
$rev_compl_match_desc));
return $rev_compl_match_desc;
}
sub match_desc_to_cigar($)
{
my ($match_desc) = @_;
my @match_desc_parts = split(/(\^.*?\$)/, $match_desc);
my $cigar_str = '';
my $cigar_del_ch = 'D';
my $cigar_ins_ch = 'I';
my $cigar_match_ch = 'M';
foreach my $match_desc_part (@match_desc_parts) {
next if (!$match_desc_part);
if ($match_desc_part =~ /^\^([ACGTN]+)\$$/) {
# Deletion
$cigar_str .= (length($1) . $cigar_del_ch);
} elsif ($match_desc_part =~ /^\^(\d+)\$$/) {
# Insertion
$cigar_str .= ($1 . $cigar_ins_ch);
} else {
$cigar_str .= (match_desc_frag_length($match_desc_part)
. $cigar_match_ch);
}
}
return $cigar_str;
}
#------------------------------------------------------------------------------
sub match_desc_frag_length($)
{
my ($match_desc_str) = @_;
my $len = 0;
my @match_desc_fields = split(/([ACGTN]+)/, $match_desc_str);
foreach my $match_desc_field (@match_desc_fields) {
next if ($match_desc_field eq '');
$len += (($match_desc_field =~ /(\d+)/)
? $1 : length($match_desc_field));
}
return $len;
}
# argument holds the command line
sub write_header($;$;$)
{
my ($progname,$version,$cl) = @_;
my $complete_header = "";
$complete_header .= "\@PG\tID:$progname\tVN:$version\tCL:$cl\n";
return $complete_header;
}
| wanpinglee/scissors | src/outsources/samtools/misc/export2sam.pl | Perl | mit | 15,255 |
#line 1
package Module::Install::Fetch;
use strict;
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
BEGIN {
$VERSION = '1.04';
@ISA = 'Module::Install::Base';
$ISCORE = 1;
}
sub get_file {
my ($self, %args) = @_;
my ($scheme, $host, $path, $file) =
$args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return;
if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) {
$args{url} = $args{ftp_url}
or (warn("LWP support unavailable!\n"), return);
($scheme, $host, $path, $file) =
$args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return;
}
$|++;
print "Fetching '$file' from $host... ";
unless (eval { require Socket; Socket::inet_aton($host) }) {
warn "'$host' resolve failed!\n";
return;
}
return unless $scheme eq 'ftp' or $scheme eq 'http';
require Cwd;
my $dir = Cwd::getcwd();
chdir $args{local_dir} or return if exists $args{local_dir};
if (eval { require LWP::Simple; 1 }) {
LWP::Simple::mirror($args{url}, $file);
}
elsif (eval { require Net::FTP; 1 }) { eval {
# use Net::FTP to get past firewall
my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600);
$ftp->login("anonymous", 'anonymous@example.com');
$ftp->cwd($path);
$ftp->binary;
$ftp->get($file) or (warn("$!\n"), return);
$ftp->quit;
} }
elsif (my $ftp = $self->can_run('ftp')) { eval {
# no Net::FTP, fallback to ftp.exe
require FileHandle;
my $fh = FileHandle->new;
local $SIG{CHLD} = 'IGNORE';
unless ($fh->open("|$ftp -n")) {
warn "Couldn't open ftp: $!\n";
chdir $dir; return;
}
my @dialog = split(/\n/, <<"END_FTP");
open $host
user anonymous anonymous\@example.com
cd $path
binary
get $file $file
quit
END_FTP
foreach (@dialog) { $fh->print("$_\n") }
$fh->close;
} }
else {
warn "No working 'ftp' program available!\n";
chdir $dir; return;
}
unless (-f $file) {
warn "Fetching failed: $@\n";
chdir $dir; return;
}
return if exists $args{size} and -s $file != $args{size};
system($args{run}) if exists $args{run};
unlink($file) if $args{remove};
print(((!exists $args{check_for} or -e $args{check_for})
? "done!" : "failed! ($!)"), "\n");
chdir $dir; return !$?;
}
1;
| xiaokai-wang/nginx-discovery | modules/nginx-upsync-module/test/inc/Module/Install/Fetch.pm | Perl | bsd-2-clause | 2,455 |
#
# 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.
#
require 5.6.0;
use strict;
use warnings;
use Thrift;
#
# Protocol exceptions
#
package TProtocolException;
use base('Thrift::TException');
use constant UNKNOWN => 0;
use constant INVALID_DATA => 1;
use constant NEGATIVE_SIZE => 2;
use constant SIZE_LIMIT => 3;
use constant BAD_VERSION => 4;
use constant NOT_IMPLEMENTED => 5;
use constant MISSING_REQUIRED_FIELD => 6;
sub new {
my $classname = shift;
my $self = $classname->SUPER::new();
return bless($self,$classname);
}
#
# Protocol base class module.
#
package Thrift::Protocol;
sub new {
my $classname = shift;
my $self = {};
my $trans = shift;
$self->{trans}= $trans;
return bless($self,$classname);
}
sub getTransport
{
my $self = shift;
return $self->{trans};
}
#
# Writes the message header
#
# @param string $name Function name
# @param int $type message type TMessageType::CALL or TMessageType::REPLY
# @param int $seqid The sequence id of this message
#
sub writeMessageBegin
{
my ($name, $type, $seqid);
die "abstract";
}
#
# Close the message
#
sub writeMessageEnd {
die "abstract";
}
#
# Writes a struct header.
#
# @param string $name Struct name
# @throws TException on write error
# @return int How many bytes written
#
sub writeStructBegin {
my ($name);
die "abstract";
}
#
# Close a struct.
#
# @throws TException on write error
# @return int How many bytes written
#
sub writeStructEnd {
die "abstract";
}
#
# Starts a field.
#
# @param string $name Field name
# @param int $type Field type
# @param int $fid Field id
# @throws TException on write error
# @return int How many bytes written
#
sub writeFieldBegin {
my ($fieldName, $fieldType, $fieldId);
die "abstract";
}
sub writeFieldEnd {
die "abstract";
}
sub writeFieldStop {
die "abstract";
}
sub writeMapBegin {
my ($keyType, $valType, $size);
die "abstract";
}
sub writeMapEnd {
die "abstract";
}
sub writeListBegin {
my ($elemType, $size);
die "abstract";
}
sub writeListEnd {
die "abstract";
}
sub writeSetBegin {
my ($elemType, $size);
die "abstract";
}
sub writeSetEnd {
die "abstract";
}
sub writeBool {
my ($bool);
die "abstract";
}
sub writeByte {
my ($byte);
die "abstract";
}
sub writeI16 {
my ($i16);
die "abstract";
}
sub writeI32 {
my ($i32);
die "abstract";
}
sub writeI64 {
my ($i64);
die "abstract";
}
sub writeDouble {
my ($dub);
die "abstract";
}
sub writeString
{
my ($str);
die "abstract";
}
#
# Reads the message header
#
# @param string $name Function name
# @param int $type message type TMessageType::CALL or TMessageType::REPLY
# @parem int $seqid The sequence id of this message
#
sub readMessageBegin
{
my ($name, $type, $seqid);
die "abstract";
}
#
# Read the close of message
#
sub readMessageEnd
{
die "abstract";
}
sub readStructBegin
{
my($name);
die "abstract";
}
sub readStructEnd
{
die "abstract";
}
sub readFieldBegin
{
my ($name, $fieldType, $fieldId);
die "abstract";
}
sub readFieldEnd
{
die "abstract";
}
sub readMapBegin
{
my ($keyType, $valType, $size);
die "abstract";
}
sub readMapEnd
{
die "abstract";
}
sub readListBegin
{
my ($elemType, $size);
die "abstract";
}
sub readListEnd
{
die "abstract";
}
sub readSetBegin
{
my ($elemType, $size);
die "abstract";
}
sub readSetEnd
{
die "abstract";
}
sub readBool
{
my ($bool);
die "abstract";
}
sub readByte
{
my ($byte);
die "abstract";
}
sub readI16
{
my ($i16);
die "abstract";
}
sub readI32
{
my ($i32);
die "abstract";
}
sub readI64
{
my ($i64);
die "abstract";
}
sub readDouble
{
my ($dub);
die "abstract";
}
sub readString
{
my ($str);
die "abstract";
}
#
# The skip function is a utility to parse over unrecognized data without
# causing corruption.
#
# @param TType $type What type is it
#
sub skip
{
my $self = shift;
my $type = shift;
my $ref;
my $result;
my $i;
if($type == TType::BOOL)
{
return $self->readBool(\$ref);
}
elsif($type == TType::BYTE){
return $self->readByte(\$ref);
}
elsif($type == TType::I16){
return $self->readI16(\$ref);
}
elsif($type == TType::I32){
return $self->readI32(\$ref);
}
elsif($type == TType::I64){
return $self->readI64(\$ref);
}
elsif($type == TType::DOUBLE){
return $self->readDouble(\$ref);
}
elsif($type == TType::STRING)
{
return $self->readString(\$ref);
}
elsif($type == TType::STRUCT)
{
$result = $self->readStructBegin(\$ref);
while (1) {
my ($ftype,$fid);
$result += $self->readFieldBegin(\$ref, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
$result += $self->skip($ftype);
$result += $self->readFieldEnd();
}
$result += $self->readStructEnd();
return $result;
}
elsif($type == TType::MAP)
{
my($keyType,$valType,$size);
$result = $self->readMapBegin(\$keyType, \$valType, \$size);
for ($i = 0; $i < $size; $i++) {
$result += $self->skip($keyType);
$result += $self->skip($valType);
}
$result += $self->readMapEnd();
return $result;
}
elsif($type == TType::SET)
{
my ($elemType,$size);
$result = $self->readSetBegin(\$elemType, \$size);
for ($i = 0; $i < $size; $i++) {
$result += $self->skip($elemType);
}
$result += $self->readSetEnd();
return $result;
}
elsif($type == TType::LIST)
{
my ($elemType,$size);
$result = $self->readListBegin(\$elemType, \$size);
for ($i = 0; $i < $size; $i++) {
$result += $self->skip($elemType);
}
$result += $self->readListEnd();
return $result;
}
return 0;
}
#
# Utility for skipping binary data
#
# @param TTransport $itrans TTransport object
# @param int $type Field type
#
sub skipBinary
{
my $self = shift;
my $itrans = shift;
my $type = shift;
if($type == TType::BOOL)
{
return $itrans->readAll(1);
}
elsif($type == TType::BYTE)
{
return $itrans->readAll(1);
}
elsif($type == TType::I16)
{
return $itrans->readAll(2);
}
elsif($type == TType::I32)
{
return $itrans->readAll(4);
}
elsif($type == TType::I64)
{
return $itrans->readAll(8);
}
elsif($type == TType::DOUBLE)
{
return $itrans->readAll(8);
}
elsif( $type == TType::STRING )
{
my @len = unpack('N', $itrans->readAll(4));
my $len = $len[0];
if ($len > 0x7fffffff) {
$len = 0 - (($len - 1) ^ 0xffffffff);
}
return 4 + $itrans->readAll($len);
}
elsif( $type == TType::STRUCT )
{
my $result = 0;
while (1) {
my $ftype = 0;
my $fid = 0;
my $data = $itrans->readAll(1);
my @arr = unpack('c', $data);
$ftype = $arr[0];
if ($ftype == TType::STOP) {
last;
}
# I16 field id
$result += $itrans->readAll(2);
$result += $self->skipBinary($itrans, $ftype);
}
return $result;
}
elsif($type == TType::MAP)
{
# Ktype
my $data = $itrans->readAll(1);
my @arr = unpack('c', $data);
my $ktype = $arr[0];
# Vtype
$data = $itrans->readAll(1);
@arr = unpack('c', $data);
my $vtype = $arr[0];
# Size
$data = $itrans->readAll(4);
@arr = unpack('N', $data);
my $size = $arr[0];
if ($size > 0x7fffffff) {
$size = 0 - (($size - 1) ^ 0xffffffff);
}
my $result = 6;
for (my $i = 0; $i < $size; $i++) {
$result += $self->skipBinary($itrans, $ktype);
$result += $self->skipBinary($itrans, $vtype);
}
return $result;
}
elsif($type == TType::SET || $type == TType::LIST)
{
# Vtype
my $data = $itrans->readAll(1);
my @arr = unpack('c', $data);
my $vtype = $arr[0];
# Size
$data = $itrans->readAll(4);
@arr = unpack('N', $data);
my $size = $arr[0];
if ($size > 0x7fffffff) {
$size = 0 - (($size - 1) ^ 0xffffffff);
}
my $result = 5;
for (my $i = 0; $i < $size; $i++) {
$result += $self->skipBinary($itrans, $vtype);
}
return $result;
}
return 0;
}
#
# Protocol factory creates protocol objects from transports
#
package TProtocolFactory;
sub new {
my $classname = shift;
my $self = {};
return bless($self,$classname);
}
#
# Build a protocol from the base transport
#
# @return TProtcol protocol
#
sub getProtocol
{
my ($trans);
die "interface";
}
1;
| chjp2046/fbthrift | thrift/lib/perl/lib/Thrift/Protocol.pm | Perl | apache-2.0 | 9,942 |
#!/usr/bin/env perl
use strict;
use warnings;
use constant N_GRP => 6;
my $chcnt = 0;
my $idlen = 0;
my $numlen = 4;
my @ch;
my @hr;
while (<>) {
chomp;
# printf "LINE: {%s}\n", $_;
unless (/^\s*(\w+)\s*:\s*(.*)\|$/) {
next;
}
my ($id, $line) = ($1, $2);
if (uc($id) =~ /STATISTICS/) {
if (@hr != 0) {
printf "header already parsed\n";
exit 1;
}
@hr = ($id);
for my $f (split '\|', $line) {
$f =~ s/(?:^\s*|\s*$)//g;
push @hr, $f;
}
next;
}
++$chcnt;
$idlen = length($id) if (length($id) > $idlen);
my @groups = split '\|', $line;
#printf "%3d: id: %s, groups: %d\n", $chcnt, $id, scalar(@groups);
if (@groups != N_GRP()) {
printf "id %s: group not 6\n", $id;
exit 1;
}
my $x = [$id];
for my $g (@groups) {
unless ($g =~ /P\s*(\d+)\s*\(\s*(\d+)%\), F\s*(\d+)/) {
printf "invalid: %s\n", $g;
exit 1;
}
my ($pass, $rate, $fail) = ($1, $2, $3);
printf "%15s: pass %d, fail %d, rate %d%%\n", $id, $pass, $fail, $rate;
$numlen = length($pass) if (length($pass) > $numlen);
$numlen = length($fail) if (length($fail) > $numlen);
push @{$x}, [$pass, $fail, $rate];
}
push @ch, $x;
}
printf "Total: %d\n", $chcnt;
my $fmt_id = "%${idlen}s:";
my $fmt_pf = "P%${numlen}d F%${numlen}d (%3d%%)";
my $pf_len = length(sprintf($fmt_pf, 1, 1, 1));
my $fmt_hr = "%${pf_len}s";
printf "%s %s\n", sprintf($fmt_id, $hr[0]),
join('|', map { sprintf($fmt_hr, $_); } @hr[1 .. $#hr]);
for my $x (@ch) {
my $str_id = sprintf $fmt_id, $x->[0];
my @str_pfs = ();
for my $i (1 .. $#$x) {
my $str_pf = sprintf $fmt_pf, $x->[$i][0], $x->[$i][1], $x->[$i][2];
push @str_pfs, $str_pf;
}
my $str_line = join '|', @str_pfs;
printf "%s %s\n", $str_id, $str_line;
}
| zeroxia/mystery | archive/2013/perl/tabify.pl | Perl | mit | 1,726 |
#!/usr/bin/perl
use strict;
use warnings;
my $file = shift or die("Usage: $0 <Matrix_file_U133.gz>\n");
my $u133dict = "/net/isi-dcnl/ifs/user_data/jochan/Group/qgong/hg19/Annotation/HG-U133A_2.na34.annot.txt";
my %u133gs;
open IN, $u133dict or die($!);
while (<IN>) {
chomp;
my @a = split;
$u133gs{ $a[0] } = $a[1];
}
close IN;
$u133gs{"ID_REF"} = "GeneSymbol";
open my $fh, '-|', '/usr/bin/gunzip', '-c', $file or die($!);
while (<$fh>) {
chomp;
next if /^$/ or /^!/;
s/"//g;
my @a = split /\t/;
next unless exists $u133gs{ $a[0] };
$a[0] = $u133gs{ $a[0] };
print join "\t", @a;
print "\n";
}
close $fh;
| littlegq/PerlPrograms | U133AMatrixGeneSymbolConvertor.pl | Perl | mit | 654 |
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use lib 'lib';
use RUM::SpliceSignals;
my @donor = RUM::SpliceSignals->donor;
my @donor_rev = RUM::SpliceSignals->donor_rev;
my @acceptor = RUM::SpliceSignals->acceptor;
my @acceptor_rev = RUM::SpliceSignals->acceptor_rev;
# Written by Gregory R. Grant
# University of Pennsylvania, 2010
if(@ARGV < 2) {
die "
Usage: sam2xs-flag.pl <sam file> <genome seq>
";
}
my $genome_sequence = $ARGV[1];
$|=1;
sub load_genome {
my ($genome_filename) = @_;
my %seq_for_chr;
open my $genome_fh, '<', $genome_filename;
while (defined (my $line = <$genome_fh>)) {
chomp($line);
$line =~ s/^>//;
my $name = $line;
$line = <$genome_fh>;
chomp($line);
$seq_for_chr{$name} = $line;
}
return \%seq_for_chr;
}
my $seq_for_chr = load_genome($genome_sequence);
open my $infile, $ARGV[0];
my $line = <$infile>;
while ($line =~ /^@..\t/) {
print $line;
$line = <$infile>;
}
while (defined $line) {
chomp $line;
my ($qname, $flag, $rname, $pos, $mapq, $cigar, $rnext, $pnext, $tlen,
$seq, $qual, @optional) = split /\t/, $line;
my $xs_tag = xs_a_tag_for_sam($rname, $pos, $cigar, $seq_for_chr);
if (defined($xs_tag)) {
print "$line\t$xs_tag\n";
}
else {
print "$line\n";
}
$line = <$infile>;
}
sub xs_a_tag_for_sam {
my ($rname, $pos, $cigar, $seq_for_rname) = @_;
my @intron_at_span;
$rname =~ s/:.*//;
# Examine the CIGAR string to build up a list of spans, and mark a
# span (in $intron_at_span) that is over an intron.
my @spans;
while($cigar =~ /^(\d+)([^\d])/) {
my ($num, $type) = ($1, $2);
if ($type eq 'M') {
my $E = $pos + $num - 1;
push @spans, [$pos, $E];
$pos = $E;
}
if ($type eq 'D' || $type eq 'N') {
$pos = $pos + $num + 1;
}
if ($type eq 'N') {
push @intron_at_span, $#spans;
}
if ($type eq 'I') {
$pos++;
}
$cigar =~ s/^\d+[^\d]//;
}
return if ! @intron_at_span;
my @tags;
my $plus = 0;
my $minus = 0;
for my $intron_at_span (@intron_at_span) {
my $istart = $spans[$intron_at_span ][1] + 1;
my $iend = $spans[$intron_at_span + 1][0] - 1;
my $upstream = substr $seq_for_rname->{$rname}, $istart - 1, 2;
my $downstream = substr $seq_for_rname->{$rname}, $iend - 2, 2;
for my $sig (0 .. $#donor) {
if ($upstream eq $donor[$sig] && $downstream eq $acceptor[$sig]) {
$plus++;
}
elsif ($upstream eq $acceptor_rev[$sig] && $downstream eq $donor_rev[$sig]) {
$minus++;
}
}
}
if ($plus && !$minus) {
return "XS:A:+";
}
elsif ($minus && !$plus) {
return "XS:A:-";
}
return;
}
| itmat/rum | util/sam2xs-flag.pl | Perl | mit | 3,004 |
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use FindBin qw($Bin $Script);
use File::Basename qw(basename dirname);
use Data::Dumper;
&usage if @ARGV<1;
#open IN,"" ||die "Can't open the file:$\n";
#open OUT,"" ||die "Can't open the file:$\n";
sub usage {
my $usage = << "USAGE";
Description of this script.
Author: zhoujj2013\@gmail.com
Usage: $0 <para1> <para2>
Example:perl $0 para1 para2
USAGE
print "$usage";
exit(1);
};
###########################################
my ($coexpr_raw_f, $chromatin_f, $gene_expr_f) = @ARGV;
my %chromatin;
open IN,"$chromatin_f" || die $!;
while(<IN>){
chomp;
my @t = split /\t/;
$chromatin{$t[0]}{$t[1]} = 1;
}
close IN;
my %expr;
open IN,"$gene_expr_f" || die $!;
while(<IN>){
chomp;
my @t = split /\t/;
$expr{$t[0]} = 1;
}
close IN;
############################################
my %int;
open IN,"$coexpr_raw_f" || die $!;
while(<IN>){
chomp;
my @t = split /\t/;
next unless(exists $expr{$t[0]} && exists $expr{$t[1]});
if($expr{$t[0]} eq "miRNA" || $expr{$t[1]} eq "miRNA"){
next;
}
$int{$t[0]}{$t[1]}{'con'} = \@t;
}
close IN;
foreach my $tf (keys %chromatin){
my %tars;
foreach my $target (keys %{$chromatin{$tf}}){
$tars{$target} = 1;
if(exists $int{$tf}{$target} && !(exists $int{$tf}{$target}{'out'})){
print join "\t",@{$int{$tf}{$target}{'con'}};
print "\n";
$int{$tf}{$target}{'out'} = 1;
}elsif(exists $int{$target}{$tf}){
print join "\t",@{$int{$target}{$tf}{'con'}};
print "\n";
$int{$target}{$tf}{'out'} = 1;
}
}
foreach my $k (keys %tars){
if(exists $int{$k}){
foreach my $kk (keys %{$int{$k}}){
if(exists $tars{$kk} && !(exists $int{$k}{$kk}{'out'})){
print join "\t",@{$int{$k}{$kk}{'con'}};
print "\n";
$int{$k}{$kk}{'out'} = 1;
}
}
}
}
}
#############################################
#open IN,"$coexpr_raw_f" || die $!;
#while(<IN>){
# chomp;
# my @t = split /\t/;
# next unless(exists $expr{$t[0]} && exists $expr{$t[1]});
# my $flag = 0;
# if(exists $chromatin{$t[0]}{$t[1]} || exists $chromatin{$t[1]}{$t[0]}){
# $flag = 1;
# }else{
# foreach my $id (keys %chromatin){
# my $tar = $chromatin{$id};
# if(exists $tar->{$t[0]} && exists $tar->{$t[1]}){
# $flag = 1;
# last;
# }
# }
# }
#
# #output
# if($flag == 1){
# print join "\t",@t;
# print "\n";
# }
#}
#close IN;
| zhoujj2013/lncfuntk | bin/NetworkConstruction/CalcConfidentScore.pl | Perl | mit | 2,378 |
# -------------------------------------------------------------------------------------
# Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
# For email, run on linux (perl v5.8.5):
# perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
# -------------------------------------------------------------------------------------
use strict;
use warnings;
my $languages = ":C:CPP:JAVA:PYTHON:PERL:PHP:RUBY:CSHARP:HASKELL:CLOJURE:BASH:SCALA:ERLANG:CLISP:LUA:BRAINFUCK:JAVASCRIPT:GO:D:OCAML:R:PASCAL:SBCL:DART:GROOVY:OBJECTIVEC:";
my $num = <STDIN>; chomp $num;
for (my $i=0; $i<$num; $i++) {
my $line = <STDIN>; chomp $line;
if ($line =~ /^[0-9]{5}\s+([A-Za-z]+)\s*$/) {
my $lang = uc $1;
if ($languages =~ /:$lang:/) {
print "VALID\n";
next;
}
}
print "INVALID\n";
} | cbrghostrider/Hacking | HackerRank/Algorithms/RegEx/hackerrankLanguage.pl | Perl | mit | 910 |
package Module::Build::Config;
use strict;
use warnings;
our $VERSION = '0.4216';
$VERSION = eval $VERSION;
use Config;
sub new {
my ($pack, %args) = @_;
return bless {
stack => {},
values => $args{values} || {},
}, $pack;
}
sub get {
my ($self, $key) = @_;
return $self->{values}{$key} if ref($self) && exists $self->{values}{$key};
return $Config{$key};
}
sub set {
my ($self, $key, $val) = @_;
$self->{values}{$key} = $val;
}
sub push {
my ($self, $key, $val) = @_;
push @{$self->{stack}{$key}}, $self->{values}{$key}
if exists $self->{values}{$key};
$self->{values}{$key} = $val;
}
sub pop {
my ($self, $key) = @_;
my $val = delete $self->{values}{$key};
if ( exists $self->{stack}{$key} ) {
$self->{values}{$key} = pop @{$self->{stack}{$key}};
delete $self->{stack}{$key} unless @{$self->{stack}{$key}};
}
return $val;
}
sub values_set {
my $self = shift;
return undef unless ref($self);
return $self->{values};
}
sub all_config {
my $self = shift;
my $v = ref($self) ? $self->{values} : {};
return {%Config, %$v};
}
1;
| jkb78/extrajnm | local/lib/perl5/Module/Build/Config.pm | Perl | mit | 1,102 |
# -----------------------------------------------
# DevOps::Cli::Config
# -----------------------------------------------
# Description:
# the config command
#
#
# -----------------------------------------------
# Copyright Chris Williams 2013
# -----------------------------------------------
package DevOps::Cli::ConfigLocationOption;
use parent "Paf::Cli::Option";
use strict;
1;
sub new {
my $class=shift;
my $self=$class->SUPER::new(@_);
$self->{api} = shift;
return $self;
}
sub name {
return "location";
}
sub help {
return "restrict the following commands to the config specified at the specifed location";
}
sub synopsis {
return "restrict the following commands to the config specified at the specifed location";
}
sub run {
my $self=shift;
my $args=shift;
my $location=shift @$args || die "no location specified";
die "$location does not exist", if( ! -d $location );
$self->{config_location}=$location;
return 0;
}
sub config_location {
my $self=shift;
if( ! defined $self->{config_location} ) {
$self->{config_location}=$self->{api}->get_config()->config_dir();
}
return $self->{config_location};
}
package DevOps::Cli::Config;
use parent "DevOps::Cli::Command";
use DevOps::Cli::ConfigAdd;
use DevOps::Cli::ConfigList;
use strict;
1;
# -- initialisation
sub new {
my $class=shift;
my $self=$class->SUPER::new(@_);
$self->add_cmds(DevOps::Cli::ConfigAdd->new($self->{api}),
DevOps::Cli::ConfigList->new($self->{api}));
$self->{loc_opt}=DevOps::Cli::ConfigLocationOption->new($self->{api});
$self->add_options($self->{loc_opt});
return $self;
}
sub name {
return "config";
}
sub synopsis {
return "view or update application level configuration\n"
}
sub config {
my $self=shift;
return $self->{api}->get_config();
}
sub config_location {
my $self=shift;
if( ! defined $self->{config_location} ) {
$self->{config_location}=$self->{loc_opt}->config_location();
if( ! defined $self->{config_location} ) {
$self->{config_location}=$self->config()->config_dir();
}
}
return $self->{config_location};
}
# -- private methods -------------------------
| chrisjwilliams/devops | DevOps/Cli/Config.pm | Perl | mit | 2,273 |
package TCManager::Chart;
use Mojo::Base 'Mojolicious::Controller';
use Date::Calc qw/Time_to_Date Date_to_Time Add_Delta_Days/;
use Mojo::JSON;
#
#
#
sub cTotalsHistory {
my $s = shift;
my ($empID) = $s->param("empID") =~ /(\d+)/;
my $oldestPeriod = $s->currentPeriod() - 27;
my %totals;
for my $period ($oldestPeriod..$s->currentPeriod()) {
my $dates = $s->datesForPeriod($period);
my $time = $s->calcEmployeeTime($empID, $period);
for (qw/regular over vacation sick holiday/) {
my $w1Time = sprintf("%.2f", $time->{$_ . "W1"} / 60) + 0;
my $w2Time = sprintf("%.2f", $time->{$_ . "W2"} / 60) + 0;
my $w1Date = $dates->{startEpoch} * 1000;
my $w2Date = Date_to_Time(@{$dates->{startW2}}, 0, 0, 0) * 1000;
push(@{$totals{$_}}, [$w1Date, ($w1Time > 0) ? $w1Time : 0]);
push(@{$totals{$_}}, [$w2Date, ($w2Time > 0) ? $w2Time : 0]);
}
}
# Offset a bit so the highligh matches up with the bar widths better.
my $dates = $s->datesForPeriod($s->session("period"));
$totals{periodStart} = Date_to_Time( Add_Delta_Days(@{$dates->{start}}, -3), 0, 0, 0 ) * 1000;
$totals{periodEnd} = Date_to_Time( Add_Delta_Days(@{$dates->{start}}, 10), 0, 0, 0 ) * 1000;
$s->render(json => \%totals);
}
#
# Charts the hours breakdown for all employees.
#
sub cEmployeeList {
my $s = shift;
my $period = $s->session("period");
my $dates = $s->datesForPeriod($period);
my %totals;
for my $empID ($s->accountEmployees()) {
my $emp = $s->employeeDetails($empID);
my $time = $s->calcEmployeeTime($empID, $period);
$totals{$empID}{name} = $emp->{first_name} . " " . $emp->{last_name};
$totals{$empID}{empID} = $empID;
for (qw/regular over vacation sick holiday/) {
$totals{$empID}{$_} = sprintf("%.2f", $time->{$_} / 60) + 0;
}
}
my %chart;
for my $e (sort { $a->{name} cmp $b->{name} } values %totals) {
push(@{ $chart{names} }, $e->{name});
for (qw/regular over vacation sick holiday/) {
push(@{$chart{$_}}, {
name => $e->{name},
empID => $e->{empID},
y => $e->{$_},
});
}
}
$s->render(json => \%chart);
}
#
#
#
sub cPeriodSummary {
my $s = shift;
my ($empID) = $s->param("empID") =~ /(\d+)/;
my $time = $s->calcEmployeeTime($empID, $s->session("period"));
my %series = (
type => 'pie',
name => 'Summary'
);
my @colors = qw/428BCA D9534F 5CB85C F0AD4E 5BC0DE/;
for (qw/regular over vacation sick holiday/) {
my $color = shift(@colors);
if ($time->{$_} != 0) {
push(@{$series{data}}, {
name => ucfirst($_),
color => "#$color",
y => sprintf("%.2f", $time->{$_} / 60) + 0,
});
}
}
$s->render(json => \%series);
}
#
#
#
sub cPeriodPunches {
my $s = shift;
my ($empID) = $s->param("empID") =~ /(\d+)/;
my $dates = $s->datesForPeriod($s->session("period"));
my $punches = $s->periodPunches($empID, $s->session("period"));
my $reasons = $s->db->selectall_hashref("
SELECT
punch_id,
description AS reason,
user AS modified_by
FROM punches
LEFT JOIN reasons USING (reason_id)
LEFT JOIN accounts ON (modified_by = account_id)
WHERE
modified_on IS NOT NULL AND
time >= ? AND
time <= ? AND
employee_id = ?
", "punch_id", {},
$dates->{startSQL},
$dates->{endSQL},
$empID
);
# [dow, in time, out time]
# [1, 1375686000*1000, 1375705800*1000],
my $startTime = $dates->{startEpoch};
my %chart;
for my $dayOfPeriod (0..13) {
my $week = ($dayOfPeriod < 7) ? "week1" : "week2";
my $dayOfWeek = $dayOfPeriod % 7;
# To make sure all days show up in the chart.
push(@{$chart{$week}}, { data => [[0]] }) unless (exists($punches->{$dayOfPeriod}));
for my $punch (@{ $punches->{$dayOfPeriod} }) {
my ($h, $m, $s) = (Time_to_Date($punch->{in}))[3..5];
my $inTime = $startTime + ($h * 3600) + ($m * 60);
($h, $m, $s) = (Time_to_Date($punch->{out}))[3..5];
my $outTime = $startTime + ($h * 3600) + ($m * 60);
my $reason = "";
my $color = '#428BCA';
if ($punch->{fake} == 1) {
# Show why it was modified in the tooltip hover.
$color = '#F0AD4E';
$reason = $reasons->{ $punch->{inID} }->{reason};
}
if ($punch->{tardy}) {
$color = '#F0AD4E';
}
# Make the modified punches stand out yellow orange.
push(@{$chart{$week}}, {
color => $color,
name => 'punch',
reason => $reason,
tardy => $punch->{tardy},
inID => $punch->{inID},
data => [[$dayOfWeek, $inTime * 1000, $outTime * 1000]]
});
}
}
$s->render(json => {
data => \%chart,
minDate => $dates->{startEpoch},
});
}
1;
| ryanzachry/timeclock | manager/lib/TCManager/Chart.pm | Perl | mit | 4,761 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Services::CustomConversionGoalService::MutateCustomConversionGoalsRequest;
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},
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/V10/Services/CustomConversionGoalService/MutateCustomConversionGoalsRequest.pm | Perl | apache-2.0 | 1,243 |
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::Factory::Search;
use strict;
use base qw(EnsEMBL::Web::Factory);
use EnsEMBL::Web::Cache;
sub createObjects {
my $self = shift;
### Parse parameters to get Species names
my @species = $self->param('species') || $self->species;
#( my $SPECIES = $self->species ) =~ s/_/ /g;
if (@species) {
$self->param( 'species', @species );
}
### Set up some extra variables in the new object
my $data = $self->__data;
$data->{'__status'} = 'no_search';
$data->{'__error'} = undef;
### Create Lucene domain object
my $lucene = eval { Lucene::WebServiceWrapper->new({
'endpoint' => $self->species_defs->LUCENE_ENDPOINT,
'ext_endpoint' => $self->species_defs->LUCENE_EXT_ENDPOINT,
})};
if ($@) {
warn "!!! Failed to connect to Lucene Search engine: $@";
$data->{'__status'} = ('failure');
$data->{'__error'} = ("Search engine failure: $@");
}
## Make this into an EnsEMBL::Web::Object
my $object = $self->new_object('Search', $lucene, $data);
$object->parse;
if ( $object->__error || $object->__status eq 'failure' ) {
$self->problem( 'fatal', 'Search Engine Error', 'Search is currently unavailable' );
warn '!!! SEARCH FAILURE: ' . $object->__error;
}
$self->DataObjects($object);
}
1;
| andrewyatz/public-plugins | lucene/modules/EnsEMBL/Web/Factory/Search.pm | Perl | apache-2.0 | 2,008 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::alcatel::pss::1830::snmp::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
%{$self->{modes}} = (
'sap-qos-stats' => 'network::alcatel::pss::1830::snmp::mode::sapqosstats',
'list-sap' => 'network::alcatel::pss::1830::snmp::mode::listsap',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Alcatel 1830 Photonic Service Switch (PSS) in SNMP.
=cut
| Tpo76/centreon-plugins | network/alcatel/pss/1830/snmp/plugin.pm | Perl | apache-2.0 | 1,372 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::acmepacket::snmp::mode::listrealm;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
my $oid_apSigRealmStatsRealmName = '.1.3.6.1.4.1.9148.3.2.1.2.4.1.2';
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"filter-name:s" => { name => 'filter_name' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
}
sub manage_selection {
my ($self, %options) = @_;
my $snmp_result = $self->{snmp}->get_table(oid => $oid_apSigRealmStatsRealmName, nothing_quit => 1);
$self->{realm} = {};
foreach my $oid (keys %{$snmp_result}) {
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$snmp_result->{$oid} !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping service class '" . $snmp_result->{$oid} . "'.", debug => 1);
next;
}
$self->{realm}->{$snmp_result->{$oid}} = { name => $snmp_result->{$oid} };
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->manage_selection();
foreach my $name (sort keys %{$self->{realm}}) {
$self->{output}->output_add(long_msg => "'" . $name . "'");
}
$self->{output}->output_add(severity => 'OK',
short_msg => 'List Realm:');
$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']);
}
sub disco_show {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->manage_selection();
foreach my $name (sort keys %{$self->{realm}}) {
$self->{output}->add_disco_entry(name => $name);
}
}
1;
__END__
=head1 MODE
List realm.
=over 8
=item B<--filter-name>
Filter by realm name.
=back
=cut
| Tpo76/centreon-plugins | network/acmepacket/snmp/mode/listrealm.pm | Perl | apache-2.0 | 3,035 |
#
# Copyright 2016 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::voip::asterisk::snmp::mode::externalcalls;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use centreon::plugins::statefile;
my $oid_astBase = '.1.3.6.1.4.1.22736';
my $oid_astConfigCallsActive = $oid_astBase.'.1.2.5.0';
my $oid_astChanName = $oid_astBase.'.1.5.2.1.2'; # need an index at the end
my $oid_astChanIndex = $oid_astBase.'.1.5.2.1.1'; # need an index at the end
my $oid_astNumChannels = $oid_astBase.'.1.5.1.0';
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"warning:s" => { name => 'warning', },
"critical:s" => { name => 'critical', },
"warnontrunk:s" => { name => 'warnontrunk', },
"critontrunk:s" => { name => 'critontrunk', },
"force-oid:s" => { name => 'force_oid', },
"trunkusernamelist:s" => { name => 'trunkusernamelist', },
"filter-name" => { name => 'filter-name' },
});
$self->{statefile_value} = centreon::plugins::statefile->new(%options);
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'warnontrunk', value => $self->{option_results}->{warnontrunk})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warnontrunk} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critontrunk', value => $self->{option_results}->{critontrunk})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critontrunk} . "'.");
$self->{output}->option_exit();
}
if (!defined($self->{option_results}->{trunkusernamelist})) {
$self->{output}->add_option_msg(short_msg => "trunkusernamelist must be defined.");
$self->{output}->option_exit();
}
$self->{statefile_value}->check_options(%options);
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
my ($result, $value);
my (@callsbytrunk, @error_msg, @msg);
# explode trunk list
my @trunkusernamelist = split(',',$self->{option_results}->{trunkusernamelist});
foreach my $trunk (@trunkusernamelist)
{
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$trunk !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "Skipping trunk '" . $trunk . "': no matching filter name");
next;
}
push @callsbytrunk , { trunk => $trunk, num => 0};
}
# get chanName and sum calls for each
$result = $self->{snmp}->get_leef(oids => [ $oid_astNumChannels ], nothing_quit => 1);
my $astNumChannels = $result->{$oid_astNumChannels};
my $astConfigCallsActive = 0;
foreach my $i (1..$astNumChannels) {
$result = $self->{snmp}->get_leef(oids => [ $oid_astChanName.'.'.$i ], nothing_quit => 1);
$value = $result->{$oid_astChanName.'.'.$i};
$value =~ /^(.*)\/(.*)-.*/;
my ($protocol, $trunkname) = ($1, $2);
foreach my $val (@callsbytrunk)
{
if ( $val->{trunk} eq $trunkname )
{
$val->{num} = $val->{num}+1;
$astConfigCallsActive = $astConfigCallsActive+1;
}
}
}
# compute status based on total number of active calls
my $exit_code = $self->{perfdata}->threshold_check(value => $astConfigCallsActive,
threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
push @msg, {msg => sprintf("Current external calls: %s", $astConfigCallsActive)};
# Perfdata on all active calls
$self->{output}->perfdata_add(label => 'Total calls',
value => $astConfigCallsActive,
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'),
min => 0);
# Perfdata on number of calls for each trunk
my ($temp_exit, $exit_msg);
my (@trunk_msg, @out_msg);
my $trunk_exit_code = 'ok';
foreach $value (@callsbytrunk)
{
$temp_exit = $self->{perfdata}->threshold_check(value => $value->{num},
threshold => [ { label => 'critontrunk', exit_litteral => 'critical' }, { label => 'warnontrunk', exit_litteral => 'warning' } ]);
$self->{output}->perfdata_add(label => $value->{trunk},
value => $value->{num},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warnontrunk'),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critontrunk'),
min => 0);
$self->{output}->output_add(long_msg => sprintf("%s : %s", $value->{trunk}, $value->{num}));
$trunk_exit_code = $self->{output}->get_most_critical(status => [ $temp_exit, $trunk_exit_code ]);
# create msg for most critical data ....
if ($self->{output}->is_status(value => $temp_exit, compare => $trunk_exit_code, litteral => 1))
{
push @trunk_msg, {msg => sprintf("'%s': %s", $value->{trunk}, $value->{num})};
}
}
if (!$self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1) && !$self->{output}->is_status(value => $trunk_exit_code, compare => 'ok', litteral => 1))
{
unshift @trunk_msg, @msg;
$exit_code = $self->{output}->get_most_critical(status => [ $exit_code, $trunk_exit_code ]);
}
if (!$self->{output}->is_status(value => $trunk_exit_code, compare => 'ok', litteral => 1))
{
@out_msg=@trunk_msg;
$exit_code = $trunk_exit_code ;
}
else
{
push @out_msg, @msg;
}
$exit_msg = '';
my $separator = '';
foreach my $out (@out_msg)
{
$exit_msg .= $separator.$out->{msg};
$separator = ', ';
}
$self->{output}->output_add(severity => $exit_code,
short_msg => $exit_msg
);
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check number of external calls (total and by trunk)
=over 8
=item B<--warning>
Threshold warning for total number of external calls.
=item B<--critical>
Threshold critical for total number of external calls.
=item B<--warnontrunk>
Threshold warning for trunks.
=item B<--critontrunk>
Threshold critical for trunks.
=item B<--force-oid>
Can choose your oid (numeric format only).
=item B<--trunkusernamelist>
List of outgoing trunks' username.
=item B<--filter-name>
Filter on trunk's username (regexp can be used).
=back
=cut | bcournaud/centreon-plugins | apps/voip/asterisk/snmp/mode/externalcalls.pm | Perl | apache-2.0 | 8,821 |
#!/usr/bin/env perl
# Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on
# an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
use strict;
use warnings;
use HTTP::Tiny;
use IO::Socket::SSL 1.52;
use utf8;
my $Github_Key = load_github_key();
my $Base_URL = "https://${Github_Key}api.github.com/repos/";
my $User_Repo = 'elastic/elasticsearch/';
my $Issue_URL = "http://github.com/${User_Repo}issues/";
my @Groups = (
">breaking", ">breaking-java", ">deprecation", ">feature",
">enhancement", ">bug", ">regression", ">upgrade"
);
my %Ignore = map { $_ => 1 }
( ">non-issue", ">refactoring", ">docs", ">test", ":Core/Build" );
my %Group_Labels = (
'>breaking' => 'Breaking changes',
'>breaking-java' => 'Breaking Java changes',
'>deprecation' => 'Deprecations',
'>feature' => 'New features',
'>enhancement' => 'Enhancements',
'>bug' => 'Bug fixes',
'>regression' => 'Regressions',
'>upgrade' => 'Upgrades',
'other' => 'NOT CLASSIFIED',
);
use JSON();
use Encode qw(encode_utf8);
my $json = JSON->new->utf8(1);
my %All_Labels = fetch_labels();
my $version = shift @ARGV
or dump_labels();
dump_labels("Unknown version '$version'")
unless $All_Labels{$version};
my $issues = fetch_issues($version);
dump_issues( $version, $issues );
#===================================
sub dump_issues {
#===================================
my $version = shift;
my $issues = shift;
$version =~ s/v//;
my $branch = $version;
$branch =~ s/\.\d+$//;
my ( $day, $month, $year ) = (gmtime)[ 3 .. 5 ];
$month++;
$year += 1900;
print <<"ASCIIDOC";
:issue: https://github.com/${User_Repo}issues/
:pull: https://github.com/${User_Repo}pull/
[[release-notes-$version]]
== $version Release Notes
coming[$version]
Also see <<breaking-changes-$branch>>.
ASCIIDOC
for my $group ( @Groups, 'other' ) {
my $group_issues = $issues->{$group} or next;
my $group_id = $group;
$group_id =~ s/^>//;
print "[[$group_id-$version]]\n"
. "[float]\n"
. "=== $Group_Labels{$group}\n\n";
for my $header ( sort keys %$group_issues ) {
my $header_issues = $group_issues->{$header};
print( $header || 'HEADER MISSING', "::\n" );
for my $issue (@$header_issues) {
my $title = $issue->{title};
if ( $issue->{state} eq 'open' ) {
$title .= " [OPEN]";
}
unless ( $issue->{pull_request} ) {
$title .= " [ISSUE]";
}
my $number = $issue->{number};
print encode_utf8("* $title {pull}${number}[#${number}]");
if ( my $related = $issue->{related_issues} ) {
my %uniq = map { $_ => 1 } @$related;
print keys %uniq > 1
? " (issues: "
: " (issue: ";
print join ", ", map {"{issue}${_}[#${_}]"}
sort keys %uniq;
print ")";
}
print "\n";
}
print "\n";
}
print "\n\n";
}
}
#===================================
sub fetch_issues {
#===================================
my $version = shift;
my @issues;
my %seen;
for my $state ( 'open', 'closed' ) {
my $page = 1;
while (1) {
my $tranche
= fetch( $User_Repo
. 'issues?labels='
. $version
. '&pagesize=100&state='
. $state
. '&page='
. $page )
or die "Couldn't fetch issues for version '$version'";
push @issues, @$tranche;
for my $issue (@$tranche) {
next unless $issue->{pull_request};
for ( $issue->{body} =~ m{(?:#|${User_Repo}issues/)(\d+)}g ) {
$seen{$_}++;
push @{ $issue->{related_issues} }, $_;
}
}
$page++;
last unless @$tranche;
}
}
my %group;
ISSUE:
for my $issue (@issues) {
next if $seen{ $issue->{number} } && !$issue->{pull_request};
for ( @{ $issue->{labels} } ) {
next ISSUE if $Ignore{ $_->{name} };
}
# uncomment for including/excluding PRs already issued in other versions
# next if grep {$_->{name}=~/^v2/} @{$issue->{labels}};
my %labels = map { $_->{name} => 1 } @{ $issue->{labels} };
my ($header) = map { m{:[^/]+/(.+)} && $1 }
grep {/^:/} sort keys %labels;
$header ||= 'NOT CLASSIFIED';
for (@Groups) {
if ( $labels{$_} ) {
push @{ $group{$_}{$header} }, $issue;
next ISSUE;
}
}
push @{ $group{other}{$header} }, $issue;
}
return \%group;
}
#===================================
sub fetch_labels {
#===================================
my %all;
my $page = 1;
while (1) {
my $labels = fetch( $User_Repo . 'labels?page=' . $page++ )
or die "Couldn't retrieve version labels";
last unless @$labels;
for (@$labels) {
my $name = $_->{name};
next unless $name =~ /^v/;
$all{$name} = 1;
}
}
return %all;
}
#===================================
sub fetch {
#===================================
my $url = $Base_URL . shift();
my $response = HTTP::Tiny->new->get($url);
die "$response->{status} $response->{reason}\n"
unless $response->{success};
# print $response->{content};
return $json->decode( $response->{content} );
}
#===================================
sub load_github_key {
#===================================
my ($file) = glob("~/.github_auth");
unless ( -e $file ) {
warn "File ~/.github_auth doesn't exist - using anonymous API. "
. "Generate a Personal Access Token at https://github.com/settings/applications\n";
return '';
}
open my $fh, $file or die "Couldn't open $file: $!";
my ($key) = <$fh> || die "Couldn't read $file: $!";
$key =~ s/^\s+//;
$key =~ s/\s+$//;
die "Invalid GitHub key: $key"
unless $key =~ /^[0-9a-f]{40}$/;
return "$key:x-oauth-basic@";
}
#===================================
sub dump_labels {
#===================================
my $error = shift || '';
if ($error) {
$error = "\nERROR: $error\n";
}
my $labels = join( "\n - ", '', ( sort keys %All_Labels ) );
die <<USAGE
$error
USAGE: $0 version > outfile
Known versions:$labels
USAGE
}
| qwerty4030/elasticsearch | dev-tools/es_release_notes.pl | Perl | apache-2.0 | 7,516 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Mapper::IndelCoordinate
=head1 SYNOPSIS
=head1 DESCRIPTION
Representation of a indel in a sequence; returned from Mapper.pm when
the target region is in a deletion.
=head1 METHODS
=cut
package Bio::EnsEMBL::Mapper::IndelCoordinate;
use Bio::EnsEMBL::Mapper::Gap;
use Bio::EnsEMBL::Mapper::Coordinate;
use vars qw(@ISA);
use strict;
@ISA = qw(Bio::EnsEMBL::Mapper::Coordinate Bio::EnsEMBL::Mapper::Gap);
=head2 new
Arg [1] : Bio::EnsEMBL::Mapper::Gap $gap
Arg [2] : Bio::EnsEMBL::Mapper::Coordinate $coordinate
Example : $indelCoord = Bio::EnsEMBL::Mapper::IndelCoordinate($gap, $coordinate);
Description: Creates a new IndelCoordinate object.
Returntype : Bio::EnsEMBL::Mapper::IndelCoordinate
Exceptions : none
Caller : Bio::EnsEMBL::Mapper
=cut
sub new {
my ( $proto, $gap, $coordinate ) = @_;
my $class = ref($proto) || $proto;
return
bless( { 'start' => $coordinate->start(),
'end' => $coordinate->end(),
'strand' => $coordinate->strand(),
'id' => $coordinate->id(),
'coord_system' => $coordinate->coord_system(),
'gap_start' => $gap->start(),
'gap_end' => $gap->end()
},
$class );
}
=head2 gap_start
Arg[1] : (optional) int $gap_start
Example : $gap_start = $ic->gap_start()
Description : Getter/Setter for the start of the Gap region
ReturnType : int
Exceptions : none
Caller : general
=cut
sub gap_start {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'gap_start'} = $value;
}
return $self->{'gap_start'};
}
=head2 gap_end
Arg[1] : (optional) int $gap_end
Example : $gap_end = $ic->gap_end()
Description : Getter/Setter for the end of the Gap region
ReturnType : int
Exceptions : none
Caller : general
=cut
sub gap_end {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'gap_end'} = $value;
}
return $self->{'gap_end'};
}
=head2 gap_length
Args : None
Example : $gap_length = $ic->gap_length()
Description : Getter for the length of the Gap region
ReturnType : int
Exceptions : none
Caller : general
=cut
sub gap_length {
my ($self) = @_;
return $self->{'gap_end'} - $self->{'gap_start'} + 1;
}
1;
| danstaines/ensembl | modules/Bio/EnsEMBL/Mapper/IndelCoordinate.pm | Perl | apache-2.0 | 3,340 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V9::Services::CampaignDraftService::ListCampaignDraftAsyncErrorsRequest;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
pageSize => $args->{pageSize},
pageToken => $args->{pageToken},
resourceName => $args->{resourceName}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Services/CampaignDraftService/ListCampaignDraftAsyncErrorsRequest.pm | Perl | apache-2.0 | 1,155 |
=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::TextSequence::Markup::VariationConservation;
use strict;
use warnings;
use parent qw(EnsEMBL::Web::TextSequence::Markup::Conservation);
sub replaces { return 'EnsEMBL::Web::TextSequence::Markup::Conservation'; }
sub markup {
my ($self, $sequence, $markup, $config) = @_;
my $difference = 0;
for my $i (0..scalar(@$sequence)-1) {
# XXX temporary hack for Compara_Alignments
next unless $sequence->[$i]->is_root;
next if $config->{'slices'}->[$i] and $config->{'slices'}->[$i]->{'no_alignment'};
my $seq = $sequence->[$i]->legacy;
for (0..$config->{'length'}-1) {
next if $seq->[$_]->{'match'};
$seq->[$_]->{'class'} .= 'dif ';
$difference = 1;
}
}
$config->{'key'}->{'other'}{'difference'} = 1 if $difference;
}
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Web/TextSequence/Markup/VariationConservation.pm | Perl | apache-2.0 | 1,528 |
# 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::UserDataService::UploadUserDataResponse;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
receivedOperationsCount => $args->{receivedOperationsCount},
uploadDateTime => $args->{uploadDateTime}};
# 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/UserDataService/UploadUserDataResponse.pm | Perl | apache-2.0 | 1,136 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package centreon::plugins::backend::http::curlconstants;
use strict;
use warnings;
use Net::Curl::Easy qw(:constants);
sub get_constant_value {
my (%options) = @_;
return eval $options{name};
}
1;
| Tpo76/centreon-plugins | centreon/plugins/backend/http/curlconstants.pm | Perl | apache-2.0 | 969 |
package Google::Ads::AdWords::v201402::CampaignFeedService::mutateResponse;
use strict;
use warnings;
{ # BLOCK to scope variables
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' }
__PACKAGE__->__set_name('mutateResponse');
__PACKAGE__->__set_nillable();
__PACKAGE__->__set_minOccurs();
__PACKAGE__->__set_maxOccurs();
__PACKAGE__->__set_ref();
use base qw(
SOAP::WSDL::XSD::Typelib::Element
Google::Ads::SOAP::Typelib::ComplexType
);
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %rval_of :ATTR(:get<rval>);
__PACKAGE__->_factory(
[ qw( rval
) ],
{
'rval' => \%rval_of,
},
{
'rval' => 'Google::Ads::AdWords::v201402::CampaignFeedReturnValue',
},
{
'rval' => 'rval',
}
);
} # end BLOCK
} # end of BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201402::CampaignFeedService::mutateResponse
=head1 DESCRIPTION
Perl data type class for the XML Schema defined element
mutateResponse from the namespace https://adwords.google.com/api/adwords/cm/v201402.
=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::v201402::CampaignFeedService::mutateResponse->new($data);
Constructor. The following data structure may be passed to new():
{
rval => $a_reference_to, # see Google::Ads::AdWords::v201402::CampaignFeedReturnValue
},
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201402/CampaignFeedService/mutateResponse.pm | Perl | apache-2.0 | 1,807 |
#! /usr/bin/perl
# Author: BaconKwan
# Email: pkguan@genedenovo.com
# Version: 1.0
# Create date:
# Usage:
use utf8;
use strict;
use warnings;
my ($base_count, $read_count, $q20_count, $gc_count, $N_count) = (0, 0, 0, 0);
open IN, "gzip -cd $ARGV[0] |" || die $!;
while(<IN>){
my $base = <IN>;
<IN>;
my $quality = <IN>;
chomp $base;
chomp $quality;
my @base = split "", $base;
my @quality = split "", $quality;
$read_count++;
$base_count += @base;
$gc_count += $base =~ tr/GCgc/GCgc/;
$N_count += $base =~ tr/Nn/Nn/;
for(my $i = 0; $i < @quality; $i++){
my $q = ord($quality[$i]) - 64;
$q20_count++ if($q >= 20);
}
}
close IN;
$ARGV[0] =~ s/\.fq\.gz//;
open STAT, "> $ARGV[0].txt" || die $!;
print STAT "total reads:\t$read_count\n";
print STAT "total reads nt:\t$base_count\n";
print STAT "Q20 number:\t$q20_count\n";
$q20_count = sprintf("%.2f%%", 100 * $q20_count / $base_count);
print STAT "Q20 percentage\t$q20_count\n";
print STAT "GC number\t$gc_count\n";
$gc_count = sprintf("%.2f%%", 100 * $gc_count / $base_count);
print STAT "GC percentage\t$gc_count\n";
print STAT "N number\t$N_count\n";
$N_count = sprintf("%.2f%%", 100 * $N_count / $base_count);
print STAT "N percentage\t$N_count\n";
close STAT;
| BaconKwan/Perl_programme | utility/stat_gz.pl | Perl | apache-2.0 | 1,248 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::ArchiveStableIdAdaptor
=head1 SYNOPSIS
my $registry = "Bio::EnsEMBL::Registry";
my $archiveStableIdAdaptor =
$registry->get_adaptor( 'Human', 'Core', 'ArchiveStableId' );
my $stable_id = 'ENSG00000068990';
my $arch_id = $archiveStableIdAdaptor->fetch_by_stable_id($stable_id);
print("Latest incarnation of this stable ID:\n");
printf( " Stable ID: %s.%d\n",
$arch_id->stable_id(), $arch_id->version() );
print(" Release: "
. $arch_id->release() . " ("
. $arch_id->assembly() . ", "
. $arch_id->db_name()
. ")\n" );
print "\nStable ID history:\n\n";
my $history =
$archiveStableIdAdaptor->fetch_history_tree_by_stable_id(
$stable_id);
foreach my $a ( @{ $history->get_all_ArchiveStableIds } ) {
printf( " Stable ID: %s.%d\n", $a->stable_id(), $a->version() );
print(" Release: "
. $a->release() . " ("
. $a->assembly() . ", "
. $a->db_name()
. ")\n\n" );
}
=head1 DESCRIPTION
ArchiveStableIdAdaptor does all SQL to create ArchiveStableIds and works
of
stable_id_event
mapping_session
peptite_archive
gene_archive
tables inside the core database.
This whole module has a status of At Risk as it is under development.
=head1 METHODS
fetch_by_stable_id
fetch_by_stable_id_version
fetch_by_stable_id_dbname
fetch_all_by_archive_id
fetch_predecessors_by_archive_id
fetch_successors_by_archive_id
fetch_history_tree_by_stable_id
add_all_current_to_history
list_dbnames
previous_dbname
next_dbname
get_peptide
get_current_release
get_current_assembly
=head1 RELATED MODULES
Bio::EnsEMBL::ArchiveStableId
Bio::EnsEMBL::StableIdEvent
Bio::EnsEMBL::StableIdHistoryTree
=head1 METHODS
=cut
package Bio::EnsEMBL::DBSQL::ArchiveStableIdAdaptor;
use strict;
use warnings;
no warnings qw(uninitialized);
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
our @ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);
use Bio::EnsEMBL::ArchiveStableId;
use Bio::EnsEMBL::StableIdEvent;
use Bio::EnsEMBL::StableIdHistoryTree;
use Bio::EnsEMBL::Utils::Exception qw(warning throw);
use constant MAX_ROWS => 30;
use constant NUM_HIGH_SCORERS => 20;
=head2 fetch_by_stable_id
Arg [1] : string $stable_id
Arg [2] : (optional) string $type
Example : none
Description : Retrives an ArchiveStableId that is the latest incarnation of
given stable_id. If the lookup fails, attempts to check for a
version id delimited by a period (.) and lookup again using the
version id.
Returntype : Bio::EnsEMBL::ArchiveStableId or undef if not in database
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub fetch_by_stable_id {
my $self = shift;
my $stable_id = shift;
my $arch_id = $self->_fetch_by_stable_id($stable_id, @_);
# If we didn't get anything back, desperately try to see if there's
# a version number in the stable_id
if(!defined($arch_id) && (my $vindex = rindex($stable_id, '.'))) {
$arch_id = $self->fetch_by_stable_id_version(substr($stable_id,0,$vindex),
substr($stable_id,$vindex+1),
@_);
}
return $arch_id;
}
=head2 _fetch_by_stable_id
Arg [1] : string $stable_id
Arg [2] : (optional) string $type
Example : none
Description : Retrives an ArchiveStableId that is the latest incarnation of
given stable_id. Helper function to fetch_by_stable_id, should
not be directly called.
Returntype : Bio::EnsEMBL::ArchiveStableId or undef if not in database
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub _fetch_by_stable_id {
my $self = shift;
my $stable_id = shift;
my $arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $stable_id,
-adaptor => $self
);
@_ ? $arch_id->type(shift) : $self->_resolve_type($arch_id);
if ($self->lookup_current($arch_id)) {
# stable ID is in current release
$arch_id->version($arch_id->current_version);
$arch_id->db_name($self->dbc->dbname);
$arch_id->release($self->get_current_release);
$arch_id->assembly($self->get_current_assembly);
} else {
# look for latest version of this stable id
my $extra_sql = defined($arch_id->{'type'}) ?
" AND sie.type = '@{[lc($arch_id->{'type'})]}'" : '';
my $r = $self->_fetch_archive_id($stable_id, $extra_sql, $extra_sql);
if ($r->{'new_stable_id'} and $r->{'new_stable_id'} eq $stable_id) {
# latest event is a self event, use new_* data
$arch_id->version($r->{'new_version'});
$arch_id->release($r->{'new_release'});
$arch_id->assembly($r->{'new_assembly'});
$arch_id->db_name($r->{'new_db_name'});
} else {
# latest event is a deletion event (or mapping to other ID; this clause
# is only used to cope with buggy data where deletion events are
# missing), use old_* data
$arch_id->version($r->{'old_version'});
$arch_id->release($r->{'old_release'});
$arch_id->assembly($r->{'old_assembly'});
$arch_id->db_name($r->{'old_db_name'});
}
$arch_id->type(ucfirst(lc($r->{'type'})));
}
if (! defined $arch_id->db_name) {
# couldn't find stable ID in archive or current db
return undef;
}
$arch_id->is_latest(1);
return $arch_id;
}
=head2 fetch_by_stable_id_version
Arg [1] : string $stable_id
Arg [2] : int $version
Example : none
Description : Retrieve an ArchiveStableId with given version and stable ID.
Returntype : Bio::EnsEMBL::ArchiveStableId
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub fetch_by_stable_id_version {
my $self = shift;
my $stable_id = shift;
my $version = shift;
my $arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $stable_id,
-version => $version,
-adaptor => $self
);
@_ ? $arch_id->type(shift) : $self->_resolve_type($arch_id);
if ($self->lookup_current($arch_id) && $arch_id->is_current) {
# this version is the current one
$arch_id->db_name($self->dbc->dbname);
$arch_id->release($self->get_current_release);
$arch_id->assembly($self->get_current_assembly);
} else {
# find latest release this stable ID version is found in archive
my $extra_sql1 = qq(AND sie.old_version = "$version");
my $extra_sql2 = qq(AND sie.new_version = "$version");
my $r = $self->_fetch_archive_id($stable_id, $extra_sql1, $extra_sql2);
if ($r->{'new_stable_id'} and $r->{'new_stable_id'} eq $stable_id
and $r->{'new_version'} == $version) {
# latest event is a self event, use new_* data
$arch_id->release($r->{'new_release'});
$arch_id->assembly($r->{'new_assembly'});
$arch_id->db_name($r->{'new_db_name'});
} else {
# latest event is a deletion event (or mapping to other ID; this clause
# is only used to cope with buggy data where deletion events are
# missing), use old_* data
$arch_id->release($r->{'old_release'});
$arch_id->assembly($r->{'old_assembly'});
$arch_id->db_name($r->{'old_db_name'});
}
$arch_id->type(ucfirst(lc($r->{'type'})));
}
if (! defined $arch_id->db_name) {
# couldn't find stable ID version in archive or current release
return undef;
}
return $arch_id;
}
=head2 fetch_by_stable_id_dbname
Arg [1] : string $stable_id
Arg [2] : string $db_name
Example : none
Description : Create an ArchiveStableId from given arguments.
Returntype : Bio::EnsEMBL::ArchiveStableId or undef if not in database
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub fetch_by_stable_id_dbname {
my $self = shift;
my $stable_id = shift;
my $db_name = shift;
my $arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $stable_id,
-db_name => $db_name,
-adaptor => $self
);
@_ ? $arch_id->type(shift) : $self->_resolve_type($arch_id);
if ($self->lookup_current($arch_id) and $db_name eq $self->dbc->dbname) {
# this version is the current one
$arch_id->version($arch_id->current_version);
$arch_id->release($self->get_current_release);
$arch_id->assembly($self->get_current_assembly);
} else {
# find version for this dbname in the stable ID archive
my $extra_sql = defined($arch_id->{'type'}) ?
" AND sie.type = '@{[lc($arch_id->{'type'})]}'" : '';
my $extra_sql1 = $extra_sql . qq( AND ms.old_db_name = "$db_name");
my $extra_sql2 = $extra_sql . qq( AND ms.new_db_name = "$db_name");
my $r = $self->_fetch_archive_id($stable_id, $extra_sql1, $extra_sql2);
if ($r->{'new_stable_id'} and $r->{'new_stable_id'} eq $stable_id
and $r->{'new_db_name'} eq $db_name) {
# latest event is a self event, use new_* data
$arch_id->release($r->{'new_release'});
$arch_id->assembly($r->{'new_assembly'});
$arch_id->version($r->{'new_version'});
} else {
# latest event is a deletion event (or mapping to other ID; this clause
# is only used to cope with buggy data where deletion events are
# missing), use old_* data
$arch_id->release($r->{'old_release'});
$arch_id->assembly($r->{'old_assembly'});
$arch_id->version($r->{'old_version'});
}
$arch_id->type(ucfirst(lc($r->{'type'})));
}
if (! defined $arch_id->version ) {
# couldn't find stable ID version in archive or current release
return undef;
}
return $arch_id;
}
#
# Helper method to do fetch ArchiveStableId from db.
# Used by fetch_by_stable_id(), fetch_by_stable_id_version() and
# fetch_by_stable_id_dbname().
# Returns hashref as returned by DBI::sth::fetchrow_hashref
#
sub _fetch_archive_id {
my $self = shift;
my $stable_id = shift;
my $extra_sql1 = shift;
my $extra_sql2 = shift;
# using a UNION is much faster in this query than somthing like
# "... AND (sie.old_stable_id = ? OR sie.new_stable_id = ?)"
my $sql = qq(
SELECT * FROM stable_id_event sie, mapping_session ms
WHERE sie.mapping_session_id = ms.mapping_session_id
AND sie.old_stable_id = ?
$extra_sql1
UNION
SELECT * FROM stable_id_event sie, mapping_session ms
WHERE sie.mapping_session_id = ms.mapping_session_id
AND sie.new_stable_id = ?
$extra_sql2
ORDER BY created DESC, score DESC
LIMIT 1
);
my $sth = $self->prepare($sql);
$sth->execute($stable_id,$stable_id);
my $r = $sth->fetchrow_hashref;
$sth->finish;
return $r;
}
=head2 fetch_all_by_archive_id
Arg [1] : Bio::EnsEMBL::ArchiveStableId $archive_id
Arg [2] : String $return_type - type of ArchiveStableId to fetch
Example : my $arch_id = $arch_adaptor->fetch_by_stable_id('ENSG0001');
my @archived_transcripts =
$arch_adaptor->fetch_all_by_archive_id($arch_id, 'Transcript');
Description : Given a ArchiveStableId it retrieves associated ArchiveStableIds
of specified type (e.g. retrieve transcripts for genes or vice
versa).
See also fetch_associated_archived() for a different approach to
retrieve this data.
Returntype : listref Bio::EnsEMBL::ArchiveStableId
Exceptions : none
Caller : Bio::EnsEMBL::ArchiveStableId->get_all_gene_archive_ids,
get_all_transcript_archive_ids, get_all_translation_archive_ids
Status : At Risk
: under development
=cut
sub fetch_all_by_archive_id {
my $self = shift;
my $archive_id = shift;
my $return_type = shift;
my @result = ();
my $lc_self_type = lc($archive_id->type);
my $lc_return_type = lc($return_type);
my $sql = qq(
SELECT
ga.${lc_return_type}_stable_id,
ga.${lc_return_type}_version,
m.old_db_name,
m.old_release,
m.old_assembly
FROM gene_archive ga, mapping_session m
WHERE ga.${lc_self_type}_stable_id = ?
AND ga.${lc_self_type}_version = ?
AND ga.mapping_session_id = m.mapping_session_id
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $archive_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2, $archive_id->version, SQL_SMALLINT);
$sth->execute;
my ($stable_id, $version, $db_name, $release, $assembly);
$sth->bind_columns(\$stable_id, \$version, \$db_name, \$release, \$assembly);
while ($sth->fetch) {
my $new_arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $stable_id,
-version => $version,
-db_name => $db_name,
-release => $release,
-assembly => $assembly,
-type => $return_type,
-adaptor => $self
);
push( @result, $new_arch_id );
}
$sth->finish();
return \@result;
}
=head2 fetch_associated_archived
Arg[1] : Bio::EnsEMBL::ArchiveStableId $arch_id -
the ArchiveStableId to fetch associated archived IDs for
Example : my ($arch_gene, $arch_tr, $arch_tl, $pep_seq) =
@{ $archive_adaptor->fetch_associated_archived($arch_id) };
Description : Fetches associated archived stable IDs from the db for a given
ArchiveStableId (version is taken into account).
Return type : Listref of
ArchiveStableId archived gene
ArchiveStableId archived transcript
(optional) ArchiveStableId archived translation
(optional) peptide sequence
Exceptions : thrown on missing or wrong argument
thrown if ArchiveStableID has no type
Caller : Bio::EnsEMBL::ArchiveStableId->get_all_associated_archived()
Status : At Risk
: under development
=cut
sub fetch_associated_archived {
my $self = shift;
my $arch_id = shift;
throw("Need a Bio::EnsEMBL::ArchiveStableId") unless ($arch_id
and ref($arch_id) and $arch_id->isa('Bio::EnsEMBL::ArchiveStableId'));
my $type = $arch_id->type();
if ( !defined($type) ) {
throw("Can't deduce ArchiveStableId type.");
}
$type = lc($type);
my $sql = qq(
SELECT ga.gene_stable_id,
ga.gene_version,
ga.transcript_stable_id,
ga.transcript_version,
ga.translation_stable_id,
ga.translation_version,
pa.peptide_seq,
ms.old_release,
ms.old_assembly,
ms.old_db_name
FROM (mapping_session ms, gene_archive ga)
LEFT JOIN peptide_archive pa
ON ga.peptide_archive_id = pa.peptide_archive_id
WHERE ga.mapping_session_id = ms.mapping_session_id
AND ga.${type}_stable_id = ?
AND ga.${type}_version = ?
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2, $arch_id->version, SQL_SMALLINT);
$sth->execute;
my @result = ();
while (my $r = $sth->fetchrow_hashref) {
my @row = ();
# create ArchiveStableIds genes, transcripts and translations
push @row, Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $r->{'gene_stable_id'},
-version => $r->{'gene_version'},
-db_name => $r->{'old_db_name'},
-release => $r->{'old_release'},
-assembly => $r->{'old_assembly'},
-type => 'Gene',
-adaptor => $self
);
push @row, Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $r->{'transcript_stable_id'},
-version => $r->{'transcript_version'},
-db_name => $r->{'old_db_name'},
-release => $r->{'old_release'},
-assembly => $r->{'old_assembly'},
-type => 'Transcript',
-adaptor => $self
);
if ($r->{'translation_stable_id'}) {
push @row, Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $r->{'translation_stable_id'},
-version => $r->{'translation_version'},
-db_name => $r->{'old_db_name'},
-release => $r->{'old_release'},
-assembly => $r->{'old_assembly'},
-type => 'Translation',
-adaptor => $self
);
# push peptide sequence onto result list
push @row, $r->{'peptide_seq'};
}
push @result, \@row;
}
return \@result;
}
=head2 fetch_predecessors_by_archive_id
Arg [1] : Bio::EnsEMBL::ArchiveStableId
Example : none
Description : Retrieve a list of ArchiveStableIds that were mapped to the
given one. This method goes back only one level, to retrieve
a full predecessor history use fetch_predecessor_history, or
ideally fetch_history_tree_by_stable_id for the complete
history network.
Returntype : listref Bio::EnsEMBL::ArchiveStableId
Exceptions : none
Caller : Bio::EnsEMBL::ArchiveStableId->get_all_predecessors
Status : At Risk
: under development
=cut
sub fetch_predecessors_by_archive_id {
my $self = shift;
my $arch_id = shift;
my @result;
if( ! ( defined $arch_id->stable_id() &&
defined $arch_id->db_name() )) {
throw( "Need db_name for predecessor retrieval" );
}
my $sql = qq(
SELECT
sie.old_stable_id,
sie.old_version,
sie.type,
m.old_db_name,
m.old_release,
m.old_assembly
FROM mapping_session m, stable_id_event sie
WHERE sie.mapping_session_id = m.mapping_session_id
AND sie.new_stable_id = ?
AND m.new_db_name = ?
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2, $arch_id->db_name, SQL_VARCHAR);
$sth->execute();
my ($old_stable_id, $old_version, $type, $old_db_name, $old_release, $old_assembly);
$sth->bind_columns(\$old_stable_id, \$old_version, \$type, \$old_db_name, \$old_release, \$old_assembly);
while ($sth->fetch) {
if (defined $old_stable_id) {
my $old_arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $old_stable_id,
-version => $old_version,
-db_name => $old_db_name,
-release => $old_release,
-assembly => $old_assembly,
-type => $type,
-adaptor => $self
);
push( @result, $old_arch_id );
}
}
$sth->finish();
# if you didn't find any predecessors, there might be a gap in the
# mapping_session history (i.e. databases in mapping_session don't chain). To
# bridge the gap, look in the previous mapping_session for identical
# stable_id.version
unless (@result) {
$sql = qq(
SELECT
sie.new_stable_id,
sie.new_version,
sie.type,
m.new_db_name,
m.new_release,
m.new_assembly
FROM mapping_session m, stable_id_event sie
WHERE sie.mapping_session_id = m.mapping_session_id
AND sie.new_stable_id = ?
AND m.new_db_name = ?
);
$sth = $self->prepare($sql);
my $curr_dbname = $arch_id->db_name;
PREV:
while (my $prev_dbname = $self->previous_dbname($curr_dbname)) {
$sth->bind_param(1,$arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2,$prev_dbname, SQL_VARCHAR);
$sth->execute();
$sth->bind_columns(\$old_stable_id, \$old_version, \$type, \$old_db_name, \$old_release, \$old_assembly);
while( $sth->fetch() ) {
if (defined $old_stable_id) {
my $old_arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $old_stable_id,
-version => $old_version,
-db_name => $old_db_name,
-release => $old_release,
-assembly => $old_assembly,
-type => $type,
-adaptor => $self
);
push( @result, $old_arch_id );
last PREV;
}
}
$curr_dbname = $prev_dbname;
}
$sth->finish();
}
return \@result;
}
=head2 fetch_successors_by_archive_id
Arg [1] : Bio::EnsEMBL::ArchiveStableId
Example : none
Description : Retrieve a list of ArchiveStableIds that the given one was
mapped to. This method goes forward only one level, to retrieve
a full successor history use fetch_successor_history, or
ideally fetch_history_tree_by_stable_id for the complete
history network.
Returntype : listref Bio::EnsEMBL::ArchiveStableId
Exceptions : none
Caller : Bio::EnsEMBL::ArchiveStableId->get_all_successors
Status : At Risk
: under development
=cut
sub fetch_successors_by_archive_id {
my $self = shift;
my $arch_id = shift;
my @result;
if( ! ( defined $arch_id->stable_id() &&
defined $arch_id->db_name() )) {
throw( "Need db_name for successor retrieval" );
}
my $sql = qq(
SELECT
sie.new_stable_id,
sie.new_version,
sie.type,
m.new_db_name,
m.new_release,
m.new_assembly
FROM mapping_session m, stable_id_event sie
WHERE sie.mapping_session_id = m.mapping_session_id
AND sie.old_stable_id = ?
AND m.old_db_name = ?
);
my $sth = $self->prepare( $sql );
$sth->bind_param(1,$arch_id->stable_id,SQL_VARCHAR);
$sth->bind_param(2,$arch_id->db_name,SQL_VARCHAR);
$sth->execute();
my ($new_stable_id, $new_version, $type, $new_db_name, $new_release, $new_assembly);
$sth->bind_columns(\$new_stable_id, \$new_version, \$type, \$new_db_name, \$new_release, \$new_assembly);
while( $sth->fetch() ) {
if( defined $new_stable_id ) {
my $new_arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $new_stable_id,
-version => $new_version,
-db_name => $new_db_name,
-release => $new_release,
-assembly => $new_assembly,
-type => $type,
-adaptor => $self
);
push( @result, $new_arch_id );
}
}
$sth->finish();
# if you didn't find any successors, there might be a gap in the
# mapping_session history (i.e. databases in mapping_session don't chain). To
# bridge the gap, look in the next mapping_session for identical
# stable_id.version
unless (@result) {
$sql = qq(
SELECT
sie.old_stable_id,
sie.old_version,
sie.type,
m.old_db_name,
m.old_release,
m.old_assembly
FROM mapping_session m, stable_id_event sie
WHERE sie.mapping_session_id = m.mapping_session_id
AND sie.old_stable_id = ?
AND m.old_db_name = ?
);
$sth = $self->prepare($sql);
my $curr_dbname = $arch_id->db_name;
NEXTDB:
while (my $next_dbname = $self->next_dbname($curr_dbname)) {
$sth->bind_param(1, $arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2, $next_dbname, SQL_VARCHAR);
$sth->execute();
$sth->bind_columns(\$new_stable_id, \$new_version, \$type, \$new_db_name, \$new_release, \$new_assembly);
while( $sth->fetch() ) {
if (defined $new_stable_id) {
my $new_arch_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $new_stable_id,
-version => $new_version,
-db_name => $new_db_name,
-release => $new_release,
-assembly => $new_assembly,
-type => $type,
-adaptor => $self
);
push( @result, $new_arch_id );
last NEXTDB;
}
}
$curr_dbname = $next_dbname;
}
$sth->finish();
}
return \@result;
}
=head2 fetch_history_tree_by_stable_id
Arg [1] : String $stable_id - the stable ID to fetch the history tree for
Arg [2] : (optional) Int $num_high_scorers
number of mappings per stable ID allowed when filtering
Arg [3] : (optional) Int $max_rows
maximum number of stable IDs in history tree (used for
filtering)
Arg [4] : (optional) Float $time_limit
Optimise tree normally runs until it hits a minimised state
but this can take a very long time. Therefore you can
opt to bail out of the optimisation early. Specify the
time in seconds. Floating point values are supported should you
require sub-second limits
Example : my $history = $archive_adaptor->fetch_history_tree_by_stable_id(
'ENSG00023747897');
Description : Returns the history tree for a given stable ID. This will
include a network of all stable IDs it is related to. The
method will try to return a minimal (sparse) set of nodes
(ArchiveStableIds) and links (StableIdEvents) by removing any
redundant entries and consolidating mapping events so that only
changes are recorded.
Return type : Bio::EnsEMBL::StableIdHistoryTree
Exceptions : thrown on missing argument
Caller : Bio::EnsEMBL::ArchiveStableId::get_history_tree, general
Status : At Risk
: under development
=cut
sub fetch_history_tree_by_stable_id {
my ($self, $stable_id, $num_high_scorers, $max_rows, $time_limit) = @_;
throw("Expecting a stable ID argument.") unless $stable_id;
$num_high_scorers ||= NUM_HIGH_SCORERS;
$max_rows ||= MAX_ROWS;
# using a UNION is much faster in this query than somthing like
# "... AND (sie.old_stable_id = ?) OR (sie.new_stable_id = ?)"
#
# SQLite uses the fully qualified column name as the key in
# fetchrow_hashref() when there's a UNION, hence the need to
# avoid table names qualifiers in the column lists.
my $sql = qq(
SELECT old_stable_id, old_version,
old_db_name, old_release, old_assembly,
new_stable_id, new_version,
new_db_name, new_release, new_assembly,
type, score
FROM stable_id_event sie, mapping_session ms
WHERE sie.mapping_session_id = ms.mapping_session_id
AND sie.old_stable_id = ?
UNION
SELECT old_stable_id, old_version,
old_db_name, old_release, old_assembly,
new_stable_id, new_version,
new_db_name, new_release, new_assembly,
type, score
FROM stable_id_event sie, mapping_session ms
WHERE sie.mapping_session_id = ms.mapping_session_id
AND sie.new_stable_id = ?
);
my $sth = $self->prepare($sql);
my $history = Bio::EnsEMBL::StableIdHistoryTree->new(
-CURRENT_DBNAME => $self->dbc->dbname,
-CURRENT_RELEASE => $self->get_current_release,
-CURRENT_ASSEMBLY => $self->get_current_assembly,
);
# remember stable IDs you need to do and those that are done. Initialise the
# former hash with the focus stable ID
my %do = ($stable_id => 1);
my %done;
# while we got someting to do
while (my ($id) = keys(%do)) {
# if we already have more than MAX_ROWS stable IDs in this tree, we can't
# build the full tree. Return undef.
if (scalar(keys(%done)) > $max_rows) {
# warning("Too many related stable IDs (".scalar(keys(%done)).") to draw a history tree.");
$history->is_incomplete(1);
$sth->finish;
last;
}
# mark this stable ID as done
delete $do{$id};
$done{$id} = 1;
# fetch all stable IDs related to this one from the database
$sth->bind_param(1, $id, SQL_VARCHAR);
$sth->bind_param(2, $id, SQL_VARCHAR);
$sth->execute;
my @events;
while (my $r = $sth->fetchrow_hashref) {
#
# create old and new ArchiveStableIds and a StableIdEvent to link them
# add all of these to the history tree
#
my ($old_id, $new_id);
if ($r->{'old_stable_id'}) {
$old_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $r->{'old_stable_id'},
-version => $r->{'old_version'},
-db_name => $r->{'old_db_name'},
-release => $r->{'old_release'},
-assembly => $r->{'old_assembly'},
-type => $r->{'type'},
-adaptor => $self
);
}
if ($r->{'new_stable_id'}) {
$new_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $r->{'new_stable_id'},
-version => $r->{'new_version'},
-db_name => $r->{'new_db_name'},
-release => $r->{'new_release'},
-assembly => $r->{'new_assembly'},
-type => $r->{'type'},
-adaptor => $self
);
}
my $event = Bio::EnsEMBL::StableIdEvent->new(
-old_id => $old_id,
-new_id => $new_id,
-score => $r->{'score'}
);
push @events, $event;
}
# filter out low-scoring events; the number of highest scoring events
# returned is defined by NUM_HIGH_SCORERS
my @others;
foreach my $event (@events) {
my $old_id = $event->old_ArchiveStableId;
my $new_id = $event->new_ArchiveStableId;
# creation, deletion and mapping-to-self events are added to the history
# tree directly
if (!$old_id || !$new_id || ($old_id->stable_id eq $new_id->stable_id)) {
$history->add_StableIdEvents($event);
} else {
push @others, $event;
}
}
#if (scalar(@others) > $num_high_scorers) {
# warn "Filtering ".(scalar(@others) - $num_high_scorers).
# " low-scoring events.\n";
#}
my $k = 0;
foreach my $event (sort { $b->score <=> $a->score } @others) {
$history->add_StableIdEvents($event);
# mark stable IDs as todo if appropriate
$do{$event->old_ArchiveStableId->stable_id} = 1
unless $done{$event->old_ArchiveStableId->stable_id};
$do{$event->new_ArchiveStableId->stable_id} = 1
unless $done{$event->new_ArchiveStableId->stable_id};
last if (++$k == $num_high_scorers);
}
}
$sth->finish;
# try to consolidate the tree (remove redundant nodes, bridge gaps)
$history->consolidate_tree;
# now add ArchiveStableIds for current Ids not found in the archive
$self->add_all_current_to_history($history);
# calculate grid coordinates for the sorted tree; this will also try to
# untangle the tree
$history->calculate_coords($time_limit);
return $history;
}
=head2 add_all_current_to_history
Arg[1] : Bio::EnsEMBL::StableIdHistoryTree $history -
the StableIdHistoryTree object to add the current IDs to
Description : This method adds the current versions of all stable IDs found
in a StableIdHistoryTree object to the tree, by creating
appropriate Events for the stable IDs found in the *_stable_id
tables. This is a helper method for
fetch_history_tree_by_stable_id(), see there for more
documentation.
Return type : none (passed-in object is manipulated)
Exceptions : thrown on missing or wrong argument
Caller : internal
Status : At Risk
: under development
=cut
sub add_all_current_to_history {
my $self = shift;
my $history = shift;
unless ($history and $history->isa('Bio::EnsEMBL::StableIdHistoryTree')) {
throw("Need a Bio::EnsEMBL::StableIdHistoryTree.");
}
my @ids = @{ $history->get_unique_stable_ids };
my $id_string = join("', '", @ids);
my $tmp_id = Bio::EnsEMBL::ArchiveStableId->new(-stable_id => $ids[0]);
my $type = lc($self->_resolve_type($tmp_id));
return unless ($type);
# get current stable IDs from db
my $sql = qq(
SELECT stable_id, version FROM ${type}
WHERE stable_id IN ('$id_string')
);
my $sth = $self->prepare($sql);
$sth->execute;
while (my ($stable_id, $version) = $sth->fetchrow_array) {
my $new_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $stable_id,
-version => $version,
-current_version => $version,
-db_name => $self->dbc->dbname,
-release => $self->get_current_release,
-assembly => $self->get_current_assembly,
-type => $type,
-adaptor => $self
);
my $event = $history->get_latest_StableIdEvent($new_id);
next unless ($event);
if ($event->old_ArchiveStableId and
$event->old_ArchiveStableId->stable_id eq $stable_id) {
# latest event was a self event
# update it with current stable ID and add to tree
$event->new_ArchiveStableId($new_id);
} else {
# latest event was a non-self event
# create a new event where the old_id is the new_id from latest
my $new_event = Bio::EnsEMBL::StableIdEvent->new(
-old_id => $event->new_ArchiveStableId,
-new_id => $new_id,
-score => $event->score,
);
$history->add_StableIdEvents($new_event);
}
}
# refresh node cache
$history->flush_ArchiveStableIds;
$history->add_ArchiveStableIds_for_events;
}
=head2 fetch_successor_history
Arg [1] : Bio::EnsEMBL::ArchiveStableId $arch_id
Example : none
Description : Gives back a list of archive stable ids which are successors in
the stable_id_event tree of the given stable_id. Might well be
empty.
This method is valid, but in most cases you will rather
want to use fetch_history_tree_by_stable_id().
Returntype : listref Bio::EnsEMBL::ArchiveStableId
Since every ArchiveStableId knows about it's successors, this is
a linked tree.
Exceptions : none
Caller : webcode for archive
Status : At Risk
: under development
=cut
sub fetch_successor_history {
my $self = shift;
my $arch_id = shift;
my $current_db_name = $self->list_dbnames->[0];
my $dbname = $arch_id->db_name;
if ($dbname eq $current_db_name) {
return [$arch_id];
}
my $old = [];
my @result = ();
push @$old, $arch_id;
while ($dbname ne $current_db_name) {
my $new = [];
while (my $asi = (shift @$old)) {
push @$new, @{ $asi->get_all_successors };
}
if (@$new) {
$dbname = $new->[0]->db_name;
} else {
last;
}
# filter duplicates
my %unique = map { join(":", $_->stable_id, $_->version, $_->release) =>
$_ } @$new;
@$new = values %unique;
@$old = @$new;
push @result, @$new;
}
return \@result;
}
=head2 fetch_predecessor_history
Arg [1] : Bio::EnsEMBL::ArchiveStableId $arch_id
Example : none
Description : Gives back a list of archive stable ids which are predecessors
in the stable_id_event tree of the given stable_id. Might well
be empty.
This method is valid, but in most cases you will rather
want to use fetch_history_tree_by_stable_id().
Returntype : listref Bio::EnsEMBL::ArchiveStableId
Since every ArchiveStableId knows about it's successors, this is
a linked tree.
Exceptions : none
Caller : webcode for archive
Status : At Risk
: under development
=cut
sub fetch_predecessor_history {
my $self = shift;
my $arch_id = shift;
my $oldest_db_name = $self->list_dbnames->[-1];
my $dbname = $arch_id->db_name;
if ($dbname eq $oldest_db_name) {
return [$arch_id];
}
my $old = [];
my @result = ();
push @$old, $arch_id;
while ($dbname ne $oldest_db_name) {
my $new = [];
while (my $asi = (shift @$old)) {
push @$new, @{ $asi->get_all_predecessors };
}
if( @$new ) {
$dbname = $new->[0]->db_name;
} else {
last;
}
# filter duplicates
my %unique = map { join(":", $_->stable_id, $_->version, $_->release) =>
$_ } @$new;
@$new = values %unique;
@$old = @$new;
push @result, @$new;
}
return \@result;
}
=head2 fetch_stable_id_event
Arg [1] : Bio::EnsEMBL::ArchiveStableId $arch_id
Arg [2] : stable_id
Example : my $archive = $archive_stable_id_adaptor->fetch_by_stable_id($id);
my $event = $archive_stable_id_adaptor($archive, $id2);
Description : Gives back the event that links an archive stable id
to a specific stable id
Returntype : Bio::EnsEMBL::StableIdEvent
Undef if no event was found
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub fetch_stable_id_event {
my $self = shift;
my $arch_id = shift;
my $stable_id = shift;
my $event;
my $sql = qq(
SELECT sie.old_stable_id, sie.old_version, sie.new_stable_id, sie.new_version, sie.type, sie.score,
ms.old_db_name, ms.new_db_name, ms.old_release, ms.new_release, ms.old_assembly, ms.new_assembly
FROM stable_id_event sie, mapping_session ms
WHERE ms.mapping_session_id = sie.mapping_session_id
AND (old_stable_id = ? AND ms.old_db_name = ? AND old_release = ? AND old_assembly = ? AND new_stable_id = ?)
OR (new_stable_id = ? AND ms.new_db_name = ? AND new_release = ? AND new_assembly = ? AND old_stable_id = ?)
);
my $sth = $self->prepare($sql);
$sth->bind_param(1, $arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(2, $arch_id->db_name, SQL_VARCHAR);
$sth->bind_param(3, $arch_id->release, SQL_INTEGER);
$sth->bind_param(4, $arch_id->assembly, SQL_VARCHAR);
$sth->bind_param(5, $stable_id, SQL_VARCHAR);
$sth->bind_param(6, $arch_id->stable_id, SQL_VARCHAR);
$sth->bind_param(7, $arch_id->db_name, SQL_VARCHAR);
$sth->bind_param(8, $arch_id->release, SQL_INTEGER);
$sth->bind_param(9, $arch_id->assembly, SQL_VARCHAR);
$sth->bind_param(10, $stable_id, SQL_VARCHAR);
$sth->execute();
my ($old_stable_id, $old_version, $new_stable_id, $new_version, $type, $score);
my ($old_db_name, $new_db_name, $old_release, $new_release, $old_assembly, $new_assembly);
$sth->bind_columns(\$old_stable_id, \$old_version, \$new_stable_id, \$new_version, \$type, \$score,
\$old_db_name, \$new_db_name, \$old_release, \$new_release, \$old_assembly, \$new_assembly);
while ($sth->fetch) {
if ($new_stable_id eq $stable_id) {
my $alt_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $new_stable_id,
-version => $new_version,
-db_name => $new_db_name,
-release => $new_release,
-assembly => $new_assembly,
-type => $type,
-adaptor => $self
);
$event = Bio::EnsEMBL::StableIdEvent->new(
-old_id => $arch_id,
-new_id => $alt_id,
-score => $score
);
} elsif ($old_stable_id eq $stable_id) {
my $alt_id = Bio::EnsEMBL::ArchiveStableId->new(
-stable_id => $old_stable_id,
-version => $old_version,
-db_name => $old_db_name,
-release => $old_release,
-assembly => $old_assembly,
-type => $type,
-adaptor => $self
);
$event = Bio::EnsEMBL::StableIdEvent->new(
-old_id => $alt_id,
-new_id => $arch_id,
-score => $score
);
}
}
$sth->finish();
return $event;
}
=head2 list_dbnames
Args : none
Example : none
Description : A list of available database names from the latest (current) to
the oldest (ordered).
Returntype : listref of strings
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub list_dbnames {
my $self = shift;
if( ! defined $self->{'dbnames'} ) {
my $sql = qq(
SELECT old_db_name, new_db_name
FROM mapping_session
ORDER BY created DESC
);
my $sth = $self->prepare( $sql );
$sth->execute();
my ( $old_db_name, $new_db_name );
my @dbnames = ();
my %seen;
$sth->bind_columns( \$old_db_name, \$new_db_name );
while( $sth->fetch() ) {
# this code now can deal with non-chaining mapping sessions
push(@{ $self->{'dbnames'} }, $new_db_name) unless ($seen{$new_db_name});
$seen{$new_db_name} = 1;
push(@{ $self->{'dbnames'} }, $old_db_name) unless ($seen{$old_db_name});
$seen{$old_db_name} = 1;
}
$sth->finish();
}
return $self->{'dbnames'};
}
=head2 previous_dbname
Arg[1] : String $dbname - focus db name
Example : my $prev_db = $self->previous_dbname($curr_db);
Description : Returns the name of the next oldest database which has mapping
session information.
Return type : String (or undef if not available)
Exceptions : none
Caller : general
Status : At Risk
=cut
sub previous_dbname {
my $self = shift;
my $dbname = shift;
my $curr_idx = $self->_dbname_index($dbname);
my @dbnames = @{ $self->list_dbnames };
if ($curr_idx == @dbnames) {
# this is the oldest dbname, so no previous one available
return undef;
} else {
return $dbnames[$curr_idx+1];
}
}
=head2 next_dbname
Arg[1] : String $dbname - focus db name
Example : my $prev_db = $self->next_dbname($curr_db);
Description : Returns the name of the next newest database which has mapping
session information.
Return type : String (or undef if not available)
Exceptions : none
Caller : general
Status : At Risk
=cut
sub next_dbname {
my $self = shift;
my $dbname = shift;
my $curr_idx = $self->_dbname_index($dbname);
my @dbnames = @{ $self->list_dbnames };
if ($curr_idx == 0) {
# this is the latest dbname, so no next one available
return undef;
} else {
return $dbnames[$curr_idx-1];
}
}
#
# helper method to return the array index of a database in the ordered list of
# available databases (as returned by list_dbnames()
#
sub _dbname_index {
my $self = shift;
my $dbname = shift;
my @dbnames = @{ $self->list_dbnames };
for (my $i = 0; $i < @dbnames; $i++) {
if ($dbnames[$i] eq $dbname) {
return $i;
}
}
}
=head2 get_peptide
Arg [1] : Bio::EnsEMBL::ArchiveStableId $arch_id
Example : none
Description : Retrieves the peptide string for given ArchiveStableId. If its
not a peptide or not in the database returns undef.
Returntype : string or undef
Exceptions : none
Caller : Bio::EnsEMBL::ArchiveStableId->get_peptide, general
Status : At Risk
: under development
=cut
sub get_peptide {
my $self = shift;
my $arch_id = shift;
if ( lc( $arch_id->type() ) ne 'translation' ) {
return undef;
}
my $sql = qq(
SELECT pa.peptide_seq
FROM peptide_archive pa, gene_archive ga
WHERE ga.translation_stable_id = ?
AND ga.translation_version = ?
AND ga.peptide_archive_id = pa.peptide_archive_id
);
my $sth = $self->prepare($sql);
$sth->bind_param( 1, $arch_id->stable_id, SQL_VARCHAR );
$sth->bind_param( 2, $arch_id->version, SQL_SMALLINT );
$sth->execute();
my ($peptide_seq) = $sth->fetchrow_array();
$sth->finish();
return $peptide_seq;
} ## end sub get_peptide
=head2 get_current_release
Example : my $current_release = $archive_adaptor->get_current_release;
Description : Returns the current release number (as found in the meta table).
Return type : Int
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub get_current_release {
my $self = shift;
unless ($self->{'current_release'}) {
my $mca = $self->db->get_MetaContainer;
my ($release) = @{ $mca->list_value_by_key('schema_version') };
$self->{'current_release'} = $release;
}
return $self->{'current_release'};
}
=head2 get_current_assembly
Example : my $current_assembly = $archive_adaptor->get_current_assembly;
Description : Returns the current assembly version (as found in the meta
table).
Return type : String
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub get_current_assembly {
my $self = shift;
unless ($self->{'current_assembly'}) {
my $mca = $self->db->get_MetaContainer;
my ($assembly) = @{ $mca->list_value_by_key('assembly.default') };
$self->{'current_assembly'} = $assembly;
}
return $self->{'current_assembly'};
}
=head2 lookup_current
Arg[1] : Bio::EnsEMBL::ArchiveStableId $arch_id -
the stalbe ID to find the current version for
Example : if ($self->lookup_version($arch_id) {
$arch_id->version($arch_id->current_version);
$arch_id->db_name($self->dbc->dbname);
Description : Look in [gene|transcript|translation]_stable_id if you can find
a current version for this stable ID. Set
ArchiveStableId->current_version if found.
Return type : Boolean (TRUE if current version found, else FALSE)
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub lookup_current {
my $self = shift;
my $arch_id = shift;
my $type = lc( $arch_id->type );
unless ($type) {
warning("Can't lookup current version without a type.");
return 0;
}
my $sql = qq(
SELECT version FROM ${type}
WHERE stable_id = ?
);
my $sth = $self->prepare($sql);
$sth->execute( $arch_id->stable_id );
my ($version) = $sth->fetchrow_array;
$sth->finish;
if ($version) {
$arch_id->current_version($version);
return 1;
}
# didn't find a current version
return 0;
} ## end sub lookup_current
# infer type from stable ID format
sub _resolve_type {
my $self = shift;
my $arch_id = shift;
my $stable_id = $arch_id->stable_id();
my $id_type;
# first, try to infer type from stable ID format
#
# Anopheles IDs
if ($stable_id =~ /^AGAP.*/) {
if ($stable_id =~ /.*-RA/) {
$id_type = "Transcript";
} elsif ($stable_id =~ /.*-PA/) {
$id_type = "Translation";
} else {
$id_type = "Gene";
}
# standard Ensembl IDs
} elsif ($stable_id =~ /.*G\d+(\.\d+)?$/) {
$id_type = "Gene";
} elsif ($stable_id =~ /.*T\d+(\.\d+)?$/) {
$id_type = "Transcript";
} elsif ($stable_id =~ /.*P\d+(\.\d+)?$/) {
$id_type = "Translation";
} elsif ($stable_id =~ /.*E\d+(\.\d+)?$/) {
$id_type = "Exon";
# if guessing fails, look in db
} else {
my $sql = qq(
SELECT type from stable_id_event
WHERE old_stable_id = ?
OR new_stable_id = ?
);
my $sth = $self->prepare($sql);
$sth->execute($stable_id, $stable_id);
($id_type) = $sth->fetchrow_array;
$sth->finish;
}
warning("Couldn't resolve stable ID type.") unless ($id_type);
$arch_id->type($id_type);
}
1;
| muffato/ensembl | modules/Bio/EnsEMBL/DBSQL/ArchiveStableIdAdaptor.pm | Perl | apache-2.0 | 47,794 |
use strict;
use warnings;
package Boilerplater::Type::Object;
use base qw( Boilerplater::Type );
use Boilerplater::Parcel;
use Boilerplater::Util qw( verify_args );
use Scalar::Util qw( blessed );
use Carp;
our %new_PARAMS = (
const => undef,
specifier => undef,
indirection => 1,
parcel => undef,
incremented => 0,
decremented => 0,
);
sub new {
my $either = shift;
verify_args( \%new_PARAMS, @_ ) or confess $@;
my $self = bless { %new_PARAMS, @_, }, ref($either) || $either;
# Validate indirection.
confess("Indirection must be 1") unless $self->{indirection} == 1;
# Find parcel and parcel prefix.
if ( !defined $self->{parcel} ) {
$self->{parcel} = Boilerplater::Parcel->default_parcel;
}
elsif ( blessed( $self->{parcel} ) ) {
confess("Not a Boilerplater::Parcel")
unless $self->{parcel}->isa('Boilerplater::Parcel');
}
else {
$self->{parcel}
= Boilerplater::Parcel->singleton( name => $self->{parcel} );
}
my $prefix = $self->{parcel}->get_prefix;
# Validate specifier.
confess("illegal specifier: '$self->{specifier}")
unless $self->{specifier}
=~ /^(?:$prefix)?[A-Z][A-Za-z0-9]*[a-z]+[A-Za-z0-9]*(?!\w)/;
# Add $prefix if necessary.
$self->{specifier} = $prefix . $self->{specifier}
unless $self->{specifier} =~ /^$prefix/;
return $self;
}
# Accessors.
sub const { shift->{const} }
sub void {0}
sub is_object {1}
sub is_integer {0}
sub is_floating {0}
sub incremented { shift->{incremented} }
sub decremented { shift->{decremented} }
sub is_string_type {
my $self = shift;
return 0 unless $self->{specifier} =~ /CharBuf/;
return 1;
}
sub equals {
my ( $self, $other ) = @_;
return 0 unless $self->{specifier} eq $other->{specifier};
for (qw( const incremented decremented )) {
return 0 if ( $self->{$_} xor $other->{$_} );
}
return 1;
}
sub to_c {
my $self = shift;
my $string = $self->const ? 'const ' : '';
$string .= "$self->{specifier}*";
return $string;
}
1;
__END__
| robertkrimen/Search-Kino03 | boilerplater/lib/Boilerplater/Type/Object.pm | Perl | apache-2.0 | 2,152 |
#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: src/usr/targeting/common/xmltohb/create_ekb_targattr.pl $
#
# OpenPOWER HostBoot Project
#
# Contributors Listed Below - COPYRIGHT 2017
# [+] International Business Machines Corp.
#
#
# 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.
#
# IBM_PROLOG_END_TAG
#
#
# Usage:
#
# create_attr_ekb --fapi=fapiattrs.xml --attr=attribute_types_ekb.xml
# --targ=target_types.xmltohb --default=hb_temp_default.xml
#
# Purpose:
#
# This perl script processes the FAPI attributes in fapiattrs.xml, and the
# temporary defaults in hb_temp_defaults.xml and creates attribute_types_ekb.xml,
# and target_types_ekb.xml with equivalent Hostboot attribute definitions.
#
use strict;
use XML::Simple;
use Data::Dumper;
#add the fapi_utils path to include paths
#this is useful for debugging
push (@INC, "../../xmltohb");
require "fapi_utils.pl";
$XML::Simple::PREFERRED_PARSER = 'XML::Parser';
use Digest::MD5 qw(md5_hex);
#init variables
my $generic = "";
my $fapi_filename = "";
my $targ_filename = "";
my $attr_filename = "";
my $hbCustomize_filename = "";
my $usage = 0;
use Getopt::Long;
GetOptions( "fapi:s" => \$fapi_filename,
"attr:s" => \$attr_filename,
"targ:s" => \$targ_filename,
"default:s" => \$hbCustomize_filename,
"help" => \$usage, );
if( ($fapi_filename eq "")
|| ($attr_filename eq "")
|| ($targ_filename eq "") )
{
display_help();
exit 1;
}
elsif ($usage)
{
display_help();
exit 0;
}
#use the XML::Simple tool to convert the xml files into hashmaps
my $xml = new XML::Simple (KeyAttr=>[]);
#data from the ekb fapi attributes
my $fapiXml = $xml->XMLin("$fapi_filename" ,
forcearray => ['attribute'],
NoAttr => 1);
#data from the temporary default xml
my $hbCustomizeXml = $xml->XMLin("$hbCustomize_filename" ,
forcearray => ['attribute'],
NoAttr => 1);
####################
##### Generate attribute_types #####
print "\nGenerating attribute_types\n";
my $numattrs = 0;
open (my $ATTR_FH, ">$attr_filename") ||
die "ERROR: unable to open $attr_filename\n";
print $ATTR_FH "<attributes>\n\n";
# Walk attribute definitions in fapiattrs.xml
foreach my $FapiAttr ( @{$fapiXml->{attribute}} )
{
#we dont need to worry about EC FEATURE attributes
if( $FapiAttr->{id} =~ /_EC_FEATURE/ )
{
next;
}
#print "====" . $FapiAttr->{id} . "\n";
#Check if there are any defaults values we need to add to fapi attrs before generating HB
foreach my $customizedAttr(@{$hbCustomizeXml->{attribute}})
{
#if we find a match, then add update the attribute w/ customized values
if ($customizedAttr->{id} eq $FapiAttr->{id})
{
if(exists $customizedAttr->{default})
{
#print "Found match for ".$customizedAttr->{id}." default val is ".$customizedAttr->{default}."\n";
$FapiAttr->{default} = $customizedAttr->{default};
}
}
}
#use utility functions to generate enum xml, if possible
my $enum = createEnumFromAttr($FapiAttr);
#use utility functions to generate attribute xml
my $attr = createAttrFromFapi($FapiAttr);
#Check if there are additional tags besides default we need to add to fapi attrs
foreach my $customizedAttr(@{$hbCustomizeXml->{attribute}})
{
#if we find a match, then add update the attribute w/ customized values
if ($customizedAttr->{id} eq $attr->{hwpfToHbAttrMap}->{id})
{
foreach my $tag (keys %$customizedAttr)
{
if($tag ne "default" && $tag ne "id" )
{
#print "Found match for ".$customizedAttr->{id}." $tag val is ".$customizedAttr->{$tag}."\n";
$attr->{$tag} = $customizedAttr->{$tag};
}
}
#Do not exit loop yet, continue in case there are more than 1 attr customization tags
}
}
#not all attribute have enumaterated values, so enums are optional
if($enum ne "0" && $enum ne "")
{
printTargEnum($ATTR_FH, $enum);
}
#write to the attribute xml file
printTargAttr($ATTR_FH,$attr);
print $ATTR_FH "\n";
$numattrs++;
}
print "...$numattrs attributes generated from EKB\n";
print $ATTR_FH "</attributes>";
close $ATTR_FH;
####################
##### Generate target_types #####
print "\nGenerating target_types\n";
open (my $TARG_FH, ">$targ_filename") ||
die "ERROR: unable to open $targ_filename\n";
my $allTargetExt = {};
# Walk attribute definitions in fapiattrs.xml
foreach my $FapiAttr ( @{$fapiXml->{attribute}} )
{
#print "====" . $FapiAttr->{id} . "\n";
#like when generating attributes, skip the _EC_FEATURES
if( $FapiAttr->{id} =~ /_EC_FEATURE/ )
{
next;
}
#use the utility function to generate a target extension xml
createTargetExtensionFromFapi($FapiAttr,$allTargetExt);
}
#begin writing the file
print $TARG_FH "<attributes>\n\n";
# Print out all the generated stuff
foreach my $targ (@{$allTargetExt->{targetTypeExtension}})
{
#print $targ->{id} ."\n";
printTargExt($TARG_FH,$targ);
print $TARG_FH "\n";
}
print $TARG_FH "</attributes>";
close $TARG_FH;
###########################################################
###########################################################
sub display_help
{
use File::Basename;
my $scriptname = basename($0);
print STDERR "
Description:
This perl script processes the FAPI attributes in fapiattrs.xml, and the
temporary defaults in hb_temp_defaults.xml and creates attribute_types_ekb.xml,
and target_types_ekb.xml with equivalent Hostboot attribute definitions.
Usage:
$scriptname --help
$scriptname --fapi=fapifname
fapifname is complete pathname of the fapiattrs.xml file
$scriptname --attr=attrofname
attrofname is complete pathname of the attribute_types_ekb.xml
$scriptname --targ=targofname
targofname is complete pathname of the target_types_ekb.xml
$scriptname --default=defaultifname
defaultifname is the complete pathname of the hb_temp_defaults.xml
\n";
}
| Over-enthusiastic/hostboot | src/usr/targeting/common/xmltohb/create_ekb_targattr.pl | Perl | apache-2.0 | 6,913 |
:- module(lqsort, [test/2], [lazy]).
:- use_module(library(prolog_sys), [statistics/2]).
:- use_module(library(lists), [append/3]).
:- use_module(library('lazy/lazy_lib'), _).
:- use_module(library(random)).
:- lazy qsort/2.
qsort([X|L], R) :-
partition(L, X, L1, L2),
qsort(L2, R2),
qsort(L1, R1),
append(R1, [X|R2], R).
qsort([], []).
:- lazy partition/4.
partition([], _B, [], []).
partition([E|R], C, [E|Left1], Right):-
E < C,
partition(R, C, Left1, Right).
partition([E|R], C, Left, [E|Right1]):-
E >= C,
partition(R, C, Left, Right1).
:- lazy gen_list/2.
gen_list(0, []).
gen_list(X, [N|T]) :-
X > 0,
random(1, 1000000, N),
gen_list(X-1, T).
test(X, Res) :-
gen_list(X, L),
qsort(L, LOrd),
take(X, LOrd, Res).
| leuschel/ecce | www/CiaoDE/ciao/contrib/lazy/examples/lqsort.pl | Perl | apache-2.0 | 746 |
package VMOMI::VmfsMountFault;
use parent 'VMOMI::HostConfigFault';
use strict;
use warnings;
our @class_ancestors = (
'HostConfigFault',
'VimFault',
'MethodFault',
);
our @class_members = (
['uuid', undef, 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/VmfsMountFault.pm | Perl | apache-2.0 | 454 |
#!/usr/bin/env perl
# vim:ts=4:sw=4:expandtab
#
# © 2010-2011 Michael Stapelberg and contributors
#
# syntax: ./complete-run.pl --display :1 --display :2
# to run the test suite on the X11 displays :1 and :2
# use 'Xdummy :1' and 'Xdummy :2' before to start two
# headless X11 servers
#
use strict;
use warnings;
use EV;
use AnyEvent;
use IO::Scalar; # not in core :\
use File::Temp qw(tempfile tempdir);
use v5.10;
use DateTime;
use Data::Dumper;
use Cwd qw(abs_path);
use Proc::Background;
use TAP::Harness;
use TAP::Parser;
use TAP::Parser::Aggregator;
use File::Basename qw(basename);
use AnyEvent::I3 qw(:all);
use Try::Tiny;
use Getopt::Long;
use Time::HiRes qw(sleep);
use X11::XCB::Connection;
# install a dummy CHLD handler to overwrite the CHLD handler of AnyEvent / EV
# XXX: we could maybe also use a different loop than the default loop in EV?
$SIG{CHLD} = sub {
};
# reads in a whole file
sub slurp {
open my $fh, '<', shift;
local $/;
<$fh>;
}
my $coverage_testing = 0;
my @displays = ();
my $result = GetOptions(
"coverage-testing" => \$coverage_testing,
"display=s" => \@displays,
);
@displays = split(/,/, join(',', @displays));
@displays = map { s/ //g; $_ } @displays;
@displays = qw(:1) if @displays == 0;
# connect to all displays for two reasons:
# 1: check if the display actually works
# 2: keep the connection open so that i3 is not the only client. this prevents
# the X server from exiting (Xdummy will restart it, but not quick enough
# sometimes)
my @conns;
my @wdisplays;
for my $display (@displays) {
try {
my $x = X11::XCB::Connection->new(display => $display);
push @conns, $x;
push @wdisplays, $display;
} catch {
say STDERR "WARNING: Not using X11 display $display, could not connect";
};
}
my $i3cmd = abs_path("../i3") . " -V -d all --disable-signalhandler";
my $config = slurp('i3-test.config');
# 1: get a list of all testcases
my @testfiles = @ARGV;
# if no files were passed on command line, run all tests from t/
@testfiles = <t/*.t> if @testfiles == 0;
# 2: create an output directory for this test-run
my $outdir = "testsuite-";
$outdir .= DateTime->now->strftime("%Y-%m-%d-%H-%M-%S-");
$outdir .= `git describe --tags`;
chomp($outdir);
mkdir($outdir) or die "Could not create $outdir";
unlink("latest") if -e "latest";
symlink("$outdir", "latest") or die "Could not symlink latest to $outdir";
# 3: run all tests
my @done;
my $num = @testfiles;
my $harness = TAP::Harness->new({ });
my $aggregator = TAP::Parser::Aggregator->new();
$aggregator->start();
my $cv = AnyEvent->condvar;
# We start tests concurrently: For each display, one test gets started. Every
# test starts another test after completing.
take_job($_) for @wdisplays;
#
# Takes a test from the beginning of @testfiles and runs it.
#
# The TAP::Parser (which reads the test output) will get called as soon as
# there is some activity on the stdout file descriptor of the test process
# (using an AnyEvent->io watcher).
#
# When a test completes and @done contains $num entries, the $cv condvar gets
# triggered to finish testing.
#
sub take_job {
my ($display) = @_;
my ($fh, $tmpfile) = tempfile();
say $fh $config;
say $fh "ipc-socket /tmp/nested-$display";
close($fh);
my $test = shift @testfiles;
return unless $test;
my $logpath = "$outdir/i3-log-for-" . basename($test);
my $cmd = "export DISPLAY=$display; exec $i3cmd -c $tmpfile >$logpath 2>&1";
my $dont_start = (slurp($test) =~ /# !NO_I3_INSTANCE!/);
my $process = Proc::Background->new($cmd) unless $dont_start;
say "[$display] Running $test with logfile $logpath";
sleep 0.5;
my $kill_i3 = sub {
# Don’t bother killing i3 when we haven’t started it
return if $dont_start;
# When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
# files are not written) and fallback to killing it
if ($coverage_testing) {
my $exited = 0;
try {
say "Exiting i3 cleanly...";
i3("/tmp/nested-$display")->command('exit')->recv;
$exited = 1;
};
return if $exited;
}
say "[$display] killing i3";
kill(9, $process->pid) or die "could not kill i3";
};
my $output;
my $parser = TAP::Parser->new({
exec => [ 'sh', '-c', "DISPLAY=$display /usr/bin/perl -It/lib $test" ],
spool => IO::Scalar->new(\$output),
merge => 1,
});
my @watchers;
my ($stdout, $stderr) = $parser->get_select_handles;
for my $handle ($parser->get_select_handles) {
my $w;
$w = AnyEvent->io(
fh => $handle,
poll => 'r',
cb => sub {
# Ignore activity on stderr (unnecessary with merge => 1,
# but let’s keep it in here if we want to use merge => 0
# for some reason in the future).
return if defined($stderr) and $handle == $stderr;
my $result = $parser->next;
if (defined($result)) {
# TODO: check if we should bail out
return;
}
# $result is not defined, we are done parsing
say "[$display] $test finished";
close($parser->delete_spool);
$aggregator->add($test, $parser);
push @done, [ $test, $output ];
$kill_i3->();
undef $_ for @watchers;
if (@done == $num) {
$cv->send;
} else {
take_job($display);
}
}
);
push @watchers, $w;
}
}
$cv->recv;
$aggregator->stop();
for (@done) {
my ($test, $output) = @$_;
say "output for $test:";
say $output;
}
# 4: print summary
$harness->summary($aggregator);
| freexploit/i3wm | testcases/complete-run.pl | Perl | bsd-3-clause | 5,957 |
#!/usr/bin/perl
# Copyright (c) AB_Life 2011
# Writer: xuxiong <xuxiong19880610@163.com>
# Program Date: 2011.
# Modifier: xuxiong <xuxiong19880610@163.com>
# Last Modified: 2011.
use strict;
use Data::Dumper;
use FindBin qw($Bin $Script);
use File::Basename qw(basename dirname);
use List::Util qw(first max maxstr min minstr reduce shuffle sum);
use warnings;
#Before writing your programmeyou must write the detailed timediscriptionsparameter and it's explanation,Meanwhile,annotation your programme in English if possible.
if (scalar(@ARGV)<1) {
print "Usage:perl $0 geneID times length tag_len1 tag_len2 ......\n";
print "\nFor example:\n";
print "perl $Bin/$0 AT1G01010 500 1757 24 32 21 23 21 32 20 21 32\n\n";
exit;
}
my $Gene_id = shift @ARGV;
my $times = shift @ARGV;
my $len = shift @ARGV;
my @tag_len=@ARGV;
my $start = 0;
my $end = $len;
my %MAX_HEIGHT=();
for (my $i=0;$i<$times ;$i++) {
my $current_max_height=&random_peak_max_height($start,$end,\@tag_len);
$MAX_HEIGHT{$current_max_height}++;
}
print "#########################\n";
print "Gene:",$Gene_id,"\n";
my %cumulative_p_value=();
my @keys =sort {$a <=> $b} keys %MAX_HEIGHT;
my $i=0;
foreach my $key_MAX_HEIGHT (@keys ) {
print $key_MAX_HEIGHT,"\t",$MAX_HEIGHT{$key_MAX_HEIGHT},"\t",sprintf("%2.4f",$MAX_HEIGHT{$key_MAX_HEIGHT}/$times),"\t";
$cumulative_p_value{$key_MAX_HEIGHT}=sprintf("%2.4f",sum(map {$MAX_HEIGHT{$_}/$times} @keys[$i..$#keys]));
$i++;
print $cumulative_p_value{$key_MAX_HEIGHT},"\n";
}
sub random_peak_max_height{ #(\$gene_start, \$gene_end, \@random_tag_length)
my ($gene_start,$gene_end,$ref_array)=@_;
my %pos = ();
for (my $i=0; $i<=$#{$ref_array}; $i++) {
my $random_start = $gene_start+int(rand($len-$ref_array->[$i]));
my $random_end = $random_start+$ref_array->[$i]-1;
map {$pos{$_}++} ($random_start..$random_end);
}
return max(values(%pos));
} | ablifedev/ABLIRC | ABLIRC/bin/Clip-Seq/MC/random_IP/random_IP.pl | Perl | mit | 1,896 |
/* Part of Extended Libraries for SWI-Prolog
Author: Edison Mera Menendez
E-mail: efmera@gmail.com
WWW: https://github.com/edisonm/xlibrary
Copyright (C): 2014, Process Design Center, Breda, The Netherlands.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(atomics_atom, [atomics_atom/2]).
%! atomics_atom(+Atms:list(atomic), -Atm:atom) is det.
%! atomics_atom(?Atms:list(atom), +Atm:atomic)
%
% Atm is the atom resulting from concatenating all atomics in the list Atms in
% the order in which they appear. If Atm is an atom at call then Atms can
% contain free variables, and multiple solutions can be found on backtracking.
%
% Based on atom_concat/2 of Ciao-Prolog, but without performance issues.
atomics_atom(Atomics, Atom) :-
( var(Atom)->F=1 ; F=2 ),
atomics_atom(Atomics, F, Atom).
atomics_atom([], _, '').
atomics_atom([A|L], F, Atom) :-
atomics_atom(L, F, A, Atom).
atomics_atom([], _, Atom, Atom).
atomics_atom([B|Atomics], F, A, Atom) :-
atomics_atom(F, Atomics, A, B, Atom).
% Non-optimized/naive version:
%
% atomics_atom(Atoms, A, B, Atom) :-
% nonvar(A),
% nonvar(B), !,
% atom_concat(A, B, C),
% atomics_atom(Atoms, C, Atom).
% atomics_atom(Atoms, A, B, Atom) :-
% atomics_atom(Atoms, C, Atom),
% atom_concat(A, B, C).
atomics_atom(1, Atomics, A, B, Atom) :- atomics_to_atom(Atomics, A, B, Atom).
atomics_atom(2, Atomics, A, B, Atom) :- atom_to_atomics(Atom, A, B, Atomics).
atom_to_atomics(Atom, A, B, Atomics) :-
nonvar(A), !,
atom_concat(A, Atom2, Atom),
atomics_atom(Atomics, 2, B, Atom2).
atom_to_atomics(Atom, A, B, Atomics) :-
nonvar(B), !,
sub_atom(Atom, Before, _, After, B),
sub_atom(Atom, 0, Before, _, A),
sub_atom(Atom, _, After, 0, Atom2),
atomics_atom(Atomics, 2, Atom2).
atom_to_atomics(Atom, A, B, Atomics) :-
atomics_atom(Atomics, 2, C, Atom),
atom_concat(A, B, C).
atomics_to_atom(Atomics, A, B, Atom) :-
( nonvar(A),
nonvar(B)
->atom_concat(A, B, C),
atomics_atom(Atomics, 1, C, Atom)
; throw(error(instantiation_error,
context(atomics_atom:atomics_atom/2,_)))
).
| TeamSPoon/logicmoo_workspace | packs_lib/xlibrary/prolog/atomics_atom.pl | Perl | mit | 3,521 |
#!/usr/bin/perl -w
my $USAGE = "Usage: $0 #-expected-vnodes logfile [logfiles ...]";
my @ids;
my $nv = 0;
die "$USAGE\n" if scalar @ARGV < 2;
my $expected = shift;
die "$USAGE\n#-expected-vnodes must be numeric.\n" unless $expected =~ /^\d+$/;
for $i (0 .. $#ARGV) {
dofile ($ARGV[$i], $i);
}
@ids = sort { $a->[1] <=> $b->[1] } @ids;
print "ids: ", scalar @ids, "\n";
if (scalar @ids != $expected) {
warn "Expected ", $expected, " vnodes; got ", scalar @ids, "\n";
}
for ($i = 0; $i <= $#ids; $i++) {
printf ("%d %16.7f %40s\n", $ids[$i]->[0], $ids[$i]->[1], $ids[$i]->[2]);
}
my $s = 0;
for $i (0 .. $#ARGV) {
$s = check ($ARGV[$i], $i);
if ($s == 0) {
print "unstable $i\n";
exit (0);
}
print "$ARGV[$i]: stable\n";
}
print "stable ", scalar @ARGV, "\n";
if (scalar @ids != $expected) {
exit(1);
} else {
exit(17);
}
sub findindex {
my $i = 0;
for ($i = 0; $i <= $#ids; $i++) {
if ($ids[$i]->[2] eq $_[0]) {
return $i;
}
}
print "findindex: couldn't find $_[0]\n";
exit;
}
sub findsucc {
my $i = 0;
my $j;
for ($i = 0; $i <= $#ids; $i++) {
$j = ($i+1) % ($#ids+1);
if (($ids[$i]->[1] <= $_[0]) &&
($_[0] < $ids[$j]->[1])) {
return $j;
}
}
return 0;
}
sub check {
my $f = $_[0];
my $n = $_[1];
my $id;
my $i;
my $j;
my $s = 1;
my $node;
my $last;
my $m;
print "$f\n";
open (FILE, $f);
while (defined ($line = <FILE>)) {
if ($line =~ /CHORD NODE STATS/) {
print "new check\n";
$last = "";
$s = 1;
}
if ($line =~ /===== ([a-f0-9]+)/) {
$node = $1;
$i = findindex ($node);
# print "check: $i: $ids[$i]->[2]\n";
}
if ($line =~ /finger: (\d+) : ([a-f0-9]+) : succ ([a-f0-9]+)/) {
$m = convert ($2);
$j = findsucc ($m);
if ($ids[$j]->[2] ne $3) {
print "$1: expect succ to be $ids[$j]->[2] instead of $3\n";
$s = 0;
}
}
if ($line =~ /double: ([a-f0-9]+) : d ([a-f0-9]+)/) {
$m = convert ($1);
$j = findsucc ($m);
if ($j > 0) {
$j = $j - 1;
} else {
$j = $#ids;
}
if ($ids[$j]->[2] ne $2) {
print "expect pred double $1 to be $ids[$j]->[2] instead of $2\n";
$s = 0;
}
}
if ($line =~ /succ (\d+) : ([a-f0-9]+)/) {
$i = ($i+1) % ($#ids+1);
if ($ids[$i]->[2] ne $2) {
$last = "check: $node ($n): $1 $i: expect $ids[$i]->[2] instead of $2\n";
$s = 0;
}
}
if ($line =~ /pred : ([a-f0-9]+)/) {
$m = convert ($1);
$j = findsucc ($m);
if ($ids[$j]->[2] ne $node) {
print "$1 pred is $ids[$j]->[2] instead of $node\n";
$s = 0;
}
}
}
close (FILE);
print $last;
return $s;
};
sub dofile {
my $f = $_[0];
my $n = $_[1];
print "$f\n";
open (FILE, $f);
while (defined ($line = <FILE>)) {
if ($line =~ /myID is ([a-f0-9]+)/) {
my $id = convert ($1);
# print "$n: $id\n";
$ids[$nv++] = [$n, $id, $1];
}
}
close (FILE);
}
sub convert {
my($id) = @_;
while (length($id) < 40){
$id = "0" . $id;
}
my $i;
my $x = 0.0;
for($i = 0; $i < 10; $i++){
my $c = substr ($id, $i, 1);
$x *= 16.0;
$x += hex ($c);
}
return $x / 1048575.0;
}
| sit/dht | tst/stable.pl | Perl | mit | 3,237 |
package Eldhelm::Util::CommandLine;
=pod
=head1 NAME
Eldhelm::Util::CommandLine - A utility class for parsing script arguments.
=head1 SYNOPSIS
use strict;
use Eldhelm::Util::CommandLine;
my $cmd = Eldhelm::Util::CommandLine->new(
argv => \@ARGV,
items => [ 'exmplain what should be listed here' ],
options => [
[ 'h help', 'this help text' ],
[ 'o', 'other example option']
]
);
my %args = $cmd->arguments;
if ($args{h} || $args{help}) {
print $cmd->usage;
exit;
}
# something useful here ...
This script can be called this way then:
C<perl myscript.pl item1 item2 item3 -o something>
To see the help you type:
C<perl myscript.pl -h> or C<perl myscript.pl -help>
=head1 METHODS
=over
=cut
use strict;
sub parseArgv {
shift @_ if $_[0] eq __PACKAGE__;
my ($arg, %opt);
while ($arg = shift @_) {
if ($arg =~ /^-+(\S+)/) {
my $op = $1;
if ($_[0] && $_[0] =~ /^-+\S+/) {
$opt{$op} = 1;
next;
}
$opt{$op} = shift(@_) || 1;
next;
}
if ($arg) {
$opt{list} ||= [];
push @{ $opt{list} }, $arg;
}
}
return %opt;
}
=item new(%args)
Constructs a new object.
=cut
sub new {
my ($class, %args) = @_;
my $self = {%args};
return bless $self, $class;
}
=item usage() String
Returns a stream of the help text ready to be printed in the terminal.
=cut
sub usage {
my ($self) = @_;
my $opts = join "\n\t", map {
join(" ", map { "-$_" } split(/ /, $_->[0]))." - ".join("; ", @{$_}[ 1 .. $#$_ ])
} @{ $self->{options} };
my $args = "";
if ($self->{items}) {
my $items = join("|", @{ $self->{items} });
$args .= "[$items] ";
}
if ($opts) {
$args .= "[Options] ";
}
my $usage = "Usage:\n\tperl $0 $args\n";
$usage .= "\nOptions:\n\t$opts\n" if $opts;
if ($self->{examples}) {
my $examples = join("\n", map { "\t".$_ } @{ $self->{examples} });
$usage .= "\nExamples:\n$examples\n";
}
return $usage;
}
=item arguments() Hash
Returns a Hash of parsed arguments.
=cut
sub arguments {
my ($self) = @_;
return Eldhelm::Util::CommandLine->parseArgv(@{ $self->{argv} });
}
=back
=head1 AUTHOR
Andrey Glavchev @ Essence Ltd. (http://essenceworks.com)
=head1 LICENSE
This software is Copyright (c) 2011-2015 of Essence Ltd.
Distributed undert the MIT license.
=cut
1;
| wastedabuser/strezov-tool | lib/Eldhelm/Util/CommandLine.pm | Perl | mit | 2,284 |
#
# Copyright (C) 2012 cogroo <cogroo@cogroo.org>
#
# 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.
#
open (LIST, "tok") or die("Could not open list file. $!");
my %results;
while (my $line = <LIST>) {
$line =~ s/^\s+|\s+$//g;
print "will evaluate $line \n";
}
close LIST;
| cogroo/cogroo4 | cogroo-eval/scripts/teste.pl | Perl | apache-2.0 | 796 |
package Zonemaster::LDNS::RRList;
use strict;
use warnings;
1;
=head1 NAME
Zonemaster::LDNS::RR - common baseclass for all classes representing resource records.
=head1 SYNOPSIS
my $rrlist = $packet->all;
=head1 INSTANCE METHODS
=over
=item count()
Returns the number of items in the list.
=item push($rr)
Pushes an RR onto the list.
=item pop()
Pops an RR off the list.
=item is_rrset()
Returns true or false depending on if the list is an RRset or not.
=back
| dotse/net-ldns | lib/Zonemaster/LDNS/RRList.pm | Perl | bsd-2-clause | 482 |
#------------------------------------------------------------------------------
# File: ja.pm
#
# Description: ExifTool Japanese language translations
#
# Notes: This file generated automatically by Image::ExifTool::TagInfoXML
#------------------------------------------------------------------------------
package Image::ExifTool::Lang::ja;
use strict;
use vars qw($VERSION);
$VERSION = '1.19';
%Image::ExifTool::Lang::ja::Translate = (
'AEAperture' => 'AE絞り',
'AEBAutoCancel' => {
Description => 'ブラケティング自動解除',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AEBBracketValue' => 'AEBブラケット値',
'AEBSequence' => 'ブラケティング順序',
'AEBSequenceAutoCancel' => {
Description => 'ブラケティング順序/自動解除',
PrintConv => {
'-,0,+/Disabled' => '-→0 →+/しない',
'-,0,+/Enabled' => '-→0 →+/する',
'0,-,+/Disabled' => '0 →-→+/しない',
'0,-,+/Enabled' => '0 →-→+/する',
},
},
'AEBShotCount' => 'ブラケティング時の撮影枚数',
'AEBXv' => 'AEブラケット 露出補正',
'AEExposureTime' => 'AE露出時間',
'AEExtra' => 'AE特別?',
'AEInfo' => '自動露出情報',
'AELock' => {
Description => 'AEロック',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AELockButton' => {
Description => 'AE-L/AF-L',
PrintConv => {
'AE-L/AF Area' => 'AE-L/AFエリア',
'AE-L/AF-L/AF Area' => 'AE-L/AF-L/AFエリア',
'AF-L/AF Area' => 'AF-L/AFエリア',
'AF-ON/AF Area' => 'AFオン/AFエリア',
'FV Lock' => 'FVロック',
'Focus Area Selection' => 'フォーカスエリア選択',
},
},
'AEMaxAperture' => 'AE最大絞り',
'AEMaxAperture2' => 'AE最大絞り(2)',
'AEMeteringMode' => {
Description => 'AE測光モード',
PrintConv => {
'Multi-segment' => 'パターン',
},
},
'AEMeteringSegments' => '自動露出測光値',
'AEMinAperture' => 'AE最小絞り',
'AEMinExposureTime' => 'AE最小露出時間',
'AEProgramMode' => {
Description => 'AEプログラムモード',
PrintConv => {
'Av, B or X' => 'Av, BかX',
'Candlelight' => 'キャンドルライト',
'DOF Program' => '深度優先プログラム',
'DOF Program (P-Shift)' => '深度優先プログラム(Pシフト)',
'Hi-speed Program' => '高速優先プログラム',
'Hi-speed Program (P-Shift)' => '高速優先プログラム(Pシフト)',
'Kids' => 'キッズ',
'Landscape' => '風景',
'M, P or TAv' => 'M, PかTAv',
'MTF Program' => 'MTF優先プログラム',
'MTF Program (P-Shift)' => 'MTF優先プログラム(Pシフト)',
'Macro' => 'マクロ',
'Museum' => 'ミュージアム',
'Night Scene' => '夜景',
'Night Scene Portrait' => '人物、夜景',
'No Flash' => 'フラッシュ無し',
'Pet' => 'ペット',
'Portrait' => 'ポートレート',
'Sport' => 'スポーツ',
'Standard' => 'スタンダード',
'Sunset' => '夕日',
'Surf & Snow' => 'サーフ&スノー',
'Sv or Green Mode' => 'Svかグリーンモード',
'Text' => 'テキスト',
},
},
'AESetting' => {
Description => '自動露出設定',
PrintConv => {
'Exposure Compensation' => '露出補正',
},
},
'AEXv' => 'AE 露出補正',
'AE_ISO' => 'AE ISO感度',
'AF-CPrioritySelection' => {
Description => 'AF-Cプライオリティー選択',
PrintConv => {
'Focus' => 'フォーカス',
'Release' => 'レリーズ',
'Release + Focus' => 'レリーズ+フォーカス',
},
},
'AF-OnForMB-D10' => {
Description => 'MB-D10用AFオン',
PrintConv => {
'AE Lock (hold)' => 'AEロック(ホールド)',
'AE Lock (reset on release)' => 'AEロック(レリーズ時リセット)',
'AE Lock Only' => 'AEロックのみ',
'AE/AF Lock' => 'AE/AFロック',
'AF Lock Only' => 'AFロックのみ',
'AF-On' => 'AFオン',
'Same as FUNC Button' => 'ファンクションボタンと同一',
},
},
'AF-SPrioritySelection' => {
Description => 'AF-Sプライオリティー選択',
PrintConv => {
'Focus' => 'フォーカス',
'Release' => 'レリーズ',
},
},
'AFActivation' => {
Description => 'AFアクティベーション',
PrintConv => {
'AF-On Only' => 'AFオンのみ',
'Shutter/AF-On' => 'シャッター/AFオン',
},
},
'AFAdjustment' => 'AF微調整',
'AFArea' => 'AFエリア',
'AFAreaHeight' => 'AFエリア高さ',
'AFAreaHeights' => 'AFエリア高さ',
'AFAreaIllumination' => {
Description => 'AFエリアイルミネーション',
PrintConv => {
'Auto' => 'オート',
'Off' => 'オフ',
'On' => 'オン',
},
},
'AFAreaMode' => {
Description => 'AFエリアモード',
PrintConv => {
'1-area' => '1点',
'1-area (high speed)' => '高速1点',
'3-area (center)?' => '3点中央?',
'3-area (left)?' => '3点左?',
'3-area (right)?' => '3点右?',
'5-area' => '5点',
'Auto-area' => '自動エリアAF',
'Dynamic Area' => 'ダイナミックエリア',
'Dynamic Area (closest subject)' => 'ダイナミック(重点主題)',
'Dynamic Area (wide)' => 'ダイナミック(ワイド)',
'Face Detect AF' => '顔優先',
'Group Dynamic' => 'グループダイナミック',
'Normal?' => 'ノーマル?',
'Single Area' => 'シングルポイント',
'Single Area (wide)' => 'シングルポイント(ワイド)',
'Spot Focusing' => 'スポットフォーカス',
'Spot Mode On' => 'スポットモードオン',
},
},
'AFAreaModeSetting' => {
Description => 'AFエリアモード',
PrintConv => {
'Closest Subject' => 'オートエリア',
'Dynamic Area' => 'ダイナミックエリア',
'Single Area' => 'シングルポイント',
},
},
'AFAreaWidth' => 'AFエリア幅',
'AFAreaWidths' => 'AFエリア幅',
'AFAreas' => 'AFエリア',
'AFAssist' => {
Description => 'AFアシスト',
PrintConv => {
'Does not emit/Fires' => 'しない/する',
'Emits/Does not fire' => 'する/しない',
'Emits/Fires' => 'する/する',
'Off' => 'オフ',
'On' => 'オン',
'Only ext. flash emits/Fires' => '外部ストロボのみする/する',
},
},
'AFAssistBeam' => {
Description => 'AF補助光の投光',
PrintConv => {
'Does not emit' => 'しない',
'Emits' => 'する',
'Only ext. flash emits' => '外部ストロボのみする',
},
},
'AFDefocus' => 'AFぼけ量',
'AFDuringLiveView' => {
Description => 'ライブビュー撮影中のAF',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
'Live mode' => 'ライブモード',
'Quick mode' => 'クイックモード',
},
},
'AFFineTune' => 'AFファインチューン',
'AFFineTuneAdj' => 'AFファインチューン',
'AFImageHeight' => 'AF画像高さ',
'AFImageWidth' => 'AF画像幅',
'AFInfo' => 'AFモード',
'AFInfo2' => 'AF情報',
'AFInfo2Version' => 'AF情報バージョン',
'AFIntegrationTime' => 'AF集積時間',
'AFMicroadjustment' => {
Description => 'AFマイクロアジャストメント',
PrintConv => {
'Adjust all by same amount' => '全レンズ一律調整',
'Adjust by lens' => 'レンズごとに調整',
'Disable' => 'しない',
},
},
'AFMode' => 'AFモード',
'AFOnAELockButtonSwitch' => {
Description => 'AF-ON/AEロックボタン入替',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'AFPoint' => {
Description => 'AF選択ポイント',
PrintConv => {
'Auto AF point selection' => 'オートAFポイント選択',
'Bottom' => '下',
'Center' => '中央',
'Face Detect' => '顔認識',
'Left' => '左',
'Manual AF point selection' => 'マニュアルAFポイント選択',
'Mid-left' => '中央左',
'Mid-right' => '中央右',
'None' => '無し',
'None (MF)' => '無し(MF)',
'Right' => '右',
'Top' => '上',
},
},
'AFPointActivationArea' => {
Description => 'AFフレームの領域拡大',
PrintConv => {
'Standard' => 'スタンダード',
},
},
'AFPointAreaExpansion' => {
Description => '任意選択時のAFフレーム領域拡大',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
'Left/right AF points' => 'する(左右1領域アシスト有効)',
'Surrounding AF points' => 'する(周囲1領域アシスト有効)',
},
},
'AFPointAutoSelection' => {
Description => 'AFフレーム自動選択の選択可否',
PrintConv => {
'Control-direct:disable/Main:disable' => 'サブ電子ダイヤル直接:不可/メイン電子ダイヤル→不可',
'Control-direct:disable/Main:enable' => 'サブ電子ダイヤル直接:不可/メイン電子ダイヤル→可',
'Control-direct:enable/Main:enable' => 'サブ電子ダイヤル直接:可/メイン電子ダイヤル→可',
},
},
'AFPointBrightness' => {
Description => 'AFフレーム点灯輝度',
PrintConv => {
'Brighter' => '明るい',
'Normal' => '標準',
},
},
'AFPointDisplayDuringFocus' => {
Description => '測距時のAFフレーム表示',
PrintConv => {
'Off' => 'しない',
'On' => 'する',
'On (when focus achieved)' => 'する(合焦時)',
},
},
'AFPointIllumination' => {
Description => 'AFポイントイルミネーション',
PrintConv => {
'Auto' => 'オート',
'Off' => 'オフ',
'On' => 'オン',
},
},
'AFPointMode' => {
Description => 'AF測距点モード',
PrintConv => {
'Auto' => 'オート',
},
},
'AFPointRegistration' => {
Description => 'AFフレームの登録',
PrintConv => {
'Automatic' => 'オート',
'Bottom' => '下',
'Center' => '中央',
'Extreme Left' => '左端',
'Extreme Right' => '右端',
'Left' => '左',
'Right' => '右',
'Top' => '上',
},
},
'AFPointSelected' => {
Description => 'AF測距点',
PrintConv => {
'Auto' => 'オート',
'Automatic Tracking AF' => '自動追尾',
'Bottom' => '下',
'Center' => '中央',
'Face Detect AF' => '顔認識',
'Fixed Center' => '中央固定',
'Left' => '左',
'Lower-left' => '左下',
'Lower-right' => '右下',
'Mid-left' => '中央左',
'Mid-right' => '中央右',
'Right' => '右',
'Top' => '上',
'Upper-left' => '左上',
'Upper-right' => '右上',
},
},
'AFPointSelected2' => {
Description => 'AF測距点選択2',
PrintConv => {
'Auto' => 'オート',
},
},
'AFPointSelection' => {
Description => 'AFポイント選択',
PrintConv => {
'11 Points' => '11点',
'51 Points' => '51点(3Dトラッキング)',
},
},
'AFPointSelectionMethod' => {
Description => 'AFフレーム選択方法',
PrintConv => {
'Multi-controller direct' => 'マルチコントローラーダイレクト',
'Normal' => '標準',
'Quick Control Dial direct' => 'サブ電子ダイヤルダイレクト',
},
},
'AFPointSpotMetering' => 'AFフレーム数/スポット測光',
'AFPoints' => 'AFポイント',
'AFPointsInFocus' => {
Description => 'AF測距点',
PrintConv => {
'All' => '全て',
'Bottom' => '下',
'Bottom, Center' => '下+中央',
'Bottom-center' => '中央下',
'Bottom-left' => '左下',
'Bottom-right' => '右下',
'Center' => '中央',
'Center (horizontal)' => '中央(水平)',
'Center (vertical)' => '中央(水平)',
'Center+Right' => '中央+右',
'Fixed Center or Multiple' => '中央固定または複数',
'Left' => '左',
'Left+Center' => '左+中央',
'Left+Right' => '左+右',
'Lower-left, Bottom' => '左下+下',
'Lower-left, Mid-left' => '左下+中央左',
'Lower-right, Bottom' => '右下+下',
'Lower-right, Mid-right' => '右下+中央右',
'Mid-left' => '中央左',
'Mid-left, Center' => '中央左+中央',
'Mid-right' => '中央右',
'Mid-right, Center' => '中央右+中央',
'None' => '無し',
'None (MF)' => '無し(MF)',
'Right' => '右',
'Top' => '上',
'Top, Center' => '上+中央',
'Top-center' => '中央上',
'Top-left' => '左上',
'Top-right' => '右上',
'Upper-left, Mid-left' => '左上+中央左',
'Upper-left, Top' => '左上+上',
'Upper-right, Mid-right' => '右上+中央右',
'Upper-right, Top' => '右上+上',
},
},
'AFPointsInFocus1D' => 'AF測距点(1D)',
'AFPointsInFocus5D' => 'AF測距点',
'AFPointsSelected' => 'AFポイント選択',
'AFPointsUnknown2' => {
Description => 'AF測距点 未確認2?',
PrintConv => {
'Auto' => 'オート',
},
},
'AFPointsUsed' => {
Description => 'AF測距点',
PrintConv => {
'Bottom' => '下',
'Center' => '中央',
'Mid-left' => '中央左',
'Mid-right' => '中央右',
'Top' => '上',
},
},
'AFPredictor' => 'AF予測',
'AFResponse' => 'AFレスポンス',
'AFResult' => 'AF結果',
'AFSearch' => {
Description => 'AFサーチ',
PrintConv => {
'Not Ready' => '準備ができていない',
'Ready' => '準備完了',
},
},
'AIServoContinuousShooting' => 'AI SERVO 連続撮影・撮影速度優先',
'AIServoImagePriority' => {
Description => 'AIサーボ1コマ目/2コマ目以降動作',
PrintConv => {
'1: AF, 2: Drive speed' => 'ピント優先/撮影速度優先',
'1: AF, 2: Tracking' => 'ピント優先/被写体追従優先',
'1: Release, 2: Drive speed' => 'レリーズ優先/撮影速度最優先',
},
},
'AIServoTrackingMethod' => {
Description => 'AIサーボ時の測距点選択特性',
PrintConv => {
'Continuous AF track priority' => '測距連続性優先',
'Main focus point priority' => '測距中心優先',
},
},
'AIServoTrackingSensitivity' => {
Description => 'AIサーボ時の被写体追従敏感度',
PrintConv => {
'Fast' => '速い',
'Slow' => '遅い',
'Standard' => 'スタンダード',
},
},
'APEVersion' => 'APEバージョン',
'ARMIdentifier' => 'ARM識別子',
'ARMVersion' => 'ARMバージョン',
'AToB0' => 'AからB0',
'AToB1' => 'AからB1',
'AToB2' => 'AからB2',
'AccessoryType' => 'アクセサリータイプ',
'ActionAdvised' => '動作推奨',
'ActiveArea' => 'アクティブ領域',
'ActiveD-Lighting' => {
Description => 'アクティブDライティング',
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Normal' => '標準',
'Off' => 'オフ',
'On' => 'オン',
},
},
'ActiveD-LightingMode' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Normal' => '標準',
'Off' => 'オフ',
},
},
'AddAspectRatioInfo' => {
Description => 'アスペクト比情報の付加',
PrintConv => {
'Off' => 'オフ',
},
},
'AddOriginalDecisionData' => {
Description => 'オリジナル画像判定用データの付加',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AdjustmentMode' => '調整モード',
'AdultContentWarning' => {
PrintConv => {
'Unknown' => '不明',
},
},
'AdvancedRaw' => {
Description => 'アドバンスRAW',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AdvancedSceneMode' => {
PrintConv => {
'Auto' => 'インテリジェントオート',
},
},
'Album' => 'アルバム',
'AlphaByteCount' => 'アルファバイト数',
'AlphaDataDiscard' => {
Description => 'アルファデータ破棄',
PrintConv => {
'Flexbits Discarded' => 'フレックスビット破棄',
'Full Resolution' => '完全な解像度',
'HighPass Frequency Data Discarded' => 'ハイパス周波数データ破棄',
'Highpass and LowPass Frequency Data Discarded' => 'ハイパスとローパス周波数データ破棄',
},
},
'AlphaOffset' => 'アルファオフセット',
'AnalogBalance' => 'アナログバランス',
'Annotations' => 'フォトショップ注釈',
'Anti-Blur' => {
PrintConv => {
'Off' => 'オフ',
'On (Continuous)' => 'オン(連写)',
'On (Shooting)' => 'オン(撮影)',
'n/a' => '該当無し',
},
},
'AntiAliasStrength' => 'カメラのアンチエイリアスフィルタの相対的な強度',
'Aperture' => '絞り',
'ApertureRange' => {
Description => '絞り数値の制御範囲の設定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ApertureRingUse' => {
Description => '絞りリングの使用',
PrintConv => {
'Permitted' => '許可',
'Prohibited' => '禁止',
},
},
'ApertureValue' => '絞り',
'ApplicationRecordVersion' => 'アプリケーションレコードバージョン',
'ApplyShootingMeteringMode' => {
Description => '撮影・測光モードの呼出',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'Artist' => '画像作成者',
'AsShotICCProfile' => '撮影時ICCプロファイル',
'AsShotNeutral' => 'ニュートラルショット',
'AsShotPreProfileMatrix' => '撮影時プロファイルマトリックス',
'AsShotProfileName' => '撮影時プロフィール名',
'AsShotWhiteXY' => 'ホワイトX-Yショット',
'AssignFuncButton' => {
Description => 'FUNC.ボタンの機能',
PrintConv => {
'Exposure comp./AEB setting' => '露出補正/AEB設定',
'Image jump with main dial' => 'メイン電子ダイヤル での画像送り',
'Image quality' => '記録画質選択',
'LCD brightness' => '液晶の明るさ',
'Live view function settings' => 'ライブビュー機能設定',
},
},
'AssistButtonFunction' => {
Description => 'アシストボタンの機能',
PrintConv => {
'Av+/- (AF point by QCD)' => 'Av±(サブ電子:AFフレーム選択)',
'FE lock' => 'FEロック',
'Normal' => '標準',
'Select HP (while pressing)' => 'HPに移動(押している間)',
'Select Home Position' => 'HPに移動',
},
},
'Audio' => {
Description => '音声',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'AudioDuration' => 'オーディオ時間',
'AudioOutcue' => 'オーディオ終了合図',
'AudioSamplingRate' => 'オーディオサンプリングレート',
'AudioSamplingResolution' => 'オーディオサンプリング解像度',
'AudioType' => 'オーディオタイプ',
'Author' => '作者',
'AuthorsPosition' => '役職名',
'AutoAperture' => {
Description => '自動絞り',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoBracket' => 'オートブラケット',
'AutoBracketModeM' => {
Description => 'オートブラケット(モードM)',
PrintConv => {
'Flash Only' => 'フラッシュのみ',
'Flash/Aperture' => 'フラッシュ/絞り',
'Flash/Speed' => 'フラッシュ/シャッター速度',
'Flash/Speed/Aperture' => 'フラッシュ/シャッター速度/絞り',
},
},
'AutoBracketOrder' => 'ブラケット順',
'AutoBracketSet' => {
Description => 'オートブラケット設定',
PrintConv => {
'AE & Flash' => '自動露出&フラッシュ',
'AE Only' => '自動露出のみ',
'Flash Only' => 'フラッシュのみ',
'WB Bracketing' => 'ホワイトバランスブラケット',
},
},
'AutoBracketing' => {
Description => 'オートブラケット',
PrintConv => {
'No flash & flash' => 'フラッシュ無し&フラッシュ有り',
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoExposureBracketing' => {
Description => 'フラッシュバイアス',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
'On (shot 1)' => 'オン(ショット1)',
'On (shot 2)' => 'オン(ショット2)',
'On (shot 3)' => 'オン(ショット3)',
},
},
'AutoFP' => {
Description => 'オートFP',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoFocus' => {
Description => 'オートフォーカス',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoISO' => {
Description => 'ISOオート',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoISOMax' => 'ISOオート 最大感度',
'AutoISOMinShutterSpeed' => 'ISOオート 最小シャッター速度',
'AutoLightingOptimizer' => {
Description => 'オートライティングオプティマイザ',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
'Low' => 'ソフト',
'Off' => 'オフ',
'Standard' => 'スタンダード',
'Strong' => '強',
'n/a' => '該当無し',
},
},
'AutoLightingOptimizerOn' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'AutoRedEye' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'AutoRotate' => {
Description => '自動回転',
PrintConv => {
'None' => '無し',
'Rotate 180' => '180度回転',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
'n/a' => 'ソフトウェアで回転',
},
},
'AuxiliaryLens' => '補助レンズ',
'AvApertureSetting' => 'Av絞り設定',
'AvSettingWithoutLens' => {
Description => 'レンズ未装着時の絞り数値設定',
PrintConv => {
'Disable' => '不可',
'Enable' => '可',
},
},
'BToA0' => 'BからA0',
'BToA1' => 'BからA1',
'BToA2' => 'BからA2',
'BWFilter' => '白黒フィルター',
'BWMode' => {
Description => '白黒モード',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'BabyAge' => '赤ちゃん/ペットの年齢',
'BackgroundColorIndicator' => '背景色指標',
'BackgroundColorValue' => '背景色値',
'BackgroundTiling' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'BadFaxLines' => '粗悪なFAX線',
'BannerImageType' => {
PrintConv => {
'None' => '無し',
},
},
'BaseExposureCompensation' => '基本露出補正',
'BaseISO' => 'ベース感度',
'BaselineExposure' => 'ベースライン露出',
'BaselineNoise' => 'ベースラインノイズ',
'BaselineSharpness' => 'ベースラインシャープネス',
'BatteryInfo' => '電源',
'BatteryLevel' => 'バッテリーレベル',
'BatteryOrder' => {
Description => 'バッテリー順',
PrintConv => {
'Camera Battery First' => 'カメラのバッテリーを最初に使う',
'MB-D10 First' => 'MB-D10のバッテリーを最初に使う',
},
},
'BayerGreenSplit' => 'ベイヤーグリーン分割',
'Beep' => {
Description => 'ビープ',
PrintConv => {
'High' => '高い',
'Low' => '低い',
'Off' => 'オフ',
'On' => 'オン',
},
},
'BestQualityScale' => '高品質スケール',
'BestShotMode' => {
Description => 'ベストショットモード',
PrintConv => {
'Off' => 'オフ',
},
},
'BitDepth' => 'ビット深度',
'BitsPerComponent' => 'コンポーネントあたりビット',
'BitsPerExtendedRunLength' => '拡張ランレングスあたりのビット',
'BitsPerRunLength' => 'ランレングスあたりのビット',
'BitsPerSample' => 'コンポーネントのビット数',
'BlackLevel' => '黒レベル',
'BlackLevel2' => '黒レベル2',
'BlackLevelDeltaH' => '黒レベルデルタH',
'BlackLevelDeltaV' => '黒レベルデルタV',
'BlackLevelRepeatDim' => '黒レベル反復値',
'BlackPoint' => '黒点',
'BlueBalance' => 'ブルーバランス',
'BlueMatrixColumn' => '青色マトリックス列',
'BlueTRC' => '青色調増殖曲線',
'BlurWarning' => {
Description => '手振れ警告',
PrintConv => {
'Blur Warning' => '手振れ警告',
'None' => '無し',
},
},
'BodyBatteryADLoad' => '電源A/D本体起動時',
'BodyBatteryADNoLoad' => '電源A/D本体オフ時',
'BodyBatteryState' => '電源状態本体',
'BodyFirmwareVersion' => '本体ファームウェアバージョン',
'BracketMode' => {
Description => 'ブラケットモード',
PrintConv => {
'Off' => 'オフ',
},
},
'BracketSequence' => 'ブラケットシーケンス',
'BracketShotNumber' => {
Description => 'ブラケットショット数',
PrintConv => {
'n/a' => '該当無し',
},
},
'BracketStep' => {
Description => 'ブラケットステップ',
PrintConv => {
'1 EV' => '1ステップ',
'1/3 EV' => '1/3ステップ',
'2/3 EV' => '2/3ステップ',
},
},
'BracketValue' => 'ブラケット値',
'Brightness' => 'ブライトネス',
'BrightnessData' => 'ブライトネスデータ',
'BrightnessValue' => 'ブライトネス',
'BulbDuration' => 'バルブ時間',
'BurstMode' => {
Description => 'ブラストモード',
PrintConv => {
'Infinite' => '無限',
'Off' => 'オフ',
'On' => 'オン',
},
},
'ButtonFunctionControlOff' => {
Description => 'サブ電子ダイヤル〈OFF〉時のボタン操作',
PrintConv => {
'Disable main, Control, Multi-control' => 'メイン電子ダイヤル、サブ電子ダイヤル、マルチコントローラーは無効',
'Normal (enable)' => '通常(有効)',
},
},
'By-line' => '製作者',
'By-lineTitle' => '製作者の職種',
'CCDScanMode' => {
Description => 'CCDスキャンモード',
PrintConv => {
'Interlaced' => 'インタレース',
'Progressive' => 'プログレッシブ',
},
},
'CFALayout' => 'CFAレイアウト',
'CFAPattern' => 'CFAパターン',
'CFAPattern2' => 'CFAパターン2',
'CFAPlaneColor' => 'CFAプレーン色',
'CFARepeatPatternDim' => 'CFA反復パターン特性',
'CLModeShootingSpeed' => 'CLモード撮影速度',
'CMContrast' => 'CMコントラスト',
'CMExposureCompensation' => 'CM露出補正',
'CMHue' => 'CM色相',
'CMMFlags' => 'CMMフラグ',
'CMSaturation' => 'CM彩度',
'CMSharpness' => 'CMシャープネス',
'CMWhiteBalance' => 'CMホワイトバランス',
'CMWhiteBalanceComp' => 'CMホワイトバランス補正',
'CMWhiteBalanceGrayPoint' => 'CMホワイトバランスグレーポイント',
'CMYKEquivalent' => 'CMYK等価物',
'CPUFirmwareVersion' => 'CPUファームウエアバージョン',
'CPUType' => {
PrintConv => {
'None' => '無し',
},
},
'CalibrationDateTime' => 'キャリブレーション日時',
'CalibrationIlluminant1' => {
Description => '光源キャリブレーション1',
PrintConv => {
'Cloudy' => '曇り',
'Cool White Fluorescent' => '白色蛍光灯',
'Day White Fluorescent' => '昼白色蛍光灯',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Fine Weather' => '良い天気',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'ISO Studio Tungsten' => 'ISOスタジオタングステン',
'Other' => 'その他の光源',
'Shade' => '日陰',
'Standard Light A' => '標準ライトA',
'Standard Light B' => '標準ライトB',
'Standard Light C' => '標準ライトC',
'Tungsten (Incandescent)' => 'タングステン(白熱灯)',
'Unknown' => '不明',
'Warm White Fluorescent' => '暖白光色蛍光灯',
'White Fluorescent' => '温白色蛍光灯',
},
},
'CalibrationIlluminant2' => {
Description => '光源キャリブレーション2',
PrintConv => {
'Cloudy' => '曇り',
'Cool White Fluorescent' => '白色蛍光灯',
'Day White Fluorescent' => '昼白色蛍光灯',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Fine Weather' => '良い天気',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'ISO Studio Tungsten' => 'ISOスタジオタングステン',
'Other' => 'その他の光源',
'Shade' => '日陰',
'Standard Light A' => '標準ライトA',
'Standard Light B' => '標準ライトB',
'Standard Light C' => '標準ライトC',
'Tungsten (Incandescent)' => 'タングステン(白熱灯)',
'Unknown' => '不明',
'Warm White Fluorescent' => '暖白光色蛍光灯',
'White Fluorescent' => '温白色蛍光灯',
},
},
'CameraCalibration1' => 'カメラキャリブレーション1',
'CameraCalibration2' => 'カメラキャリブレーション2',
'CameraCalibrationSig' => 'カメラキャリブレーションサイン',
'CameraID' => 'カメラID',
'CameraISO' => 'カメラISO',
'CameraInfo' => 'ペンタックスモデル',
'CameraOrientation' => {
Description => '画像の向き',
PrintConv => {
'Horizontal (normal)' => '水平(標準)',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
},
},
'CameraParameters' => 'カメラパラメーター',
'CameraSerialNumber' => 'カメラシリアル番号',
'CameraSettings' => 'カメラ設定',
'CameraSettingsVersion' => 'カメラ設定バージョン',
'CameraTemperature' => 'カメラ温度',
'CameraType' => {
Description => 'カメラタイプ',
PrintConv => {
'Compact' => 'コンパクト',
'DV Camera' => 'DVカメラ',
'EOS High-end' => 'EOSハイエンド',
'EOS Mid-range' => 'EOSミドルレンジ',
},
},
'CameraType2' => 'カメラタイプ2',
'CanonAFInfo' => 'AF情報',
'CanonAFInfo2' => 'AF情報2',
'CanonExposureMode' => {
Description => '露出モード',
PrintConv => {
'Aperture-priority AE' => '絞り優先',
'Bulb' => 'バルブ',
'Depth-of-field AE' => '被写界深度AE',
'Easy' => '簡単',
'Manual' => 'マニュアル',
'Program AE' => 'プログラムAE',
'Shutter speed priority AE' => 'シャッター優先',
},
},
'CanonFileInfo' => 'ファイル情報',
'CanonFileLength' => 'ファイル長',
'CanonFirmwareVersion' => 'ファームウェアバージョン',
'CanonFlashMode' => {
Description => 'フラッシュモード',
PrintConv => {
'Auto' => 'オート',
'External flash' => '外付フラッシュ',
'Off' => 'オフ',
'On' => 'オン',
'Red-eye reduction' => '赤目軽減',
'Red-eye reduction (Auto)' => '赤目軽減(オート)',
'Red-eye reduction (On)' => '赤目軽減(オン)',
'Slow-sync' => 'スローシンクロ',
},
},
'CanonFocalLength' => 'フォーカスタイプ',
'CanonImageHeight' => '画像高さ',
'CanonImageSize' => {
Description => 'イメージサイズ',
PrintConv => {
'Large' => 'ラージ',
'Medium' => 'ミドル',
'Medium 1' => 'ミドル1',
'Medium 2' => 'ミドル2',
'Medium 3' => 'ミドル3',
'Medium Movie' => 'ミディアム動画',
'Postcard' => 'ハガキ',
'Small' => 'スモール',
'Small 1' => 'スモール1',
'Small 2' => 'スモール2',
'Small 3' => 'スモール3',
'Small Movie' => 'スモール動画',
'Widescreen' => 'ワイド画面',
},
},
'CanonImageType' => 'イメージタイプ',
'CanonImageWidth' => '画像幅',
'CanonModelID' => 'モデルID',
'Caption-Abstract' => '表題/説明',
'CaptionWriter' => 'キャプション作成者',
'CasioImageSize' => 'カシオイメージサイズ',
'Categories' => 'カテゴリー',
'Category' => 'カテゴリー',
'CellLength' => 'セル長',
'CellWidth' => 'セル幅',
'CenterAFArea' => {
Description => '中央AFエリア',
PrintConv => {
'Normal Zone' => 'ノーマルゾーン',
'Wide Zone' => 'ワイドゾーン',
},
},
'CenterWeightedAreaSize' => {
Description => '中央重点エリア',
PrintConv => {
'Average' => '平均',
},
},
'CharTarget' => '目的文字',
'CharacterSet' => 'キャラクターセット',
'ChromaBlurRadius' => '彩度ぼけ半径',
'ChromaticAdaptation' => '色彩順応化',
'Chromaticity' => '色度',
'ChrominanceNR_TIFF_JPEG' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Off' => 'オフ',
},
},
'ChrominanceNoiseReduction' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Off' => 'オフ',
},
},
'City' => '都市',
'ClassifyState' => '分類状態',
'CleanFaxData' => '純粋なFAXデータ',
'ClipPath' => 'クリップパス',
'CodedCharacterSet' => 'キャラクタセットコード',
'ColorAberrationControl' => {
Description => '色収差コントロール',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ColorAdjustment' => '色調整',
'ColorAdjustmentMode' => {
Description => '色調整モード',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ColorBalance' => 'カラーバランス',
'ColorBalanceAdj' => {
Description => 'カラーバランス調整',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ColorBalanceBlue' => 'カラーバランス青',
'ColorBalanceGreen' => 'カラーバランス緑',
'ColorBalanceRed' => 'カラーバランス赤',
'ColorBoostData' => 'カラーブーストデータ',
'ColorBoostLevel' => 'カラーブーストレベル1',
'ColorBoostType' => {
Description => 'カラーブーストタイプ',
PrintConv => {
'Nature' => '自然',
'People' => '人々',
},
},
'ColorBooster' => {
Description => 'カラーブースター',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ColorCalibrationMatrix' => 'カラーキャリブレーションマトリックステーブル',
'ColorCharacterization' => 'カラー特徴描写',
'ColorControl' => 'カラーコントロール',
'ColorEffect' => {
Description => 'カラーエフェクト',
PrintConv => {
'Black & White' => '白黒',
'Cool' => '冷色',
'Off' => 'オフ',
'Sepia' => 'セピア',
'Warm' => '暖色',
},
},
'ColorFilter' => {
Description => 'カラーフィルター',
PrintConv => {
'Black & White' => '白黒',
'Blue' => '青',
'Green' => '緑',
'Off' => 'オフ',
'Pink' => 'ピンク',
'Purple' => '紫',
'Red' => '赤',
'Sepia' => 'セピア',
'Yellow' => '黄色',
},
},
'ColorGain' => 'カラーゲイン',
'ColorHue' => '色相',
'ColorInfo' => '色情報',
'ColorMap' => 'カラーマップ',
'ColorMatrix' => 'カラーマトリックス',
'ColorMatrix1' => 'カラーマトリックス1',
'ColorMatrix2' => 'カラーマトリックス2',
'ColorMatrixNumber' => 'カラーマトリックス番号',
'ColorMode' => {
Description => 'カラーモード',
PrintConv => {
'Autumn Leaves' => '紅葉',
'B & W' => '白黒',
'B&W' => '白黒',
'Black & White' => '白黒',
'Chrome' => 'クローム',
'Clear' => 'クリアー',
'Deep' => 'ディープ',
'Evening' => '夕焼け',
'Landscape' => '風景',
'Light' => 'ライト',
'Natural' => 'ナチュラル',
'Natural color' => 'ナチュラルカラー',
'Natural sRGB' => 'ナチュラル sRGB',
'Natural+ sRGB' => 'ナチュラル+ sRGB',
'Neutral' => 'ニュートラル',
'Night Portrait' => '人物夜景',
'Night Scene' => '夜景',
'Night View' => 'ナイトビュー',
'Night View/Portrait' => '夜景/夜景ポートレート',
'Normal' => 'ノーマル',
'Off' => 'オフ',
'Portrait' => 'ポートレート',
'Sepia' => 'セピア',
'Solarization' => 'ソラリゼーション',
'Standard' => 'スタンダード',
'Sunset' => '夕日',
'Vivid' => 'ビビッド',
'Vivid color' => 'ビビッドカラー',
},
},
'ColorMoireReduction' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ColorMoireReductionMode' => {
Description => '色モアレリダクション',
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Off' => 'オフ',
},
},
'ColorPalette' => 'カラーパレット',
'ColorProfile' => {
Description => 'カラープロフィール',
PrintConv => {
'Embedded' => '埋め込み',
'Not Embedded' => '埋め込み無し',
},
},
'ColorRepresentation' => '色表現',
'ColorReproduction' => '色再現',
'ColorResponseUnit' => '色応答単位',
'ColorSequence' => 'カラーシーケンス',
'ColorSpace' => {
Description => '色空間',
PrintConv => {
'ICC Profile' => 'ICCプロフィール',
'Monochrome' => 'モノトーン',
'Uncalibrated' => '未調整',
},
},
'ColorSpaceData' => 'カラースペースデータ',
'ColorTable' => 'カラーテーブル',
'ColorTemperature' => '色温度',
'ColorTone' => {
Description => 'カラートーン',
PrintConv => {
'Normal' => '標準',
},
},
'ColorToneFaithful' => 'カラートーン忠実設定',
'ColorToneLandscape' => 'カラートーン風景',
'ColorToneNeutral' => 'カラートーンニュートラル',
'ColorTonePortrait' => 'カラートーンポートレート',
'ColorToneStandard' => 'カラートーンスタンダード',
'ColorToneUserDef1' => 'カラートーンユーザ設定1',
'ColorToneUserDef2' => 'カラートーンユーザ設定2',
'ColorToneUserDef3' => 'カラートーンユーザ設定3',
'ColorantOrder' => '着色順',
'ColorantTable' => '着色テーブル',
'ColorimetricReference' => '比色分析参照',
'CommandDials' => {
Description => 'コマンダーダイヤル',
PrintConv => {
'Reversed (Main Aperture, Sub Shutter)' => 'リバース',
'Standard (Main Shutter, Sub Aperture)' => 'デフォルト',
},
},
'CommandDialsApertureSetting' => {
Description => 'コマンドダイヤルカスタマイズ 絞り設定',
PrintConv => {
'Aperture Ring' => '絞りリング',
'Sub-command Dial' => 'サブコントロールダイヤル',
},
},
'CommandDialsChangeMainSub' => {
Description => 'コマンドダイヤルカスタマイズ メイン/サブ変更',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'CommandDialsMenuAndPlayback' => {
Description => 'コマンドダイヤルカスタマイズ メニューと再生',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'CommandDialsReverseRotation' => {
Description => 'コマンドダイヤルカスタマイズ 回転保持',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'CommanderChannel' => 'コマンダーモード チャンネル',
'CommanderGroupAManualOutput' => 'コマンダーモード グループA M 補正',
'CommanderGroupAMode' => {
Description => 'コマンダーモード グループA モード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
},
},
'CommanderGroupA_TTL-AAComp' => 'コマンダーモード 内蔵フラッシュ TTL/AA 補正',
'CommanderGroupBManualOutput' => 'コマンダーモード グループB M 補正',
'CommanderGroupBMode' => {
Description => 'コマンダーモード グループB モード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
},
},
'CommanderGroupB_TTL-AAComp' => 'コマンダーモード グループB TTL/AA 補正',
'CommanderInternalFlash' => {
Description => 'コマンダーモード 内蔵フラッシュ モード',
PrintConv => {
'Manual' => 'マニュアル',
'Off' => 'オフ',
},
},
'CommanderInternalManualOutput' => 'コマンダーモード 内蔵フラッシュ M 補正',
'CommanderInternalTTLComp' => 'コマンダーモード 内蔵フラッシュ TTL 補正',
'Comment' => 'コメント',
'Compilation' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ComponentsConfiguration' => '各構成要素の意味',
'CompressedBitsPerPixel' => '画像圧縮モード',
'CompressedImageSize' => '圧縮画像サイズ',
'Compression' => {
Description => '圧縮計画',
PrintConv => {
'JPEG' => 'JPEG圧縮率',
'JPEG (old-style)' => 'JPEG(古い形式)',
'None' => '無し',
'Uncompressed' => '非圧縮',
},
},
'CompressionRatio' => '圧縮率',
'CompressionType' => {
PrintConv => {
'None' => '無し',
},
},
'ConditionalFEC' => 'フラッシュ露出補正',
'ConnectionSpaceIlluminant' => '接続スペース光源',
'ConsecutiveBadFaxLines' => '連続的に粗悪なFAX線',
'Contact' => '連絡',
'ContentLocationCode' => '内容位置コード',
'ContentLocationName' => '内容位置名',
'ContinuousDrive' => {
Description => 'ドライブモード',
PrintConv => {
'Continuous' => '連続撮影',
'Continuous, High' => '連写(High)',
'Continuous, Low' => '連写(Low)',
'Continuous, Speed Priority' => '高速連写',
'Movie' => '動画',
'Single' => '1コマ撮影',
},
},
'ContinuousShootingSpeed' => {
Description => '連続撮影速度',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ContinuousShotLimit' => {
Description => '連続撮影時の撮影枚数制限',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'Contrast' => {
Description => 'コントラスト',
PrintConv => {
'Film Simulation' => 'フィルムシミュレーション',
'High' => 'ハード',
'Low' => 'ソフト',
'Med High' => '少し高い',
'Med Low' => '少し低い',
'Medium High' => '少し高い',
'Medium Low' => '少し低い',
'Normal' => 'スタンダード',
'Very High' => 'かなり高い',
'Very Low' => 'かなり低い',
},
},
'ContrastCurve' => 'コントラストカーブ',
'ContrastFaithful' => 'コントラスト忠実設定',
'ContrastLandscape' => 'コントラスト風景',
'ContrastMonochrome' => 'コントラストモノクロ',
'ContrastNeutral' => 'コントラストニュートラル',
'ContrastPortrait' => 'コントラストポートレート',
'ContrastSetting' => 'コントラスト設定',
'ContrastStandard' => 'コントラストスタンダード',
'ContrastUserDef1' => 'コントラストユーザ設定1',
'ContrastUserDef2' => 'コントラストユーザ設定2',
'ContrastUserDef3' => 'コントラストユーザ設定3',
'ControlMode' => {
Description => 'コントロールモード',
PrintConv => {
'Camera Local Control' => 'カメラローカルコントロール',
'Computer Remote Control' => 'コンピュータリモートコントロール',
'n/a' => '該当無し',
},
},
'ConversionLens' => {
Description => 'コンバージョンレンズ',
PrintConv => {
'Macro' => 'マクロ',
'Off' => 'オフ',
'Telephoto' => 'テレフォト',
'Wide' => 'ワイド',
},
},
'Converter' => 'コンバーター',
'Copyright' => '版権所有者',
'CopyrightNotice' => '著作権表示',
'CopyrightStatus' => {
PrintConv => {
'Unknown' => '不明',
},
},
'CoringFilter' => 'コアリングフィルタ',
'CoringValues' => 'コアリング値',
'Country' => '国名',
'Country-PrimaryLocationCode' => 'ISO国コード',
'Country-PrimaryLocationName' => '国',
'CreateDate' => 'デジタルデータ作成日時',
'CreationDate' => '作成日時',
'CreativeStyle' => {
Description => 'クリエイティブスタイル',
PrintConv => {
'Autumn' => '秋',
'Autumn Leaves' => '紅葉',
'B&W' => '白黒',
'Clear' => 'クリアー',
'Deep' => 'ディープ',
'Landscape' => '風景',
'Light' => 'ライト',
'Neutral' => 'ニュートラル',
'Night View/Portrait' => '夜景/夜景ポートレート',
'Portrait' => 'ポートレート',
'Sepia' => 'セピア',
'Standard' => 'スタンダード',
'Sunset' => '夕日',
'Vivid' => 'ビビッド',
},
},
'Creator' => '製作者',
'CreatorAddress' => 'クリエーター - 住所',
'CreatorCity' => 'クリエーター - 街',
'CreatorCountry' => 'クリエーター - 国',
'CreatorPostalCode' => 'クリエーター - 郵便番号',
'CreatorRegion' => 'クリエーター - 国/州',
'CreatorWorkEmail' => 'クリエーター - 電子メール',
'CreatorWorkTelephone' => 'クリエーター - 電話番号',
'CreatorWorkURL' => 'クリエーター - WEBサイト',
'Credit' => 'プロバイダー',
'CropActive' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'CropData' => 'クロップデータ',
'CropHeight' => '最終高さ',
'CropHiSpeed' => 'ハイスピードクロップ',
'CropLeft' => '開始オフセットX',
'CropTop' => '開始オフセットY',
'CropWidth' => '最終幅',
'CurrentICCProfile' => 'カレントICCプロファイル',
'CurrentPreProfileMatrix' => 'カレントプロファイルマトリックス',
'Curves' => {
Description => 'カーブ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Custom1' => 'カスタム1',
'Custom2' => 'カスタム2',
'Custom3' => 'カスタム3',
'Custom4' => 'カスタム4',
'CustomRendered' => {
Description => 'カスタム画像処理',
PrintConv => {
'Custom' => 'カスタム処理',
'Normal' => '標準処理',
},
},
'CustomSaturation' => 'カスタム彩度',
'D-LightingHQ' => {
Description => 'DライティングHQ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'D-LightingHQColorBoost' => 'DライティングHQカラーブースト',
'D-LightingHQHighlight' => 'DライティングHQハイライト',
'D-LightingHQSelected' => {
Description => 'DライティングHQ選択',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'D-LightingHQShadow' => 'DライティングHQシャドウ',
'D-LightingHS' => {
Description => 'DライティングHS',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'D-LightingHSAdjustment' => 'DライティングHS調整',
'D-LightingHSColorBoost' => 'DライティングHSカラーブースト',
'DECPosition' => {
Description => 'DEC位置',
PrintConv => {
'Contrast' => 'コントラスト',
'Exposure' => '露出',
'Filter' => 'フィルター',
'Saturation' => '彩度',
},
},
'DNGBackwardVersion' => 'DNGバックワードバージョン',
'DNGLensInfo' => 'レンズ情報',
'DNGVersion' => 'DNGバージョン',
'DSPFirmwareVersion' => 'DSPファームウエアバージョン',
'DataCompressionMethod' => 'データ圧縮アルゴリズム プロバイダー/オーナー',
'DataDump' => 'データダンプ',
'DataImprint' => {
Description => 'データインプリント',
PrintConv => {
'None' => '無し',
'Text' => 'テキスト',
},
},
'DataType' => '日付型',
'Date' => '日付',
'DateCreated' => '作成日付',
'DateDisplayFormat' => {
Description => '日付形式',
PrintConv => {
'D/M/Y' => '日/月/年',
'M/D/Y' => '月/日/年',
'Y/M/D' => '年/月/日',
},
},
'DateSent' => '発送日付',
'DateStampMode' => {
Description => '日付スタンプモード',
PrintConv => {
'Date' => '日付',
'Off' => 'オフ',
},
},
'DateTime' => 'ファイル作成日時',
'DateTimeOriginal' => 'オリジナルデータ作成日時',
'DaylightSavings' => {
Description => '夏時間',
PrintConv => {
'No' => 'オフ',
'Yes' => 'オン',
},
},
'DefaultCropOrigin' => 'デフォルト切取り基点',
'DefaultCropSize' => 'デフォルト切取りサイズ',
'DefaultScale' => 'デフォルトスケール',
'DeletedImageCount' => '削除イメージカウント',
'Description' => '説明',
'Destination' => '宛先',
'DestinationCity' => '目的地',
'DestinationCityCode' => '目的地コード',
'DestinationDST' => {
Description => '目的地DST',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'DevelopmentDynamicRange' => '進化ダイナミックレンジ',
'DeviceAttributes' => '機器属性',
'DeviceManufacturer' => '機器メーカー',
'DeviceMfgDesc' => '機器メーカー説明',
'DeviceModel' => '機器モデル',
'DeviceModelDesc' => '機器モデル説明',
'DeviceSettingDescription' => 'デバイス設定の説明',
'DialDirectionTvAv' => {
Description => 'Tv/Av値設定時のダイヤル回転',
PrintConv => {
'Normal' => '通常',
'Reversed' => '設定方向を反転',
},
},
'DigitalCreationDate' => 'デジタル作成日付',
'DigitalCreationTime' => 'デジタル作成時間',
'DigitalGEM' => 'デジタルGEM',
'DigitalICE' => 'デジタルICE',
'DigitalROC' => 'デジタルROC',
'DigitalZoom' => {
Description => 'デジタルズーム',
PrintConv => {
'None' => '無し',
'Off' => 'オフ',
'Other' => '未確認',
},
},
'DigitalZoomOn' => {
Description => 'デジタルズームオン',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'DigitalZoomRatio' => 'デジタルズーム比率',
'Directory' => 'ファイルの場所',
'DirectoryIndex' => 'ディレクトリ索引',
'DirectoryNumber' => 'ディレクトリ番号',
'DisplayAperture' => '絞り表示',
'DisplaySize' => {
PrintConv => {
'Normal' => '標準',
},
},
'DistortionCorrection' => {
Description => '歪曲修正',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'DistortionCorrection2' => {
Description => '歪曲補正編集',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'DjVuVersion' => 'DjVuバージョン',
'DocumentHistory' => '文書履歴',
'DocumentName' => 'ドキュメント名',
'DocumentNotes' => '文書ノート',
'DotRange' => 'ドット範囲',
'DriveMode' => {
Description => 'ドライブモード',
PrintConv => {
'Bracketing' => 'ブラケット',
'Burst' => '高速連射',
'Continuous' => '連続撮影',
'Continuous High' => '連射 (Hi)',
'Continuous Shooting' => '連続撮影',
'HS continuous' => 'HS連写',
'Interval' => 'インターバル',
'Multiple Exposure' => '複数の露出',
'No Timer' => 'タイマー無し',
'Off' => 'オフ',
'Remote Control' => 'リモコン',
'Remote Control (3 s delay)' => 'リモコン (3秒後レリーズ)',
'Self-timer' => 'セルフタイマー',
'Self-timer (12 s)' => 'セルフタイマー (12秒)',
'Self-timer (2 s)' => 'セルフタイマー (2秒)',
'Self-timer Operation' => 'セルフタイマー',
'Shutter Button' => 'シャッターボタン',
'Single' => '1コマ撮影',
'Single Exposure' => 'シングル露出',
'Single Frame' => '1コマ撮影',
'Single Shot' => '1コマ撮影',
'Single-frame' => '1コマ撮影',
'Single-frame Shooting' => '1コマ撮影',
'UHS continuous' => 'UHS連写',
},
},
'DriveMode2' => {
Description => '多重露光',
PrintConv => {
'Single-frame' => '1コマ撮影',
},
},
'DynamicAFArea' => {
Description => 'ダイナミックAFエリア',
PrintConv => {
'21 Points' => '21点',
'51 Points' => '51点',
'51 Points (3D-tracking)' => '51点(3Dトラッキング)',
'9 Points' => '9点',
},
},
'DynamicRange' => {
Description => 'ダイナミックレンジ',
PrintConv => {
'Standard' => 'スタンダード',
'Wide' => 'ワイド',
},
},
'DynamicRangeExpansion' => {
Description => 'ダイナミックレンジ拡大',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'DynamicRangeOptimizer' => {
Description => 'Dレンジオプティマイザー',
PrintConv => {
'Advanced Auto' => 'アドバンスオート',
'Advanced Lv1' => 'アドバンスLv1',
'Advanced Lv2' => 'アドバンスLv2',
'Advanced Lv3' => 'アドバンスLv3',
'Advanced Lv4' => 'アドバンスLv4',
'Advanced Lv5' => 'アドバンスLv5',
'Auto' => 'オート',
'Off' => 'オフ',
'Standard' => 'スタンダード',
},
},
'DynamicRangeSetting' => 'ダイナミックレンジ設定',
'E-DialInProgram' => {
Description => '電子ダイヤルプログラム',
PrintConv => {
'P Shift' => 'Pシフト',
'Tv or Av' => 'TvかAv',
},
},
'ETTLII' => {
PrintConv => {
'Average' => '平均',
'Evaluative' => '評価',
},
},
'EVStepInfo' => 'EVステップ情報',
'EVStepSize' => {
Description => 'EVステップ',
PrintConv => {
'1/2 EV' => '1/2ステップ',
'1/3 EV' => '1/3ステップ',
},
},
'EVSteps' => {
Description => '露出ステップ',
PrintConv => {
'1/2 EV Steps' => '1/2 EVステップ',
'1/3 EV Steps' => '1/3 EVステップ',
},
},
'EasyExposureCompensation' => {
Description => '簡単な露出補正',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
'On (auto reset)' => 'オン(自動リセット)',
},
},
'EasyMode' => {
Description => '簡単モード',
PrintConv => {
'Aquarium' => '水族館',
'Beach' => 'ビーチ',
'Black & White' => '白黒',
'Color Accent' => 'カラーアクセント',
'Color Swap' => 'スイッチカラー',
'Digital Macro' => 'デジタルマクロ',
'Fast shutter' => '高速シャッター',
'Fireworks' => '花火',
'Flash Off' => 'フラッシュオフ',
'Foliage' => '葉',
'Full auto' => 'フルオート',
'Gray Scale' => 'グレースケール',
'ISO 3200' => 'ISO3200',
'Indoor' => '室内',
'Kids & Pets' => 'キッズ&ペット',
'Landscape' => '風景',
'Long Shutter' => '長秒シャッター',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'My Colors' => 'ワンポイントカラー',
'Neutral' => 'ニュートラル',
'Night' => '夜景',
'Night Scene' => '夜景',
'Night Snapshot' => 'ナイトスナップ',
'Pan focus' => 'パンフォーカス',
'Portrait' => 'ポートレート',
'Sepia' => 'セピア',
'Slow shutter' => 'スローシャッター',
'Snow' => 'スノー',
'Sports' => 'スポーツ',
'Still Image' => '静止画像',
'Sunset' => '夕焼け',
'Super Macro' => 'スーパーマクロ',
'Underwater' => '水中',
'Vivid' => 'ビビッド',
},
},
'EdgeNoiseReduction' => {
Description => 'エッジノイズリダクション',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'EditStatus' => '編集状態',
'EditorialUpdate' => {
Description => '更新編集',
PrintConv => {
'Additional language' => '追加言語',
},
},
'EffectiveLV' => '効果レベル',
'Emphasis' => {
PrintConv => {
'None' => '無し',
},
},
'EncodingProcess' => 'JPEGの符号化処理',
'EndPoints' => '末端',
'EnhanceDarkTones' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Enhancement' => {
Description => '強度',
PrintConv => {
'Blue' => '青',
'Flesh Tones' => '肌調',
'Green' => '緑',
'Off' => 'オフ',
'Red' => '赤',
},
},
'Enhancer' => '増大値2',
'EnhancerValues' => '増大値',
'EnvelopeNumber' => 'エンベロープ数',
'EnvelopePriority' => {
Description => 'エンベロープ優先度',
PrintConv => {
'0 (reserved)' => '0 (将来拡張用)',
'1 (most urgent)' => '1 (高い緊急性)',
'5 (normal urgency)' => '5 (普通の緊急性)',
'8 (least urgent)' => '8 (低い緊急性)',
'9 (user-defined priority)' => '9 (ユーザ定義優先度)',
},
},
'EnvelopeRecordVersion' => 'エンベロープレコードバージョン',
'EpsonImageHeight' => 'エプソン画像高',
'EpsonImageWidth' => 'エプソン画像幅',
'EpsonSoftware' => 'エプソンソフトウェア',
'Equipment' => 'イクイップメントIFDポインター',
'EquipmentVersion' => 'イクイップメントバージョン',
'ExcursionTolerance' => '振幅許容範囲',
'ExifCameraInfo' => 'Exifカメラ情報',
'ExifImageHeight' => '画像高さ',
'ExifImageWidth' => '画像幅',
'ExifOffset' => 'Exif IFDへのポインタ',
'ExifToolVersion' => 'ExifToolバージョン',
'ExifVersion' => 'Exifバージョン',
'ExpandFilm' => '拡張フイルム',
'ExpandFilterLens' => '拡張レンズフィルター',
'ExpandFlashLamp' => '拡張フラッシュランプ',
'ExpandLens' => '拡張レンズ',
'ExpandScanner' => '拡張スキャナー',
'ExpandSoftware' => '拡張ソフト',
'ExpirationDate' => '有効日付',
'ExpirationTime' => '有効時間',
'Exposure' => '露出',
'ExposureBracketStepSize' => '露出ブラケットステップサイズ',
'ExposureBracketValue' => '露出ブラケット値',
'ExposureCompStepSize' => {
Description => '露出補正/ファインチューン',
PrintConv => {
'1 EV' => '1ステップ',
'1/2 EV' => '1/2ステップ',
'1/3 EV' => '1/3ステップ',
},
},
'ExposureCompensation' => '露出補正値',
'ExposureControlStepSize' => {
Description => '露出制御のEVステップ',
PrintConv => {
'1 EV' => '1ステップ',
'1/2 EV' => '1/2ステップ',
'1/3 EV' => '1/3ステップ',
},
},
'ExposureDelayMode' => {
Description => '露出遅延モード',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ExposureDifference' => '露出差',
'ExposureIndex' => '露出指標',
'ExposureLevelIncrements' => {
Description => '露出制御のEVステップ',
PrintConv => {
'1-stop set, 1/3-stop comp.' => '設定1 露出補正1/3',
'1/2 Stop' => '1/2ステップ',
'1/2-stop set, 1/2-stop comp.' => '設定1/2 露出補正1/2',
'1/3 Stop' => '1/3ステップ',
'1/3-stop set, 1/3-stop comp.' => '設定1/3 露出補正1/3',
},
},
'ExposureMode' => {
Description => '露光モード',
PrintConv => {
'Aperture Priority' => '絞り優先',
'Aperture-priority AE' => '絞り優先',
'Auto' => '自動露出',
'Auto bracket' => 'オートブラケット',
'Bulb' => 'バルブ',
'Landscape' => '風景',
'Manual' => 'マニュアル露出',
'Night Scene / Twilight' => '夜景',
'Portrait' => 'ポートレート',
'Program' => 'プログラム',
'Program AE' => 'プログラムAE',
'Program-shift' => 'プログラムシフト',
'Shutter Priority' => 'シャッター優先',
'Shutter speed priority AE' => 'シャッター優先',
'n/a' => '未設定',
},
},
'ExposureModeInManual' => {
Description => 'マニュアル露出時の測光モード',
PrintConv => {
'Center-weighted average' => '中央重点',
'Evaluative metering' => '評価測光',
'Partial metering' => '部分',
'Specified metering mode' => '設定測光モード',
'Spot metering' => 'スポット',
},
},
'ExposureProgram' => {
Description => '露出プログラム',
PrintConv => {
'Action (High speed)' => 'スポーツモード(高速シャッター優先)',
'Aperture Priority' => '絞り優先',
'Aperture-priority AE' => '絞り優先',
'Bulb' => 'バルブ',
'Creative (Slow speed)' => 'クリエイティブプログラム(被写界深度優先)',
'Landscape' => '風景モード',
'Manual' => 'マニュアル',
'Not Defined' => '未定義',
'Portrait' => 'ポートレートモード',
'Program' => 'プログラム',
'Program AE' => 'ノーマルプログラム',
'Shutter Priority' => 'シャッター優先',
'Shutter speed priority AE' => 'シャッター優先',
},
},
'ExposureTime' => '露出時間',
'ExposureTime2' => '露出時間 2',
'ExposureWarning' => {
Description => '露出警告',
PrintConv => {
'Bad exposure' => '露出失敗',
'Good' => '適正',
},
},
'ExtendedWBDetect' => {
Description => '延長WB検出',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Extender' => 'エクステンダー',
'ExtenderFirmwareVersion' => 'エクステンダーファームウェアバージョン',
'ExtenderModel' => 'エクステンダーモデル',
'ExtenderSerialNumber' => 'エクステンダーシリアル番号',
'ExternalFlash' => {
Description => '外付フラッシュ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ExternalFlashAE1' => '外付フラッシュAE1?',
'ExternalFlashAE1_0' => '外付フラッシュAE1(0)?',
'ExternalFlashAE2' => '外付フラッシュAE2?',
'ExternalFlashAE2_0' => '外付フラッシュAE2(0)?',
'ExternalFlashBounce' => {
Description => '外付フラッシュバウンス',
PrintConv => {
'Bounce' => 'バウンス',
'Bounce or Off' => 'バウンスかオフ',
'Direct' => 'ダイレクト',
'No' => 'いいえ',
'Yes' => 'はい',
'n/a' => '該当無し',
},
},
'ExternalFlashExposureComp' => {
Description => '外付ストロボ露出補正',
PrintConv => {
'n/a' => '未設定(オフかオートモード)',
'n/a (Manual Mode)' => '未設定(マニュアルモード)',
},
},
'ExternalFlashFlags' => '外付フラッシュフラグ',
'ExternalFlashGuideNumber' => '外付フラッシュガイドナンバー?',
'ExternalFlashMode' => {
Description => '外付フラッシュモード',
PrintConv => {
'Off' => 'オフ',
'On, Auto' => 'オン、オート',
'On, Contrast-control Sync' => 'オン、光量比制御シンクロ',
'On, Flash Problem' => 'オン、フラッシュの問題?',
'On, High-speed Sync' => 'オン、ハイスピードシンクロ',
'On, Manual' => 'オン、マニュアル',
'On, P-TTL Auto' => 'オン、P-TTLオート',
'On, Wireless' => 'オン、ワイヤレス',
'On, Wireless, High-speed Sync' => 'オン、ワイヤレス、ハイスピードシンクロ',
'n/a - Off-Auto-Aperture' => '該当なし-自動絞りオフ',
},
},
'ExternalFlashZoom' => '外付フラッシュズーム',
'ExtraSamples' => '特別サンプル',
'FNumber' => 'F値',
'Face0Position' => '顔0位置',
'Face1Position' => '顔1位置',
'Face2Position' => '顔2位置',
'Face3Position' => '顔3位置',
'Face4Position' => '顔4位置',
'Face5Position' => '顔5位置',
'Face6Position' => '顔6位置',
'Face7Position' => '顔7位置',
'Face8Position' => '顔8位置',
'Face9Position' => '顔9位置',
'FaceDetect' => {
Description => '顔認識',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FaceDetectArea' => '顔エリア',
'FaceDetectFrameSize' => 'フレームサイズ',
'FaceOrientation' => {
PrintConv => {
'Horizontal (normal)' => '水平(標準)',
'Rotate 180' => '180度回転',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
},
},
'FacesDetected' => '顔認識',
'FastSeek' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'FaxProfile' => {
PrintConv => {
'Unknown' => '不明',
},
},
'FaxRecvParams' => 'FAX受信パラメータ',
'FaxRecvTime' => 'FAX受信時間',
'FaxSubAddress' => 'FAXサブアドレス',
'FileFormat' => 'ファイル形式',
'FileIndex' => 'ファイル索引',
'FileInfo' => 'ファイル情報',
'FileInfoVersion' => 'ファイル情報バージョン',
'FileModifyDate' => '更新日時',
'FileName' => 'ファイル名',
'FileNumber' => 'ファイル番号',
'FileNumberMemory' => {
Description => 'ファイル番号メモリ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FileNumberSequence' => {
Description => 'ファイル番号連番',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FileSize' => 'ファイルのサイズ',
'FileSource' => {
Description => 'ファイルソース',
PrintConv => {
'Digital Camera' => 'デジタルカメラ',
'Film Scanner' => 'フィルムスキャナー',
'Reflection Print Scanner' => '反射印刷スキャナー',
},
},
'FileType' => 'ファイルタイプ',
'FileVersion' => 'ファイル形式バージョン',
'Filename' => 'ファイル名',
'FillFlashAutoReduction' => {
Description => '日中シンクロ・ストロボ露出自動低減制御',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'FillOrder' => {
Description => 'フルオーダー',
PrintConv => {
'Normal' => '標準',
},
},
'FilmMode' => {
Description => 'フィルムモード',
PrintConv => {
'Dynamic (B&W)' => 'ダイナミック(白黒)',
'Dynamic (color)' => 'ダイナミック(カラー)',
'Nature (color)' => 'ナチュラル(カラー)',
'Smooth (B&W)' => '滑らか(白黒)',
'Smooth (color)' => '滑らか(カラー)',
'Standard (B&W)' => 'スタンダード(白黒)',
'Standard (color)' => 'スタンダード(カラー)',
},
},
'FilmType' => 'フィルムタイプ',
'Filter' => {
Description => 'フィルター',
PrintConv => {
'Off' => 'オフ',
},
},
'FilterEffect' => {
Description => 'フィルター効果',
PrintConv => {
'Green' => '緑',
'None' => '無し',
'Off' => 'オフ',
'Orange' => 'オレンジ',
'Red' => '赤',
'Yellow' => '黄色',
'n/a' => '該当無し',
},
},
'FilterEffectMonochrome' => {
Description => 'モノクロフィルター効果',
PrintConv => {
'Green' => '緑',
'None' => '無し',
'Orange' => 'オレンジ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'FinderDisplayDuringExposure' => {
Description => '露光中のファインダー内表示',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FineTuneOptCenterWeighted' => '最適露出微調整 中央重点測光',
'FineTuneOptMatrixMetering' => '最適露出微調整 分割測光',
'FineTuneOptSpotMetering' => '最適露出微調整 スポット測光',
'Firmware' => 'ファームウェア',
'FirmwareDate' => 'ファームウェア日付',
'FirmwareRevision' => 'ファームウェアリビジョン',
'FirmwareVersion' => 'ファームウェアバージョン',
'FixtureIdentifier' => 'フィクチャー識別子',
'Flash' => {
Description => 'ストロボ',
PrintConv => {
'Auto, Did not fire' => 'フラッシュ未発光、オートモード',
'Auto, Did not fire, Red-eye reduction' => 'オート、フラッシュ未発光、赤目軽減モード',
'Auto, Fired' => 'フラッシュ発光、オートモード',
'Auto, Fired, Red-eye reduction' => 'フラッシュ発光、オートモード、赤目軽減モード',
'Auto, Fired, Red-eye reduction, Return detected' => 'フラッシュ発光、オートモード、ストロボ光検知、赤目軽減モード',
'Auto, Fired, Red-eye reduction, Return not detected' => 'フラッシュ発光、オートモード、ストロボ光未検知、赤目軽減モード',
'Auto, Fired, Return detected' => 'フラッシュ発光、オートモード、ストロボ光検知',
'Auto, Fired, Return not detected' => 'フラッシュ発光、オートモード、ストロボ光未検知',
'Did not fire' => 'フラッシュ未発光',
'Fired' => 'フラッシュ発光',
'Fired, Red-eye reduction' => 'フラッシュ発光、赤目軽減モード',
'Fired, Red-eye reduction, Return detected' => 'フラッシュ発光、赤目軽減モード、ストロボ光検知',
'Fired, Red-eye reduction, Return not detected' => 'フラッシュ発光、赤目軽減モード、ストロボ光未検知',
'Fired, Return detected' => 'ストロボ光検知',
'Fired, Return not detected' => 'ストロボ光未検知',
'No Flash' => 'フラッシュ未発光',
'No flash function' => 'フラッシュ機能無し',
'Off' => 'オフ',
'Off, Did not fire' => 'フラッシュ未発光、強制発光モード',
'Off, Did not fire, Return not detected' => 'オフ、フラッシュ未発光、ストロボ光未検知',
'Off, No flash function' => 'オフ、フラッシュ機能無し',
'Off, Red-eye reduction' => 'オフ、赤目軽減モード',
'On' => 'オン',
'On, Did not fire' => 'オン、フラッシュ未発光',
'On, Fired' => 'フラッシュ発光、強制発光モード',
'On, Red-eye reduction' => 'フラッシュ発光、強制発光モード、赤目軽減モード',
'On, Red-eye reduction, Return detected' => 'フラッシュ発光、強制発光モード、赤目軽減モード、ストロボ光検知',
'On, Red-eye reduction, Return not detected' => 'フラッシュ発光、強制発光モード、赤目軽減モード、ストロボ光未検知',
'On, Return detected' => 'フラッシュ発光、強制発光モード、ストロボ光検知',
'On, Return not detected' => 'フラッシュ発光、強制発光モード、ストロボ光未検知',
},
},
'FlashActivity' => 'フラッシュ稼働',
'FlashBias' => 'フラッシュバイアス',
'FlashBits' => 'フラッシュ詳細',
'FlashChargeLevel' => 'フラッシュチャージレベル',
'FlashCommanderMode' => {
Description => 'コマンダーモード',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FlashCompensation' => 'フラッシュ補正',
'FlashControlMode' => {
Description => 'フラッシュコントロールモード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
'Repeating Flash' => 'リピーティングフラッシュ',
},
},
'FlashDevice' => {
Description => 'フラッシュデバイス',
PrintConv => {
'External' => '外付け',
'Internal' => '内蔵',
'Internal + External' => '内蔵+外付け',
'None' => '無し',
},
},
'FlashDistance' => 'フラッシュ強度',
'FlashEnergy' => 'フラッシュ強度',
'FlashExposureBracketValue' => 'フラッシュ露出ブラケット値',
'FlashExposureComp' => 'フラッシュ露出補正',
'FlashExposureCompSet' => 'ストロボ露出補正設定',
'FlashExposureLock' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FlashFired' => {
Description => 'フラッシュ発光',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'FlashFiring' => {
Description => 'ストロボの発光',
PrintConv => {
'Does not fire' => 'しない',
'Fires' => 'する',
},
},
'FlashFirmwareVersion' => 'フラッシュファームウェアバージョン',
'FlashFocalLength' => 'フラッシュ焦点距離',
'FlashGroupACompensation' => 'グループAフラッシュ補正',
'FlashGroupAControlMode' => {
Description => 'グループAフラッシュコントロールモード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
'Repeating Flash' => 'リピーティングフラッシュ',
},
},
'FlashGroupAOutput' => 'グループAフラッシュ出力',
'FlashGroupBCompensation' => 'グループBフラッシュ補正',
'FlashGroupBControlMode' => {
Description => 'グループBフラッシュコントロールモード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
'Repeating Flash' => 'リピーティングフラッシュ',
},
},
'FlashGroupBOutput' => 'グループBフラッシュ出力',
'FlashGroupCCompensation' => 'グループCフラッシュ補正',
'FlashGroupCControlMode' => {
Description => 'グループCフラッシュコントロールモード',
PrintConv => {
'Auto Aperture' => '自動絞り(AA)',
'Manual' => 'マニュアル',
'Off' => 'オフ',
'Repeating Flash' => 'リピーティングフラッシュ',
},
},
'FlashGroupCOutput' => 'グループCフラッシュ出力',
'FlashGuideNumber' => 'フラッシュガイドナンバー',
'FlashInfo' => 'ストロボ情報',
'FlashInfoVersion' => 'フラッシュ情報バージョン',
'FlashIntensity' => {
Description => 'フラッシュ強度',
PrintConv => {
'High' => '高い',
'Low' => '低い',
'Normal' => '標準',
'Strong' => '強い',
'Weak' => '弱い',
},
},
'FlashLevel' => 'フラッシュ補正',
'FlashMetering' => 'フラッシュ計測',
'FlashMeteringSegments' => 'フラッシュ測光値',
'FlashMode' => {
Description => 'フラッシュモード',
PrintConv => {
'Auto' => 'オート',
'Auto, Did not fire' => 'オート、発光無し',
'Auto, Did not fire, Red-eye reduction' => 'オート、発光無し、赤目軽減',
'Auto, Fired' => 'オート、発光',
'Auto, Fired, Red-eye reduction' => 'オート、発光、赤目軽減',
'Did Not Fire' => '発光禁止',
'External, Auto' => '外付、オート',
'External, Contrast-control Sync' => '外付、光量比制御シンクロ',
'External, Flash Problem' => '外付、フラッシュの問題?',
'External, High-speed Sync' => '外付、ハイスピードシンクロ',
'External, Manual' => '外付、マニュアル',
'External, P-TTL Auto' => '外付、P-TTL自動調光',
'External, Wireless' => '外付、ワイヤレス',
'External, Wireless, High-speed Sync' => '外付、ワイヤレス、ハイスピードシンクロ',
'Fill flash' => '強制発光',
'Fired, Commander Mode' => '発光、コマンダーモード',
'Fired, External' => '発光、外付',
'Fired, Manual' => '発光、マニュアル',
'Fired, TTL Mode' => '発光、TTLモード',
'Internal' => '内蔵',
'Normal' => '標準',
'Off' => 'オフ',
'Off, Did not fire' => 'オフ',
'Off?' => 'オフ?',
'On' => 'オン',
'On, Did not fire' => 'オン、発光無し',
'On, Fired' => 'オン',
'On, Red-eye reduction' => 'オン、赤目軽減',
'On, Slow-sync' => 'オン、スローシンクロ',
'On, Slow-sync, Red-eye reduction' => 'オン、スローシンクロ、赤目軽減',
'On, Soft' => 'オン、ソフト',
'On, Trailing-curtain Sync' => 'オン、後幕シンクロ',
'On, Wireless (Control)' => 'オン、ワイヤレス (コントロール)',
'On, Wireless (Master)' => 'オン、ワイヤレス (マスター)',
'Rear flash sync' => 'リアフラッシュシンクロ',
'Red-eye Reduction' => '赤目軽減',
'Red-eye reduction' => '赤目軽減',
'Unknown' => '不明',
'Wireless' => 'ワイヤレス',
'n/a - Off-Auto-Aperture' => '該当なし-自動絞りオフ',
},
},
'FlashModel' => {
Description => 'フラッシュモデル',
PrintConv => {
'None' => '無し',
},
},
'FlashOptions' => {
Description => 'フラッシュオプション',
PrintConv => {
'Auto' => 'オート',
'Auto, Red-eye reduction' => 'オート、赤目軽減',
'Normal' => '標準',
'Red-eye reduction' => '赤目軽減',
'Slow-sync' => 'スローシンクロ',
'Slow-sync, Red-eye reduction' => 'スローシンクロ、赤目軽減',
'Trailing-curtain Sync' => '後幕シンクロ',
'Wireless (Control)' => 'ワイヤレス(コントロール発光)',
'Wireless (Master)' => 'ワイヤレス(マスター発光)',
},
},
'FlashOptions2' => {
Description => 'ストロボオプション(2)',
PrintConv => {
'Auto' => 'オート',
'Auto, Red-eye reduction' => 'オート、赤目軽減',
'Normal' => '標準',
'Red-eye reduction' => '赤目軽減',
'Slow-sync' => 'スローシンクロ',
'Slow-sync, Red-eye reduction' => 'スローシンクロ、赤目軽減',
'Trailing-curtain Sync' => '後幕シンクロ',
'Wireless (Control)' => 'ワイヤレス(コントロール発光)',
'Wireless (Master)' => 'ワイヤレス(マスター発光)',
},
},
'FlashOutput' => 'フラッシュ出力',
'FlashRemoteControl' => 'フラッシュリモートコントロール',
'FlashSerialNumber' => 'フラッシュシリアル番号',
'FlashSetting' => 'フラッシュ設定',
'FlashShutterSpeed' => 'フラッシュシャッター速度',
'FlashStatus' => {
Description => 'ストロボ状態',
PrintConv => {
'External, Did not fire' => '外付、未発光',
'External, Fired' => '外付、発光',
'Internal, Did not fire' => '内蔵、未発光',
'Internal, Fired' => '内蔵、発光',
'Off' => 'オフ',
},
},
'FlashSyncSpeed' => 'フラッシュ同調速度',
'FlashSyncSpeedAv' => {
Description => 'Avモード時のストロボ同調速度',
PrintConv => {
'1/200 Fixed' => '1/200秒固定',
'1/250 Fixed' => '1/250秒固定',
'1/300 Fixed' => '1/300秒固定',
'Auto' => 'オート',
},
},
'FlashType' => {
Description => 'フラッシュタイプ',
PrintConv => {
'E-System' => 'E-システム',
'None' => '無し',
'Simple E-System' => 'シンプルE-システム',
},
},
'FlashWarning' => {
Description => 'フラッシュ警告',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FlashpixVersion' => 'サポートフラッシュピックスバージョン',
'FlickerReduce' => {
Description => 'フリッカー軽減',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'FlipHorizontal' => {
Description => '横フリップ',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'FocalLength' => 'レンズ焦点距離',
'FocalLength35efl' => 'レンズ焦点距離',
'FocalLengthIn35mmFormat' => '35mmフイルム換算焦点距離',
'FocalPlaneDiagonal' => '焦点面対角線',
'FocalPlaneResolutionUnit' => {
Description => '焦点面解像度単位',
PrintConv => {
'None' => '無し',
'inches' => 'インチ',
},
},
'FocalPlaneXResolution' => '焦点面X解像度',
'FocalPlaneXSize' => '焦点面Xサイズ',
'FocalPlaneXUnknown' => '焦点面Xサイズ',
'FocalPlaneYResolution' => '焦点面Y解像度',
'FocalPlaneYSize' => '焦点面Yサイズ',
'FocalPlaneYUnknown' => '焦点面Yサイズ',
'FocalType' => {
Description => 'フォーカスタイプ',
PrintConv => {
'Fixed' => '固定',
'Zoom' => 'ズーム',
},
},
'FocalUnits' => '焦点単位/mm',
'Focus' => {
Description => 'フォーカス',
PrintConv => {
'Manual' => 'マニュアル',
},
},
'FocusArea' => 'フォーカスエリア',
'FocusAreaSelection' => {
Description => 'フォーカスポイントラップアラウンド',
PrintConv => {
'No Wrap' => 'ノーラップ',
'Wrap' => 'ラップ',
},
},
'FocusContinuous' => {
Description => '連続フォーカス',
PrintConv => {
'Continuous' => '連続',
'Manual' => 'マニュアル',
'Single' => 'シングル',
},
},
'FocusDistance' => '被写体距離',
'FocusDistanceLower' => '焦点距離低部分',
'FocusDistanceUpper' => '焦点距離高部分',
'FocusMode' => {
Description => 'フォーカスモード',
PrintConv => {
'AI Focus AF' => 'AIフォーカスAF',
'AI Servo AF' => 'AIサーボAF',
'Auto' => 'オート',
'Auto, Continuous' => 'オート、コンティニュアス',
'Auto, Focus button' => 'オート、フォーカスボタン',
'Continuous' => '連写',
'Continuous AF' => 'コンティニュアスAF',
'Custom' => 'カスタム',
'Infinity' => '無限遠',
'Macro' => 'マクロ',
'Macro (1)' => 'マクロ(1)',
'Macro (2)' => 'マクロ(2)',
'Manual' => 'マニュアル',
'Manual Focus (3)' => 'マニュアルフォーカス(3)',
'Manual Focus (6)' => 'マニュアルフォーカス(6)',
'Multi AF' => 'マルチAF',
'Normal' => '標準',
'One-shot AF' => 'ワンショットAF',
'Pan Focus' => 'パンフォーカス',
'Sequential shooting AF' => 'シーケンシャルシューティングAF',
'Single' => 'シングル',
'Single AF' => 'シングルAF',
'Super Macro' => 'スーパーマクロ',
},
},
'FocusMode2' => 'フォーカスモード2',
'FocusModeSetting' => {
Description => 'フォーカスモード',
PrintConv => {
'Manual' => 'マニュアル',
},
},
'FocusPixel' => '焦点解像度',
'FocusPointWrap' => {
Description => 'フォーカスポイントラップアラウンド',
PrintConv => {
'No Wrap' => 'ノーラップ',
'Wrap' => 'ラップ',
},
},
'FocusPosition' => 'フォーカス距離',
'FocusProcess' => {
Description => 'フォーカスプロセス',
PrintConv => {
'AF Not Used' => 'AF未使用',
'AF Used' => 'AF使用',
},
},
'FocusRange' => {
Description => 'フォーカスレンジ',
PrintConv => {
'Auto' => 'オート',
'Close' => '近景',
'Far Range' => '遠景',
'Infinity' => '無限遠',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Middle Range' => '中間範囲',
'Normal' => 'ノーマル',
'Not Known' => '不明',
'Pan Focus' => 'パンフォーカス',
'Super Macro' => 'スーパーマクロ',
'Very Close' => '近接',
},
},
'FocusSetting' => 'フォーカス設定',
'FocusStepCount' => 'フォーカスステップ数',
'FocusStepInfinity' => '無限レンズステップ',
'FocusStepNear' => 'ニアステップ数',
'FocusTrackingLockOn' => {
Description => 'フォーカストラッキングとロックオン',
PrintConv => {
'Long' => 'ロング',
'Normal' => '標準',
'Off' => 'オフ',
'Short' => 'ショート',
},
},
'FocusWarning' => {
Description => 'フォーカス警告',
PrintConv => {
'Good' => 'ジャスピン',
'Out of focus' => 'ピンボケ',
},
},
'FocusingScreen' => 'フォーカシングスクリーン',
'FolderName' => 'フォルダ名',
'ForwardMatrix1' => '前行列1',
'ForwardMatrix2' => '前行列2',
'FrameHeight' => 'フレーム高',
'FrameNumber' => 'フレーム番号',
'FrameRate' => 'フレームレート',
'FrameSize' => 'フレームサイズ',
'FrameWidth' => 'フレーム幅',
'FreeByteCounts' => 'フリーバイト数',
'FreeMemoryCardImages' => 'フリーメモリーカードイメージ',
'FreeOffsets' => 'フリーオフセット',
'FujiFlashMode' => {
Description => 'フラッシュモード',
PrintConv => {
'Auto' => 'オート',
'External' => '外付フラッシュ',
'Off' => 'オフ',
'On' => 'オン',
'Red-eye reduction' => '赤目軽減',
},
},
'FunctionButton' => {
Description => 'FUNCボタン',
PrintConv => {
'AF-area Mode' => 'AFエリアモード',
'Center AF Area' => '中央AFエリア',
'Center-weighted' => '中央重点測光',
'FV Lock' => 'FVロック',
'Flash Off' => 'フラッシュオフ',
'Framing Grid' => 'フレーミンググリッド',
'ISO Display' => 'ISO表示',
'Matrix Metering' => '分割測光',
'Spot Metering' => 'スポット測光',
},
},
'GEMInfo' => 'GEM情報',
'GEModel' => 'モデル',
'GIFVersion' => 'GIFバージョン',
'GPSAltitude' => '高度',
'GPSAltitudeRef' => {
Description => '参照高度',
PrintConv => {
'Above Sea Level' => '海水面',
'Below Sea Level' => '参照海水面(負の値)',
},
},
'GPSAreaInformation' => 'GPSエリアの名称',
'GPSDOP' => '測定精度',
'GPSDateStamp' => 'GPSデータ',
'GPSDateTime' => 'GPS時間(原子時計)',
'GPSDestBearing' => '目的地の方向',
'GPSDestBearingRef' => {
Description => '目的地の方向の参照',
PrintConv => {
'Magnetic North' => '磁気の方向',
'True North' => '正常な方向',
},
},
'GPSDestDistance' => '目的地の距離',
'GPSDestDistanceRef' => {
Description => '目的地の距離の参照',
PrintConv => {
'Kilometers' => 'キロメートル',
'Miles' => 'マイル',
'Nautical Miles' => 'ノット',
},
},
'GPSDestLatitude' => '目的地の緯度',
'GPSDestLatitudeRef' => {
Description => '目的地の緯度のための参照',
PrintConv => {
'North' => '北緯',
'South' => '南緯',
},
},
'GPSDestLongitude' => '目的地の経度',
'GPSDestLongitudeRef' => {
Description => '目的地の経度のための参照',
PrintConv => {
'East' => '東経',
'West' => '西経',
},
},
'GPSDifferential' => {
Description => 'GPS誤差修正',
PrintConv => {
'Differential Corrected' => '誤差修正あり',
'No Correction' => '誤差修正無し',
},
},
'GPSImgDirection' => 'イメージの方向',
'GPSImgDirectionRef' => {
Description => '画像方向参照',
PrintConv => {
'Magnetic North' => '磁気の方向',
'True North' => '本当の方向',
},
},
'GPSInfo' => 'GPS IFDへのポインタ',
'GPSLatitude' => '緯度',
'GPSLatitudeRef' => {
Description => '北緯または南緯',
PrintConv => {
'North' => '北緯',
'South' => '南緯',
},
},
'GPSLongitude' => '経度',
'GPSLongitudeRef' => {
Description => '東経または西経',
PrintConv => {
'East' => '東経',
'West' => '西経',
},
},
'GPSMapDatum' => 'データが使った測地測量',
'GPSMeasureMode' => {
Description => 'GPS測定モード',
PrintConv => {
'2-D' => '2次元測定',
'2-Dimensional' => '2次元測定',
'2-Dimensional Measurement' => '2次元測定',
'3-D' => '3次元測定',
'3-Dimensional' => '3次元測定',
'3-Dimensional Measurement' => '3次元測定',
},
},
'GPSProcessingMethod' => 'GPS処理方法の名称',
'GPSSatellites' => '測定のために使われたGPS衛星',
'GPSSpeed' => 'GPS受信機のスピード',
'GPSSpeedRef' => {
Description => 'スピード単位',
PrintConv => {
'km/h' => '時速(km)',
'knots' => 'ノット',
'mph' => '時速(マイル)',
},
},
'GPSStatus' => {
Description => 'GPS受信機ステータス',
PrintConv => {
'Measurement Active' => '測定アクティブ',
'Measurement Void' => '測定無効',
},
},
'GPSTimeStamp' => 'GPS時間(原子時計)',
'GPSTrack' => '動作方向',
'GPSTrackRef' => {
Description => '動作方向の参照',
PrintConv => {
'Magnetic North' => '磁気の方向',
'True North' => '本当の方向',
},
},
'GPSVersionID' => 'GPSタグバージョン',
'GainBase' => '基本ゲイン',
'GainControl' => {
Description => 'ゲインコントロール',
PrintConv => {
'High gain down' => '高いゲインダウン',
'High gain up' => '高いゲインアップ',
'Low gain down' => '低いゲインダウン',
'Low gain up' => '低いゲインアップ',
'None' => '無し',
},
},
'Gamma' => 'ガンマ',
'GammaCompensatedValue' => 'ガンマ補償値',
'Gamut' => '全域',
'Gapless' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'GeoTiffAsciiParams' => 'ジオアスキー設定タグ',
'GeoTiffDirectory' => 'ジオキーディレクトリタグ',
'GeoTiffDoubleParams' => 'ジオダブル設定タグ',
'Gradation' => 'グラデーション',
'GrayPoint' => 'グレーポイント',
'GrayResponseCurve' => 'グレー反応曲線',
'GrayResponseUnit' => {
Description => 'グレー反応単位',
PrintConv => {
'0.0001' => '単位の数は1000を表す',
'0.001' => '単位の数は100を表す',
'0.1' => '単位の数は10を表す',
'1e-05' => '単位の数は10-1000を表す',
'1e-06' => '単位の数は100-1000を表す',
},
},
'GrayScale' => 'グレースケール',
'GrayTRC' => '灰色調増殖曲線',
'GreenMatrixColumn' => '緑色マトリックス列',
'GreenTRC' => '緑色調増殖曲線',
'GridDisplay' => {
Description => 'ビューファインダーグリッド表示',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'GripBatteryADLoad' => '電源A/Dグリップ起動時',
'GripBatteryADNoLoad' => '電源A/Dグリップオフ時',
'GripBatteryState' => '電源状態グリップ',
'HCUsage' => 'HC使用',
'HDR' => {
Description => 'オートHDR',
PrintConv => {
'Off' => '切',
},
},
'HalftoneHints' => 'ハーフトーンヒント',
'Headline' => 'ヘッドライン',
'HeightResolution' => '高さ方向の画像解像度',
'HighISONoiseReduction' => {
Description => '高感度ノイズリダクション',
PrintConv => {
'Auto' => 'オート',
'High' => '高い',
'Low' => 'ソフト',
'Minimal' => '最小',
'Normal' => '標準',
'Off' => 'オフ',
'On' => 'オン',
'Standard' => 'スタンダード',
'Strong' => '強',
'Weak' => '弱',
'Weakest' => '微弱',
},
},
'Highlight' => 'ハイライト',
'HighlightTonePriority' => {
Description => '高輝度側・階調優先',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
'Off' => 'オフ',
'On' => 'オン',
},
},
'HometownCity' => '現在地',
'HometownCityCode' => '現在地コード',
'HometownDST' => {
Description => '現在地DST',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'HostComputer' => 'ホストコンピューター',
'Hue' => '色相',
'HueAdjustment' => '色相調整',
'HueSetting' => '色相設定',
'ICCProfile' => 'ICCプロフィール',
'ICC_Profile' => 'ICC入力色プロフィール',
'IPTC-NAA' => 'IPTC-NAAメタデータ',
'IPTCBitsPerSample' => 'サンプルあたりビット数',
'IPTCData' => 'IPTCデータ',
'IPTCImageHeight' => 'ライン数',
'IPTCImageRotation' => 'イメージ回転',
'IPTCImageWidth' => 'ラインあたりのピクセル数',
'IPTCPictureNumber' => '写真番号',
'IPTCPixelHeight' => 'スキャン方向垂直ピクセルサイズ',
'IPTCPixelWidth' => 'スキャン方向ピクセルサイズ',
'ISO' => 'ISOスピードレート',
'ISO2' => 'ISO(2)',
'ISOAuto' => 'ISOオート',
'ISODisplay' => 'ISO表示',
'ISOExpansion' => {
Description => 'ISO感度拡張',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ISOExpansion2' => {
Description => 'ISO拡大(2)',
PrintConv => {
'Off' => 'オフ',
},
},
'ISOFloor' => '最低感度',
'ISOInfo' => 'ISO情報',
'ISOSelection' => 'ISO選択',
'ISOSetting' => {
Description => 'ISO設定',
PrintConv => {
'Auto' => 'オート',
'Manual' => 'マニュアル',
},
},
'ISOSpeedExpansion' => {
Description => 'ISO感度拡張',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ISOSpeedIncrements' => {
Description => 'ISO感度ステップ値',
PrintConv => {
'1 Stop' => '1ステップ',
'1/3 Stop' => '1/3ステップ',
},
},
'ISOSpeedRange' => {
Description => 'ISO感度の制御範囲の設定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ISOStepSize' => {
Description => 'ISO感度ステップ値',
PrintConv => {
'1 EV' => '1ステップ',
'1/2 EV' => '1/2ステップ',
'1/3 EV' => '1/3ステップ',
},
},
'ISOValue' => 'ISO感度',
'IT8Header' => 'IT8ヘッダー',
'Illumination' => {
Description => 'イルミネーション',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Image::ExifTool::NikonCapture::RedEyeData' => 'Nikon Capture 赤目データ',
'ImageAdjustment' => 'イメージ調整',
'ImageAreaOffset' => 'イメージ領域オフセット',
'ImageAuthentication' => {
Description => 'イメージ認証',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ImageBoundary' => 'イメージ境界線',
'ImageByteCount' => '画像バイト数',
'ImageColorIndicator' => '画像色指標',
'ImageColorValue' => '画像色値',
'ImageCount' => 'イメージカウント',
'ImageDataDiscard' => {
Description => 'イメージデータ廃棄',
PrintConv => {
'Flexbits Discarded' => 'フレックスビット破棄',
'Full Resolution' => '完全な解像度',
'HighPass Frequency Data Discarded' => 'ハイパス周波数データ破棄',
'Highpass and LowPass Frequency Data Discarded' => 'ハイパスとローパス周波数データ破棄',
},
},
'ImageDataSize' => 'イメージデータサイズ',
'ImageDepth' => 'イメージの深さ',
'ImageDescription' => 'イメージ説明',
'ImageDustOff' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ImageEditCount' => '画像処理カウント',
'ImageEditing' => {
Description => 'イメージ処理',
PrintConv => {
'Cropped' => 'クロップ',
'Digital Filter' => 'デジタルフィルター',
'Frame Synthesis?' => 'フレーム合成?',
'None' => '未処理',
},
},
'ImageHeight' => '画像高さ',
'ImageHistory' => '画像履歴',
'ImageID' => 'イメージID',
'ImageInfo' => '画像情報',
'ImageLayer' => 'イメージレイヤー',
'ImageNumber' => 'イメージ番号',
'ImageNumber2' => 'イメージ番号(2)',
'ImageOffset' => 'イメージオフセット',
'ImageOptimization' => 'イメージ最適化',
'ImageOrientation' => {
Description => 'イメージ方向',
PrintConv => {
'Landscape' => 'ランドスケープ',
'Portrait' => 'ポートレート',
'Square' => '正方形',
},
},
'ImageProcessing' => 'イメージ処理',
'ImageProcessingVersion' => '画像処理バージョン',
'ImageQuality' => {
Description => '画像品質',
PrintConv => {
'High' => '高い',
'Motion Picture' => '動画',
'Normal' => '標準',
},
},
'ImageQuality2' => 'イメージ品質2',
'ImageResourceBlocks' => 'イメージリソースブロック',
'ImageReview' => {
Description => '画像評価',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ImageReviewTime' => '自動オフタイマー 画像評価時間',
'ImageRotated' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ImageSize' => 'イメージサイズ',
'ImageSourceData' => 'イメージソースデータ',
'ImageStabilization' => {
Description => 'イメージスタビライザー',
PrintConv => {
'Best Shot' => 'ベストショット',
'Off' => 'オフ',
'On' => 'オン',
'On, Mode 1' => 'オン、モード1',
'On, Mode 2' => 'オン、モード2',
},
},
'ImageTone' => {
Description => '画像仕上',
PrintConv => {
'Bright' => '鮮やか',
'Landscape' => '風景',
'Monochrome' => 'モノトーン',
'Natural' => 'ナチュラル',
'Portrait' => 'ポートレート',
'Vibrant' => '雅(MIYABI)',
},
},
'ImageType' => 'ページ',
'ImageUniqueID' => 'ユニークなイメージID',
'ImageWidth' => '画像幅',
'Index' => '目次',
'Indexed' => 'インデックス',
'InfoButtonWhenShooting' => {
Description => '撮影時のINFOボタン',
PrintConv => {
'Displays camera settings' => 'カメラ設定内容を表示',
'Displays shooting functions' => '撮影機能の設定状態を表示',
},
},
'InitialZoomSetting' => {
Description => '初期ズーム設定',
PrintConv => {
'High Magnification' => '高い拡大',
'Low Magnification' => '低い拡大',
'Medium Magnification' => '中間拡大',
},
},
'InkNames' => 'インク名',
'InkSet' => 'インクセット',
'Instructions' => '詳細',
'IntellectualGenre' => 'インテリジャンル',
'IntelligentAuto' => 'インテリジェントオート',
'IntensityStereo' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'IntergraphMatrix' => '相互グラフマトリックスタグ',
'Interlace' => 'インタレース',
'InternalFlash' => {
Description => '内蔵フラッシュコントロール',
PrintConv => {
'Commander Mode' => 'コマンダーモード',
'Fired' => 'フラッシュ発光',
'Manual' => 'マニュアル',
'No' => 'フラッシュ未発光',
'Off' => 'オフ',
'On' => 'オン',
'Repeating Flash' => 'リピーティングフラッシュ',
},
},
'InternalFlashAE1' => '内蔵フラッシュAE1?',
'InternalFlashAE1_0' => '内蔵フラッシュAE1(0)?',
'InternalFlashAE2' => '内蔵フラッシュAE2?',
'InternalFlashAE2_0' => '内蔵フラッシュAE2(0)?',
'InternalFlashMode' => {
Description => '内蔵ストロボモード',
PrintConv => {
'Did not fire, (Unknown 0xf4)' => 'オフ(未確認 0xF4?)',
'Did not fire, Auto' => 'オフ、オート',
'Did not fire, Auto, Red-eye reduction' => 'オフ、オート、赤目軽減',
'Did not fire, Normal' => 'オフ、標準',
'Did not fire, Red-eye reduction' => 'オフ、赤目軽減',
'Did not fire, Slow-sync' => 'オフ、スローシンクロ',
'Did not fire, Slow-sync, Red-eye reduction' => 'オフ、スローシンクロ、赤目軽減',
'Did not fire, Trailing-curtain Sync' => 'オフ、後幕シンクロ',
'Did not fire, Wireless (Control)' => 'オフ、ワイヤレス(コントロール発光)',
'Did not fire, Wireless (Master)' => 'オフ、ワイヤレス(マスター発光)',
'Fired' => 'オン',
'Fired, Auto' => 'オン、オート',
'Fired, Auto, Red-eye reduction' => 'オン、オート、赤目軽減',
'Fired, Red-eye reduction' => 'オン、赤目軽減',
'Fired, Slow-sync' => 'オン、スローシンクロ',
'Fired, Slow-sync, Red-eye reduction' => 'オン、スローシンクロ、赤目軽減',
'Fired, Trailing-curtain Sync' => 'オン、後幕シンクロ',
'Fired, Wireless (Control)' => 'オン、ワイヤレス(コントロール発光)',
'Fired, Wireless (Master)' => 'オン、ワイヤレス(マスター発光)',
'n/a - Off-Auto-Aperture' => '該当なし-自動絞りオフ',
},
},
'InternalFlashStrength' => '内蔵フラッシュ強度',
'InternalFlashTable' => '内蔵フラッシュテーブル',
'InternalSerialNumber' => '内部シリアル番号',
'InteropIndex' => {
Description => 'インターオペラビリティID',
PrintConv => {
'R03 - DCF option file (Adobe RGB)' => 'R03: DCFオプションファイル(Adobe RGB)',
'R98 - DCF basic file (sRGB)' => 'R98: DCF基本ファイル(sRGB)',
'THM - DCF thumbnail file' => 'THM: DCFサムネイルファイル',
},
},
'InteropOffset' => '互換性IFDへのポインタ',
'InteropVersion' => 'インターオペラビリティバージョン',
'IntervalLength' => 'インターバル長',
'IntervalMode' => 'インターバルモード',
'IntervalNumber' => 'インターバル数',
'JFIFVersion' => 'JFIFバージョン',
'JPEGACTables' => 'JPEG AC テーブル',
'JPEGDCTables' => 'JPEG DC テーブル',
'JPEGLosslessPredictors' => 'JPEGロスレス予測',
'JPEGPointTransforms' => 'JPEG位置変換',
'JPEGProc' => 'JPEG処理',
'JPEGQTables' => 'JPEG Q テーブル',
'JPEGQuality' => {
Description => 'JPEG 品質',
PrintConv => {
'Extra Fine' => 'エクストラファイン',
'Fine' => 'ファイン',
'Standard' => 'ノーマル',
'n/a' => '未設定',
},
},
'JPEGRestartInterval' => 'JPEG再開間隔',
'JPEGTables' => 'JPEGテーブル',
'JobID' => 'ジョブID',
'JpgRecordedPixels' => 'JPEG記録サイズ',
'Keyword' => 'キーワード',
'Keywords' => 'キーワード',
'LC1' => 'レンズデータ',
'LC10' => 'Mv\' nv\' データ',
'LC11' => 'AVC 1/EXP データ',
'LC12' => 'Mv1 Avminsifデータ',
'LC14' => 'UNT_12 UNT_6 データ',
'LC15' => '統合フラッシュ最適エンドデータ',
'LC2' => '距離コードデータ',
'LC3' => 'K値(',
'LC4' => '近距離収差訂正データ',
'LC5' => '明色収差訂正データ',
'LC6' => 'オープン収差データ',
'LC7' => 'AF最低作動状態データ(LC7)',
'LCDDisplayAtPowerOn' => {
Description => '電源スイッチ〈ON〉時の液晶点灯',
PrintConv => {
'Display' => '点灯',
'Retain power off status' => '電源〈OFF〉時の状態を保持',
},
},
'LCDDisplayReturnToShoot' => {
Description => '液晶モニター表示中の撮影状態復帰',
PrintConv => {
'Also with * etc.' => '*ボタンなどでも復帰',
'With Shutter Button only' => 'シャッターボタンでのみ復帰',
},
},
'LCDIllumination' => {
Description => 'LCDイルミネーション',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'LCDIlluminationDuringBulb' => {
Description => 'バルブ撮影中の表示パネル照明',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'LCDPanels' => '上面表示パネル/背面表示パネル',
'LCHEditor' => {
Description => 'LCHエディター',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'LanguageIdentifier' => '言語識別子',
'LastFileNumber' => '最終ファイル番号',
'LeafData' => 'リーフデータ',
'Lens' => 'レンズ',
'Lens35efl' => 'レンズ',
'LensAFStopButton' => {
Description => 'レンズ・AFストップボタンの機能',
PrintConv => {
'AE lock' => 'AEロック',
'AE lock while metering' => 'AEロック(タイマー中)',
'AF Stop' => 'AFストップ',
'AF point: M->Auto/Auto->ctr' => '測距点 任意→自動/自動→中央',
'AF start' => 'AFスタート',
'AF stop' => 'AFストップ',
'IS start' => '手ブレ補正機能作動',
'One Shot <-> AI servo' => 'ワンショット/AIサーボ',
'Switch to registered AF point' => '登録AFフレームへの切り換え',
},
},
'LensApertureRange' => 'レンズ絞り範囲',
'LensData' => 'K値(LC3)',
'LensDistortionParams' => 'レンズ歪曲パラメータ',
'LensDriveNoAF' => {
Description => 'AF測距不能時のレンズ動作',
PrintConv => {
'Focus search off' => '駆動しない',
'Focus search on' => 'サーチ駆動する',
},
},
'LensFStops' => 'レンズF値',
'LensFirmwareVersion' => 'レンズファームウェアバージョン',
'LensID' => 'レンズID',
'LensInfo' => 'レンズ情報',
'LensKind' => 'レンズ種類/バージョン(LC0)',
'LensProperties' => 'レンズ機能?',
'LensSerialNumber' => 'レンズシリアル番号',
'LensSpec' => 'レンズ',
'LensTemperature' => 'レンズ温度',
'LensType' => 'レンズタイプ',
'LicenseType' => {
PrintConv => {
'Unknown' => '不明',
},
},
'LightCondition' => 'ライトコンディション',
'LightReading' => 'ライトリーディング',
'LightSource' => {
Description => '光源',
PrintConv => {
'Cloudy' => '曇り',
'Cool White Fluorescent' => '白色蛍光灯',
'Custom 1-4' => 'カスタム1-4',
'Day White Fluorescent' => '昼白色蛍光灯',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Fine Weather' => '良い天気',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'ISO Studio Tungsten' => 'ISOスタジオタングステン',
'Other' => 'その他の光源',
'Shade' => '日陰',
'Standard Light A' => '標準ライトA',
'Standard Light B' => '標準ライトB',
'Standard Light C' => '標準ライトC',
'Tungsten (Incandescent)' => 'タングステン(白熱灯)',
'Unknown' => '不明',
'Warm White Fluorescent' => '暖白光色蛍光灯',
'White Fluorescent' => '温白色蛍光灯',
},
},
'LightSourceSpecial' => {
Description => '光源スペシャル',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Lightness' => '明度',
'LinearResponseLimit' => '線型反応限界',
'LinearizationTable' => '線形化テーブル',
'Lit' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'LiveViewExposureSimulation' => {
Description => 'ライブビュー露出シミュレーション',
PrintConv => {
'Disable (LCD auto adjust)' => 'しない(適正表示)',
'Enable (simulates exposure)' => 'する(撮影露出イメージ表示)',
},
},
'LiveViewShooting' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'LocalizedCameraModel' => '限定カメラモデル',
'Location' => '撮影場所',
'LockMicrophoneButton' => {
Description => 'プロテクト/録音ボタン タンの機能',
PrintConv => {
'Protect (hold:record memo)' => 'プロテクト(長押しで録音)',
'Record memo (protect:disable)' => '録音(プロテクト不可)',
},
},
'LongExposureNoiseReduction' => {
Description => '長秒露光ノイズリダクション',
PrintConv => {
'Auto' => 'オート',
'Off' => 'オフ',
'On' => 'オン',
'n/a' => '未設定',
},
},
'LookupTable' => 'ルックアップテーブル',
'LoopStyle' => {
PrintConv => {
'Normal' => '標準',
},
},
'Luminance' => '輝度',
'LuminanceNoiseReduction' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Off' => 'オフ',
},
},
'MB-D10Batteries' => 'MB-D10電源タイプ',
'MB-D10BatteryType' => 'MB-D10電源タイプ',
'MB-D80Batteries' => 'MB-D80バッテリー',
'MIEVersion' => 'MIEバージョン',
'MIMEType' => 'MIMEタイプ',
'MSStereo' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Macro' => {
Description => 'マクロ',
PrintConv => {
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Normal' => '標準',
'Off' => 'オフ',
'On' => 'オン',
'Super Macro' => 'スーパーマクロ',
'n/a' => '未設定',
},
},
'MacroMode' => {
Description => 'マクロモード',
PrintConv => {
'Macro' => 'マクロ',
'Normal' => 'ノーマル',
'Off' => 'オフ',
'On' => 'オン',
'Super Macro' => 'スーパーマクロ',
'Tele-Macro' => 'テレマクロ',
},
},
'MagnifiedView' => {
Description => '拡大ズーム表示',
PrintConv => {
'Image playback only' => '再生時のみ',
'Image review and playback' => '撮影直後と再生時',
},
},
'MainDialExposureComp' => {
Description => 'Main Dial 露出補正',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Make' => 'メーカー',
'MakeAndModel' => '作成とモデル',
'MakerNote' => 'DNGプライベートデータ',
'MakerNoteOffset' => 'メーカーノートオフセット',
'MakerNoteSafety' => {
Description => 'メーカーノートセーフティ',
PrintConv => {
'Safe' => '安全',
'Unsafe' => '危険',
},
},
'MakerNoteType' => 'メーカーノートタイプ',
'MakerNoteVersion' => 'メーカーノートバージョン',
'MakerNotes' => 'メーカーノート',
'ManometerPressure' => '気圧計圧力',
'ManometerReading' => '気圧計高度',
'ManualFlash' => 'マニュアルフラッシュ',
'ManualFlashOutput' => {
Description => 'マニュアルフラッシュ出力',
PrintConv => {
'Low' => 'ソフト',
'n/a' => '該当無し',
},
},
'ManualFocusDistance' => 'マニュアルフォーカス距離',
'ManualTv' => {
Description => 'マニュアル露出時Tv、Av値設定',
PrintConv => {
'Tv=Control/Av=Main' => 'Tv値=サブ電子ダイヤル/Av値=メイン電子ダイヤル',
'Tv=Main/Av=Control' => 'Tv値=メイン電子ダイヤル/Av値=サブ電子ダイヤル',
},
},
'ManufactureDate' => '製造日付?',
'MaskedAreas' => 'マスク領域',
'MasterDocumentID' => 'マスタ文書ID',
'MasterGain' => 'マスターゲイン',
'Matteing' => 'マッチング',
'MaxAperture' => '最大絞り',
'MaxApertureAtCurrentFocal' => '現在焦点距離の最大絞り',
'MaxApertureAtMaxFocal' => '最大焦点時最大絞り',
'MaxApertureAtMinFocal' => '最小焦点時最大絞り',
'MaxApertureValue' => '最大レンズ口径',
'MaxContinuousRelease' => '最大連写レリーズ',
'MaxFocalLength' => '最大焦点距離',
'MaxSampleValue' => '最大サンプル値',
'MaximumDensityRange' => '最大密度範囲',
'MeasuredEV' => '計測EV',
'Measurement' => '測定オブザーバー',
'MeasurementBacking' => 'バック測定',
'MeasurementFlare' => 'フレア測定',
'MeasurementGeometry' => '幾何学測定',
'MeasurementIlluminant' => '光源測定',
'MeasurementObserver' => '測定オブザーバー',
'MediaBlackPoint' => 'メディア黒点',
'MediaType' => {
PrintConv => {
'Movie' => '動画',
'Normal' => '標準',
},
},
'MediaWhitePoint' => 'メディア白点',
'Medium' => 'ミドル',
'MenuButtonDisplayPosition' => {
Description => 'メニューの表示位置',
PrintConv => {
'Previous' => '直前のメニュー',
'Previous (top if power off)' => '直前のメニュー(電源切で先頭)',
'Top' => 'メニューの先頭',
},
},
'MenuButtonReturn' => {
PrintConv => {
'Previous' => '直前のメニュー',
'Top' => '上',
},
},
'Metering' => {
Description => '測光',
PrintConv => {
'Center-weighted' => '中央重点',
'Matrix' => '分割',
'Spot' => 'スポット',
},
},
'MeteringMode' => {
Description => '測光モード',
PrintConv => {
'Average' => '平均',
'Center-weighted average' => '中央重点',
'Default' => 'デフォルト',
'Evaluative' => '評価',
'Multi-segment' => 'パターン',
'Multi-spot' => 'マルチスポット',
'Other' => 'その他',
'Partial' => '部分',
'Pattern+AF' => 'パターン+AF',
'Spot' => 'スポット',
'Spot+Highlight control' => 'スポット+ハイライトコントロール',
'Spot+Shadow control' => 'スポット+シャドウコントロール',
'Unknown' => '不明',
},
},
'MeteringMode2' => {
Description => '測光モード2',
PrintConv => {
'Multi-segment' => 'パターン',
},
},
'MeteringMode3' => {
Description => '測光モード3',
PrintConv => {
'Multi-segment' => 'パターン',
},
},
'MeteringTime' => '自動オフタイマー メータオフ時間',
'MinAperture' => '最小絞り',
'MinFocalLength' => '最小焦点距離',
'MinSampleValue' => '最小サンプル値',
'MinoltaCameraSettings2' => 'カメラ設定2',
'MinoltaCameraSettings5D' => 'カメラ設定(5D)',
'MinoltaCameraSettings7D' => 'カメラ設定(7D)',
'MinoltaDate' => '日付',
'MinoltaImageSize' => {
Description => 'イメージサイズ',
PrintConv => {
'Full' => 'フル',
'Large' => 'ラージ',
'Medium' => 'ミドル',
'Small' => 'スモール',
},
},
'MinoltaMakerNote' => 'ミノルタメーカーノート',
'MinoltaModelID' => 'モデルID',
'MinoltaQuality' => {
Description => 'イメージ品質',
PrintConv => {
'Economy' => 'エコノミー',
'Extra Fine' => 'エクストラファイン',
'Extra fine' => 'エクストラファイン',
'Fine' => 'ファイン',
'Normal' => '標準',
'Standard' => 'スタンダード',
'Super Fine' => 'スーパーファイン',
},
},
'MinoltaTime' => '時間',
'MirrorLockup' => {
Description => 'ミラーアップ撮影',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
'Enable: Down with Set' => 'する(SETボタンでダウン)',
},
},
'Model' => '画像入力機器モデル',
'Model2' => '画像入力機器モデル(2)',
'ModelTiePoint' => 'モデル拘束ポイントタグ',
'ModelTransform' => 'モデル変化タグ',
'ModelingFlash' => {
Description => 'モデリングフラッシュ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ModifiedPictureStyle' => {
PrintConv => {
'CM Set 1' => 'CMセット1',
'CM Set 2' => 'CMセット2',
'Faithful' => '忠実設定',
'High Saturation' => '高彩度',
'Landscape' => '風景',
'Low Saturation' => '低彩度',
'Monochrome' => 'モノトーン',
'Neutral' => 'ニュートラル',
'None' => '無し',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
'User Def. 1' => 'ユーザ設定1',
'User Def. 2' => 'ユーザ設定2',
'User Def. 3' => 'ユーザ設定3',
},
},
'ModifiedSaturation' => {
Description => '彩度修正',
PrintConv => {
'CM1 (Red Enhance)' => 'CM1 (赤増)',
'CM2 (Green Enhance)' => 'CM2 (緑増)',
'CM3 (Blue Enhance)' => 'CM3 (青増)',
'CM4 (Skin Tones)' => 'CM4 (肌色増)',
'Off' => 'オフ',
},
},
'ModifiedSharpnessFreq' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Standard' => 'スタンダード',
'n/a' => '該当無し',
},
},
'ModifiedToneCurve' => {
PrintConv => {
'Custom' => 'カスタム',
'Manual' => 'マニュアル',
'Standard' => 'スタンダード',
},
},
'ModifiedWhiteBalance' => {
PrintConv => {
'Auto' => 'オート',
'Black & White' => '白黒',
'Cloudy' => '曇り',
'Custom' => 'カスタム',
'Custom 1' => 'カスタム1',
'Custom 2' => 'カスタム2',
'Custom 3' => 'カスタム3',
'Custom 4' => 'カスタム4',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'Manual Temperature (Kelvin)' => 'マニュアル白熱灯(ケルビン)',
'PC Set1' => 'PC設定1',
'PC Set2' => 'PC設定2',
'PC Set3' => 'PC設定3',
'PC Set4' => 'PC設定4',
'PC Set5' => 'PC設定5',
'Shade' => '日陰',
'Tungsten' => 'タングステン(白熱灯)',
'Underwater' => '水中',
},
},
'ModifyDate' => 'ファイル作成日時',
'MoireFilter' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'MonitorOffTime' => 'モニターオフ遅延時間',
'MonochromeFilterEffect' => {
PrintConv => {
'Green' => '緑',
'None' => '無し',
'Orange' => 'オレンジ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'MonochromeLinear' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'MonochromeToningEffect' => {
PrintConv => {
'Blue' => '青',
'Green' => '緑',
'None' => '無し',
'Purple' => '紫',
'Sepia' => 'セピア',
},
},
'MultiExposure' => '多重露出データ',
'MultiExposureAutoGain' => {
Description => '多重露出自動ゲイン',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'MultiExposureMode' => {
Description => '多重露出モード',
PrintConv => {
'Image Overlay' => 'イメージオーバーレイ',
'Multiple Exposure' => '多重露出',
'Off' => 'オフ',
},
},
'MultiExposureShots' => '多重露出ショット',
'MultiExposureVersion' => '多重露出データバージョン',
'MultiFrameNoiseReduction' => {
Description => 'マルチショットノイズリダクション',
PrintConv => {
'Off' => '切',
'On' => '入',
},
},
'MultiSample' => 'マルチサンプル',
'MultiSelector' => {
Description => 'マルチ選択',
PrintConv => {
'Do Nothing' => '何もしない',
'Reset Meter-off Delay' => 'メーターオフ遅延時間リセット',
},
},
'MultiSelectorPlaybackMode' => {
Description => 'マルチ選択 再生モード',
PrintConv => {
'Choose Folder' => 'フォルダー選択',
'Thumbnail On/Off' => 'サムネイル オン/オフ',
'View Histograms' => 'ヒストグラム表示',
'Zoom On/Off' => 'ズーム オン/オフ',
},
},
'MultiSelectorShootMode' => {
Description => 'マルチ選択 撮影モード',
PrintConv => {
'Highlight Active Focus Point' => 'ハイライトアクティブフォーカスポイント',
'Not Used' => '未使用',
'Select Center Focus Point' => '中央フォーカスポイント選択',
},
},
'MultipleExposureSet' => {
Description => '多重露出設定',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Mute' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'MyColorMode' => {
Description => 'マイカラーモード',
PrintConv => {
'B&W' => '白黒',
'Color Accent' => 'カラーアクセント',
'Color Swap' => 'スイッチカラー',
'Custom' => 'カスタム',
'Dark Skin Tone' => 'ダークスキン調',
'Light Skin Tone' => 'ライトスカイ調',
'Neutral' => 'ニュートラル',
'Off' => 'オフ',
'Positive Film' => 'ポジフィルム',
'Sepia' => 'セピア',
'Vivid' => 'ビビッド',
'Vivid Blue' => 'ビビッド青',
'Vivid Green' => 'ビビッド緑',
'Vivid Red' => 'ビビッド赤',
},
},
'MyColors' => 'マイカラーモード',
'NDFilter' => {
Description => 'NDフィルター',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'NEFCompression' => {
Description => 'RAW圧縮',
PrintConv => {
'Lossless' => 'ロスレス',
'Lossy (type 1)' => '圧縮(タイプ1)',
'Lossy (type 2)' => '圧縮(タイプ2)',
'Uncompressed' => '非圧縮',
},
},
'NEFLinearizationTable' => '線形化表',
'NamedColor2' => '色名称2',
'NativeDisplayInfo' => 'ネイティブディスプレイ情報',
'NewsPhotoVersion' => '報道写真レコードバージョン',
'NikonCaptureData' => 'ニコンキャプチャーデータ',
'NikonCaptureOffsets' => 'ニコンキャプチャーオフセット',
'NikonCaptureVersion' => 'ニコンキャプチャーバージョン',
'NoMemoryCard' => {
Description => 'メモリーカード無し',
PrintConv => {
'Enable Release' => 'レリーズ可能',
'Release Locked' => 'レリーズロック',
},
},
'Noise' => 'ノイズ',
'NoiseFilter' => {
Description => 'ピクチャーモードノイズフィルター',
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Off' => 'オフ',
'Standard' => 'スタンダード',
},
},
'NoiseReduction' => {
Description => 'ノイズリダクション',
PrintConv => {
'Auto' => 'オート',
'Low' => '低い',
'Normal' => '標準',
'Off' => 'オフ',
'On' => 'オン',
'Standard' => 'スタンダード',
},
},
'NoiseReduction2' => 'ノイズリダクション2',
'NoiseReductionApplied' => '適用ノイズリダクション',
'NoiseReductionData' => 'ノイズリダクションデータ',
'NoiseReductionIntensity' => 'ノイズリダクション強度',
'NoiseReductionMethod' => 'ノイズリダクション方法',
'NoiseReductionSharpness' => 'ノイズリダクションシャープネス',
'NominalMaxAperture' => '最大絞り',
'NominalMinAperture' => '最小絞り',
'NumAFPoints' => 'AFポイント番号',
'NumIndexEntries' => 'インデックスエントリ数',
'NumberofInks' => 'インク番号',
'OPIProxy' => 'OPIプロキシー',
'ObjectAttributeReference' => 'インテリジャンル',
'ObjectCycle' => 'オブジェクトサイクル',
'ObjectDistance' => '被写体との距離',
'ObjectFileType' => {
PrintConv => {
'None' => '無し',
'Unknown' => '不明',
},
},
'ObjectName' => 'タイトル',
'ObjectPreviewData' => 'オブジェクトデータプレビューデータ',
'ObjectPreviewFileFormat' => 'オブジェクトデータプレビューファイル形式',
'ObjectPreviewFileVersion' => 'オブジェクトデータプレビューファイル形式バージョン',
'ObjectTypeReference' => 'オブジェクトタイプ参照',
'OffsetSchema' => 'オフセットの概要',
'OlympusImageHeight' => 'イメージ高',
'OlympusImageWidth' => 'イメージ幅',
'OneTouchWB' => {
Description => 'ワンタッチホワイトバランス',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
'On (Preset)' => 'オン(プリセット)',
},
},
'OpticalZoomCode' => '光学ズームコード',
'OpticalZoomMode' => {
Description => '光学ズームモード',
PrintConv => {
'Extended' => 'EX光学',
'Standard' => 'スタンダード',
},
},
'OpticalZoomOn' => {
Description => '光学ズームオン',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Opto-ElectricConvFactor' => '光電交換関数',
'OrderNumber' => 'オーダー番号',
'Orientation' => {
Description => '画像の向き',
PrintConv => {
'Horizontal (normal)' => '水平(標準)',
'Rotate 180' => '180度回転',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
},
},
'OriginalDecisionDataOffset' => 'オリジナル決定データオフセット',
'OriginalRawFileData' => 'オリジナルRAWファイルデータ',
'OriginalRawFileDigest' => 'オリジナルRAWファイル要約',
'OriginalRawFileName' => 'オリジナルRAWファイル名',
'OriginalTransmissionReference' => '作業識別子',
'OriginatingProgram' => '開始プログラム',
'OutputResponse' => '出力反応',
'OwnerID' => 'オーナーID',
'OwnerName' => 'オーナー名',
'PEFVersion' => 'PEFバージョン',
'Padding' => '引き伸ばし',
'PageName' => 'ページ名',
'PageNumber' => 'ページ番号',
'PanasonicExifVersion' => 'パナソニックExifバージョン',
'PanasonicRawVersion' => 'パナソニックRAWバージョン',
'PanasonicTitle' => 'タイトル',
'PanoramaDirection' => 'F値',
'PanoramaMode' => 'パノラマモード',
'PentaxImageSize' => 'ペンタックスイメージサイズ',
'PentaxModelID' => 'ペンタックスモデル',
'PentaxVersion' => 'ペンタックスバージョン',
'People' => '人々',
'PhaseDetectAF' => {
Description => 'オートフォーカス',
PrintConv => {
'Off' => 'オフ',
'On (51-point)' => 'オン',
},
},
'PhotoEffect' => {
Description => '写真効果',
PrintConv => {
'B&W' => '白黒',
'Custom' => 'カスタム',
'Neutral' => 'ニュートラル',
'Off' => 'オフ',
'Sepia' => 'セピア',
'Vivid' => 'ビビッド',
},
},
'PhotoEffects' => {
Description => 'フォトエフェクト',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'PhotoEffectsBlue' => 'フォトエフェクト青',
'PhotoEffectsData' => 'フォトエフェクトデータ',
'PhotoEffectsGreen' => 'フォトエフェクト緑',
'PhotoEffectsRed' => 'フォトエフェクト赤',
'PhotoEffectsType' => {
Description => 'フォトエフェクトタイプ',
PrintConv => {
'B&W' => '白黒',
'None' => '無し',
'Sepia' => 'セピア',
'Tinted' => '淡調',
},
},
'PhotoInfoPlayback' => {
Description => '写真情報/再生',
PrintConv => {
'Info Left-right, Playback Up-down' => '情報<>/再生',
'Info Up-down, Playback Left-right' => '情報/再生<>',
},
},
'PhotometricInterpretation' => {
Description => 'ピクセル形式',
PrintConv => {
'BlackIsZero' => '黒はゼロ',
'Color Filter Array' => 'CFA (カラーフィルターマトリックス)',
'Pixar LogL' => 'CIE Log2(L) (ログ輝度)',
'Pixar LogLuv' => 'CIE Log2(L)(u\',v\') (ログ輝度と基準色)',
'RGB Palette' => 'パレット色',
'Transparency Mask' => '透明度マスク',
'WhiteIsZero' => '白はゼロ',
},
},
'PhotoshopAnnotations' => 'フォトショップ注釈',
'PhotoshopFormat' => {
PrintConv => {
'Standard' => 'スタンダード',
},
},
'PictInfo' => '写真情報',
'PictureControl' => {
Description => 'ピクチャーコントロール',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'PictureControlActive' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'PictureControlAdjust' => {
Description => 'ピクチャーコントロール調整',
PrintConv => {
'Default Settings' => 'デフォルト設定',
'Full Control' => 'フルコントロール',
'Quick Adjust' => 'クイック調整',
},
},
'PictureControlBase' => 'ピクチャーコントロールベース',
'PictureControlName' => 'ピクチャーコントロール名',
'PictureControlQuickAdjust' => 'ピクチャーコントロールクイック調整',
'PictureControlVersion' => 'ピクチャーコントロールバージョン',
'PictureFinish' => {
Description => 'ピクチャーフィニッシュ',
PrintConv => {
'Monochrome' => 'モノトーン',
'Natural' => 'ナチュラル',
'Night Portrait' => '人物夜景',
'Night Scene' => '夜景',
'Portrait' => 'ポートレート',
},
},
'PictureMode' => {
Description => 'ピクチャーモード',
PrintConv => {
'1/2 EV steps' => '1/2 EVステップ',
'1/3 EV steps' => '1/3 EVステップ',
'Anti-blur' => '手振れ補正',
'Aperture Priority' => '絞り優先',
'Aperture Priority, Off-Auto-Aperture' => '絞り優先(自動絞りOFF)',
'Aperture-priority AE' => '絞り優先',
'Auto' => 'オート',
'Auto PICT (Landscape)' => 'オートピクチャー(風景)',
'Auto PICT (Macro)' => 'オートピクチャー(マクロ)',
'Auto PICT (Portrait)' => 'オートピクチャー(ポートレート)',
'Auto PICT (Sport)' => 'オートピクチャー(スポーツ)',
'Auto PICT (Standard)' => 'オートピクチャー(標準)',
'Autumn' => '秋',
'Beach' => 'ビーチ',
'Beach & Snow' => 'ビーチ&スノー',
'Blur Reduction' => 'Digital SR',
'Bulb' => 'バルブ',
'Bulb, Off-Auto-Aperture' => 'バルブ(自動絞りOFF)',
'Candlelight' => 'キャンドルライト',
'DOF Program' => '深度優先プログラム',
'DOF Program (HyP)' => '深度優先プログラム(ハイパープログラム)',
'Dark Pet' => 'ペット黒色',
'Digital Filter' => 'デジタルフィルター',
'Fireworks' => '花火',
'Flash X-Sync Speed AE' => 'ストロボ同調速度AE',
'Flower' => '花',
'Food' => '料理',
'Frame Composite' => 'フレーム合成',
'Green Mode' => 'グリーンモード',
'Hi-speed Program' => '高速優先プログラム',
'Hi-speed Program (HyP)' => '高速優先プログラム(ハイパープログラム)',
'Illustrations' => 'イラスト',
'Kids' => 'キッズ',
'Landscape' => '風景',
'Light Pet' => 'ペット白色',
'MTF Program' => 'MTF優先プログラム',
'MTF Program (HyP)' => 'MTF優先プログラム(ハイパープログラム)',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Manual, Off-Auto-Aperture' => 'マニュアル(自動絞りOFF)',
'Medium Pet' => 'ペット灰色',
'Monotone' => 'モノトーン',
'Museum' => '美術館',
'Muted' => '弱める',
'Natural' => 'ナチュラル',
'Natural Light' => 'ナチュラルフォト',
'Natural Light & Flash' => 'ナチュラルフォト&フラッシュ',
'Natural Skin Tone' => '美肌',
'Night Scene' => '夜景',
'Night Scene Portrait' => '人物、夜景',
'No Flash' => 'フラッシュ無し',
'Panorama' => 'パノラマ',
'Party' => 'パーティ',
'Pet' => 'ペット',
'Portrait' => 'ポートレート',
'Program' => 'プログラム',
'Program (HyP)' => 'プログラムAE(ハイパープログラム)',
'Program AE' => 'プログラムAE',
'Program Av Shift' => 'プログラムAvシフト',
'Program Tv Shift' => 'プログラムTvシフト',
'Self Portrait' => '自分撮り',
'Sensitivity Priority AE' => '感度優先AE',
'Sepia' => 'セピア',
'Shutter & Aperture Priority AE' => 'シャッター&絞り優先AE',
'Shutter Speed Priority' => 'シャッター優先',
'Shutter speed priority AE' => 'シャッター優先',
'Snow' => 'スノー',
'Soft' => 'ソフト',
'Sport' => 'スポーツ',
'Sports' => 'スポーツ',
'Standard' => 'スタンダード',
'Sunset' => '夕日',
'Surf & Snow' => 'サーフ&スノー',
'Synchro Sound Record' => 'ボイスレコーディング',
'Text' => 'テキスト',
'Underwater' => '水中',
'Vivid' => 'ビビッド',
},
},
'PictureMode2' => {
Description => 'ピクチャーモード 2',
PrintConv => {
'Aperture Priority' => '絞り優先',
'Aperture Priority, Off-Auto-Aperture' => '絞り優先(自動絞りオフ)',
'Auto PICT' => 'オートピクチャ',
'Bulb' => 'バルブ',
'Bulb, Off-Auto-Aperture' => 'バルブ(自動絞りオフ)',
'Flash X-Sync Speed AE' => 'ストロボ同調速度AE',
'Green Mode' => 'グリーンモード',
'Manual' => 'マニュアル',
'Manual, Off-Auto-Aperture' => 'マニュアル(自動絞りオフ)',
'Program AE' => 'プログラムAE',
'Program Av Shift' => 'プログラムAvシフト',
'Program Tv Shift' => 'プログラムTvシフト',
'Scene Mode' => 'シーンモード',
'Sensitivity Priority AE' => '感度優先AE',
'Shutter & Aperture Priority AE' => 'シャッター&絞り優先AE',
'Shutter Speed Priority' => 'シャッター優先',
},
},
'PictureModeBWFilter' => {
Description => 'ピクチャーモードBWフィルター',
PrintConv => {
'Green' => '緑',
'Neutral' => 'ニュートラル',
'Orange' => 'オレンジ',
'Red' => '赤',
'Yellow' => '黄色',
'n/a' => '該当無し',
},
},
'PictureModeContrast' => 'ピクチャーモードコントラスト',
'PictureModeHue' => 'ピクチャーモード色相?',
'PictureModeSaturation' => 'ピクチャーモード彩度',
'PictureModeSharpness' => 'ピクチャーモードシャープネス',
'PictureModeTone' => {
Description => 'ピクチャーモードトーン',
PrintConv => {
'Blue' => '青',
'Green' => '緑',
'Neutral' => 'ニュートラル',
'Purple' => '紫',
'Sepia' => 'セピア',
'n/a' => '該当無し',
},
},
'PictureStyle' => {
Description => 'ピクチャースタイル',
PrintConv => {
'CM Set 1' => 'CMセット1',
'CM Set 2' => 'CMセット2',
'Faithful' => '忠実設定',
'High Saturation' => '高彩度',
'Landscape' => '風景',
'Low Saturation' => '低彩度',
'Monochrome' => 'モノトーン',
'Neutral' => 'ニュートラル',
'None' => '無し',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
'User Def. 1' => 'ユーザ設定1',
'User Def. 2' => 'ユーザ設定2',
'User Def. 3' => 'ユーザ設定3',
},
},
'PixelFormat' => {
Description => 'ピクセルフォーマット',
PrintConv => {
'Black & White' => '白黒',
},
},
'PixelIntensityRange' => 'ピクセル強度範囲',
'PixelScale' => 'モデル画素スケールタグ',
'PixelUnits' => {
PrintConv => {
'Unknown' => '不明',
},
},
'PlanarConfiguration' => {
Description => '画像データの並び',
PrintConv => {
'Chunky' => '点順次形式 (重ね合わせ)',
'Planar' => '平面形式',
},
},
'PowerSource' => {
Description => '電源',
PrintConv => {
'Body Battery' => '本体電源',
'External Power Supply' => '外部電源',
'Grip Battery' => 'バッテリーグリップ',
},
},
'PreCaptureFrames' => 'プレキャプチャーフレーム',
'Predictor' => '指標',
'Preview' => 'プレビューIFDポインター',
'Preview0' => 'プレビュー0',
'Preview1' => 'プレビュー1',
'Preview2' => 'プレビュー2',
'PreviewApplicationName' => 'プレビューアプリケーション名',
'PreviewApplicationVersion' => 'プレビューアプリケーションバージョン',
'PreviewColorSpace' => {
Description => 'プレビュー色空間',
PrintConv => {
'Unknown' => '不明',
},
},
'PreviewDateTime' => 'プレビュー日時',
'PreviewIFD' => 'プレビューIFDポインター',
'PreviewImage' => 'プレビューイメージ',
'PreviewImageBorders' => 'プレビュー画像境界',
'PreviewImageData' => 'プレビュー画像データ',
'PreviewImageLength' => 'プレビューイメージ容量',
'PreviewImageSize' => 'プレビューイメージサイズ',
'PreviewImageStart' => 'プレビューイメージ開始',
'PreviewImageValid' => {
Description => '有効プレビュー画像',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'PreviewQuality' => {
PrintConv => {
'Economy' => 'エコノミー',
'Fine' => 'ファイン',
'Normal' => '標準',
'Normal Movie' => '標準動画',
'Superfine' => 'S.ファイン',
},
},
'PreviewSettingsDigest' => 'プレビュー設定要約',
'PreviewSettingsName' => 'プレビュー設定名',
'PrimaryAFPoint' => {
Description => 'プライマリAFポイント',
PrintConv => {
'Bottom' => '下',
'C6 (Center)' => 'C6 (中央)',
'Center' => '中央',
'Mid-left' => '中央左',
'Mid-right' => '中央右',
'Top' => '上',
},
},
'PrimaryChromaticities' => '原色色度',
'PrimaryPlatform' => '主要プラットフォーム',
'PrintIM' => 'プリントイメージマッチング',
'ProcessingSoftware' => '処理ソフトウェア',
'ProductID' => '製品ID',
'ProductionCode' => 'カメラが修理されたか?',
'ProfileCMMType' => 'CMMタイププロフィール',
'ProfileCalibrationSig' => 'プロフィールキャリブレーションサイン',
'ProfileClass' => {
Description => 'プロフィールクラス',
PrintConv => {
'Abstract Profile' => '抜粋プロフィール',
'ColorSpace Conversion Profile' => '色空間変換プロフィール',
'DeviceLink Profile' => 'デバイスリンクプロフィール',
'Display Device Profile' => '表示装置プロフィール',
'Input Device Profile' => '入力装置プロフィール',
'NamedColor Profile' => '色名称プロフィール',
'Nikon Input Device Profile (NON-STANDARD!)' => 'ニコンプロフィール("nkpf")',
'Output Device Profile' => '出力装置プロフィール',
},
},
'ProfileConnectionSpace' => '接続スペースプロフィール',
'ProfileCopyright' => 'プロフィール著作権',
'ProfileCreator' => 'プロフィール製作者',
'ProfileDateTime' => 'プロフィール日時',
'ProfileDescription' => 'プロフィール説明',
'ProfileDescriptionML' => 'プロフィール説明ML',
'ProfileEmbedPolicy' => {
Description => 'プロフィール埋め込み方針',
PrintConv => {
'Allow Copying' => 'コピー許可',
'Embed if Used' => '埋め込み使用',
'Never Embed' => '埋め込み禁止',
'No Restrictions' => '無制限',
},
},
'ProfileFileSignature' => 'プロフィールファイルシグネーチャ',
'ProfileHueSatMapData1' => '色相Sat.マップデータプロフィール1',
'ProfileHueSatMapData2' => '色相Sat.マップデータプロフィール2',
'ProfileHueSatMapDims' => '色境界',
'ProfileID' => 'プロフィールID',
'ProfileLookTableData' => '表示テーブルデータプロフィール',
'ProfileLookTableDims' => '色境界',
'ProfileName' => 'プロフィール名',
'ProfileSequenceDesc' => 'プロフィールシーケンス説明',
'ProfileToneCurve' => 'トーンカーブプロフィール',
'ProfileVersion' => 'プロフィールバージョン',
'ProgramISO' => 'プログラムISO',
'ProgramLine' => {
Description => 'プログラムライン',
PrintConv => {
'Depth' => '深度優先',
'Hi Speed' => '高速優先',
'MTF' => 'MTF優先',
'Normal' => 'ノーマル',
},
},
'ProgramMode' => {
PrintConv => {
'Night Portrait' => '人物夜景',
'None' => '無し',
'Portrait' => 'ポートレート',
'Sports' => 'スポーツ',
'Sunset' => '夕日',
'Text' => 'テキスト',
},
},
'ProgramShift' => 'プログラムシフト',
'ProgramVersion' => 'プログラムバージョン',
'Province-State' => '行政区/州',
'Quality' => {
Description => '品質',
PrintConv => {
'Best' => 'S.ファイン',
'Better' => 'ファイン',
'Compressed RAW' => 'cRAW',
'Compressed RAW + JPEG' => 'cRAW+JPEG',
'Economy' => 'エコノミー',
'Extra Fine' => 'エクストラファイン',
'Fine' => 'ファイン',
'Good' => 'エコノミー',
'Low' => '低画質',
'Normal' => 'ノーマル',
'Premium' => 'プレミアム',
'RAW + JPEG' => 'RAW+JPEG',
'Standard' => 'スタンダード',
'n/a' => '未設定',
},
},
'QualityMode' => {
Description => '品質モード',
PrintConv => {
'Economy' => 'エコノミー',
'Fine' => 'ファイン',
'Normal' => 'ノーマル',
},
},
'QuantizationMethod' => '量子化方法',
'QuickAdjust' => 'クイック調整',
'QuickControlDialInMeter' => {
Description => '測光タイマー中のサブ電子ダイヤル',
PrintConv => {
'AF point selection' => 'AFフレーム選択',
'Exposure comp/Aperture' => '露出補正/絞り数値',
'ISO speed' => 'ISO感度',
},
},
'QuickShot' => {
Description => 'クイックショット',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'RAFVersion' => 'RAFバージョン',
'ROCInfo' => 'ROC情報',
'RasterPadding' => 'ラスタパディング',
'RasterizedCaption' => 'ラスタ化表題',
'Rating' => '格付け',
'RatingPercent' => '格付け(%)',
'RawAndJpgRecording' => {
Description => 'RAWとJPEG記録',
PrintConv => {
'RAW+Large/Fine' => 'RAW+ラージ/ファイン',
'RAW+Large/Normal' => 'RAW+ラージ/ノーマル',
'RAW+Medium/Fine' => 'RAW+ミドル/ファイン',
'RAW+Medium/Normal' => 'RAW+ミドル/ノーマル',
'RAW+Small/Fine' => 'RAW+スモール/ファイン',
'RAW+Small/Normal' => 'RAW+スモール/ノーマル',
},
},
'RawColorAdj' => {
PrintConv => {
'Custom' => 'カスタム',
'Faithful' => '忠実設定',
},
},
'RawDataOffset' => 'RAWデータオフセット',
'RawDataUniqueID' => 'RAWデータユニークID',
'RawDevAutoGradation' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'RawDevColorSpace' => '色空間',
'RawDevContrastValue' => 'コントラスト値',
'RawDevEditStatus' => {
Description => '編集状態',
PrintConv => {
'Edited (Landscape)' => 'スタジオ(風景)',
'Edited (Portrait)' => 'スタジオ(ポートレート)',
'Original' => 'オリジナル',
},
},
'RawDevEngine' => {
Description => 'エンジン',
PrintConv => {
'Advanced High Speed' => 'アドバンス高速',
'High Function' => '高機能',
'High Speed' => '高速',
},
},
'RawDevExposureBiasValue' => '露出バイアス値',
'RawDevGrayPoint' => 'グレーポイント',
'RawDevMemoryColorEmphasis' => '記憶色強調',
'RawDevNoiseReduction' => 'ノイズフィルター(増感)',
'RawDevPMPictureTone' => {
PrintConv => {
'Blue' => '青',
'Green' => '緑',
'Neutral' => 'ニュートラル',
'Purple' => '紫',
'Sepia' => 'セピア',
},
},
'RawDevPM_BWFilter' => {
PrintConv => {
'Green' => '緑',
'Neutral' => 'ニュートラル',
'Orange' => 'オレンジ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'RawDevPictureMode' => {
PrintConv => {
'Natural' => 'ナチュラル',
'Sepia' => 'セピア',
'Vivid' => 'ビビッド',
},
},
'RawDevSaturationEmphasis' => '彩度強調',
'RawDevSettings' => 'ノイズリダクション',
'RawDevSharpnessValue' => 'コントラスト値',
'RawDevVersion' => 'RAW展開バージョン',
'RawDevWBFineAdjustment' => 'ホワイトバランス微調整',
'RawDevWhiteBalance' => {
PrintConv => {
'Color Temperature' => '色温度',
},
},
'RawDevWhiteBalanceValue' => 'ホワイトバランス値',
'RawImageCenter' => 'RAWイメージセンター',
'RawImageDigest' => 'RAWイメージ要約',
'RawImageHeight' => 'イメージ高さ',
'RawImageSegmentation' => 'RAWイメージ部分番号',
'RawImageSize' => 'RAWイメージサイズ',
'RawImageWidth' => 'イメージ幅',
'RawInfoVersion' => 'RAW情報バージョン',
'RawJpgQuality' => {
Description => 'RAW JPEG 品質',
PrintConv => {
'Economy' => 'エコノミー',
'Fine' => 'ファイン',
'Normal' => '標準',
'Normal Movie' => '標準動画',
'Superfine' => 'S.ファイン',
},
},
'RawJpgSize' => {
Description => 'RAW JPEG サイズ',
PrintConv => {
'Large' => 'ラージ',
'Medium' => 'ミドル',
'Medium 1' => 'ミドル1',
'Medium 2' => 'ミドル2',
'Medium 3' => 'ミドル3',
'Medium Movie' => 'ミディアム動画',
'Postcard' => 'ハガキ',
'Small' => 'スモール',
'Small Movie' => 'スモール動画',
'Widescreen' => 'ワイド画面',
},
},
'RecordMode' => {
Description => '記録モード',
PrintConv => {
'Aperture Priority' => '絞り優先',
'Best Shot' => 'ベストショット',
'Manual' => 'マニュアル',
'Movie' => '動画',
'Movie (19)' => '動画(19)',
'Program AE' => 'プログラムAE',
'Shutter Priority' => 'シャッター優先',
'YouTube Movie' => 'YouTube動画',
},
},
'RecordShutterRelease' => 'レコードシャッターレリーズ',
'RecordingMode' => {
Description => '記録モード',
PrintConv => {
'Auto' => 'オート',
'Landscape' => '風景',
'Manual' => 'マニュアル',
'Night Scene' => '夜景',
'Panorama' => 'パノラマ',
'Portrait' => 'ポートレート',
'Single Shutter' => 'シングルシャッター',
},
},
'RedBalance' => 'レッドバランス',
'RedEyeCorrection' => {
PrintConv => {
'Automatic' => 'オート',
'Off' => 'オフ',
},
},
'RedEyeData' => '赤目データ',
'RedEyeReduction' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'RedMatrixColumn' => '赤色マトリックス列',
'RedTRC' => '赤色調増殖曲線',
'ReductionMatrix1' => '縮小マトリックス1',
'ReductionMatrix2' => '縮小マトリックス2',
'ReferenceBlackWhite' => '白黒の基準値の一組',
'ReferenceDate' => '参照日付',
'ReferenceNumber' => '参照数',
'ReferenceService' => '参照サービス',
'RelatedImageFileFormat' => '関連イメージファイル形式',
'RelatedImageHeight' => '関連イメージ高',
'RelatedImageWidth' => '関連イメージ幅',
'RelatedSoundFile' => '関連オーディオファイル',
'ReleaseButtonToUseDial' => {
Description => 'レリーズボタンから使用ダイヤル',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ReleaseDate' => 'リリース日付',
'ReleaseTime' => 'リリース時間',
'RemoteOnDuration' => 'リモート持続時間',
'RenderingIntent' => {
Description => '意思表現',
PrintConv => {
'ICC-Absolute Colorimetric' => '絶対比色分析',
'Media-Relative Colorimetric' => '相対比色分析',
'Perceptual' => '知覚的',
'Saturation' => '飽和',
},
},
'RepeatingFlashCount' => 'リピーティングフラッシュ 時間',
'RepeatingFlashOutput' => 'リピーティングフラッシュ 出力',
'RepeatingFlashRate' => 'リピーティングフラッシュ 周波数',
'ResampleParamsQuality' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
},
},
'Resaved' => {
Description => '予約',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ResolutionMode' => '解像度モード',
'ResolutionUnit' => {
Description => 'XとY解像度単位',
PrintConv => {
'None' => '無し',
'cm' => 'ピクセル/cm',
'inches' => 'インチ',
},
},
'RetouchHistory' => {
Description => 'レタッチ履歴',
PrintConv => {
'None' => '無し',
'Sepia' => 'セピア',
},
},
'ReverseIndicators' => '指標逆転',
'Rotation' => {
Description => '回転',
PrintConv => {
'Horizontal' => '水平(標準)',
'Horizontal (Normal)' => '水平(標準)',
'Horizontal (normal)' => '水平(標準)',
'Rotate 180' => '180度回転',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
'Rotated 180' => '180度回転',
'Rotated 270 CW' => '270度回転 CW',
'Rotated 90 CW' => '90度回転 CW',
},
},
'RowInterleaveFactor' => '列を挟む要因',
'RowsPerStrip' => '1片の列数',
'SMaxSampleValue' => 'S 最大サンプル値',
'SMinSampleValue' => 'S 最小サンプル値',
'SPIFFVersion' => 'SPIFFバージョン',
'SRAWQuality' => {
PrintConv => {
'n/a' => '該当無し',
},
},
'SRActive' => {
Description => '手ぶれ補正状態',
PrintConv => {
'No' => 'オフ',
'Yes' => 'オン',
},
},
'SRFocalLength' => 'SR焦点距離',
'SRHalfPressTime' => 'シャッター半押し時間',
'SRResult' => {
Description => 'SR効果',
PrintConv => {
'Not stabilized' => 'なし',
},
},
'SVGVersion' => 'SVGバージョン',
'SafetyShift' => {
Description => 'セイフティシフト',
PrintConv => {
'Disable' => 'しない',
'Enable (ISO speed)' => 'する(ISO感度)',
'Enable (Tv/Av)' => 'する(Tv/Av値)',
},
},
'SafetyShiftInAvOrTv' => {
Description => 'セイフティシフトの設定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'SampleFormat' => 'サンプル形式',
'SampleStructure' => 'サンプリング構造',
'SamplesPerPixel' => 'コンポーネント数',
'SanyoQuality' => 'サンヨー品質',
'SanyoThumbnail' => 'サンヨーサムネイル',
'Saturation' => {
Description => '彩度',
PrintConv => {
'Film Simulation' => 'フィルムシミュレーション',
'High' => '高い彩度',
'Low' => '低い彩度',
'Med High' => '少し高い',
'Med Low' => '少し低い',
'Medium High' => '少し高い',
'Medium Low' => '少し低い',
'None' => '未設定',
'None (B&W)' => '無し(黒&白)',
'Normal' => '標準',
'Very High' => 'かなり高い',
'Very Low' => 'かなり低い',
},
},
'SaturationFaithful' => '彩度忠実設定',
'SaturationLandscape' => '彩度風景',
'SaturationNeutral' => '彩度ニュートラル',
'SaturationPortrait' => '彩度ポートレート',
'SaturationSetting' => '彩度設定',
'SaturationStandard' => '彩度スタンダード',
'SaturationUserDef1' => '彩度ユーザ設定1',
'SaturationUserDef2' => '彩度ユーザ設定2',
'SaturationUserDef3' => '彩度ユーザ設定3',
'ScanImageEnhancer' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ScanningDirection' => '走査方向',
'Scene' => '場面',
'SceneArea' => 'シーンエリア?',
'SceneAssist' => 'シーン調整',
'SceneCaptureType' => {
Description => 'シーンキャプチャタイプ',
PrintConv => {
'Landscape' => '風景',
'Night' => '夜景',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
},
},
'SceneDetect' => 'シーン検出',
'SceneDetectData' => 'シーン検出データ?',
'SceneMode' => {
Description => 'シーンモード',
PrintConv => {
'2 in 1' => '2イン1',
'3D Sweep Panorama' => '3D',
'Aerial Photo' => '空撮',
'Anti Motion Blur' => '人物ブレ軽減',
'Aperture Priority' => '絞り優先',
'Auction' => 'アクション',
'Auto' => 'オート',
'Auto+' => 'Auto アドバンス',
'Available Light' => '自然光',
'Baby' => '赤ちゃん',
'Beach' => 'ビーチ',
'Beach & Snow' => 'ビーチ&スノー',
'Behind Glass' => 'ガラス越し',
'Candle' => 'キャンドル',
'Candlelight' => 'キャンドルライト',
'Children' => '子供',
'Color Effects' => 'カラーエフェクト',
'Cont. Priority AE' => '連続撮影優先AE',
'Cuisine' => '料理',
'Digital Image Stabilization' => 'デジタル手振れ補正',
'Documents' => '文書',
'Face Portrait' => '寝顔',
'Fireworks' => '花火',
'Food' => '料理',
'Handheld Night Shot' => '手持ち夜景',
'High Key' => 'ハイキー',
'High Sensitivity' => '高感度',
'High Speed Continuous Shooting' => '高速連写',
'Indoor' => '屋内撮影',
'Intelligent Auto' => 'インテリジェントオート',
'Intelligent ISO' => 'インテリジェントISO',
'Landscape' => '風景',
'Landscape+Portrait' => '風景+人物',
'Low Key' => 'ローキー',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Movie' => '動画',
'Movie Preview' => '動画プレビュー',
'Museum' => '美術館',
'My Mode' => 'マイモード',
'Nature Macro' => '自然マクロ',
'Night Portrait' => '人物夜景',
'Night Scene' => '夜景',
'Night Scenery' => '夜景',
'Night View/Portrait' => 'ナイトビュー/ポートレイト',
'Night+Portrait' => '夜景+人物',
'Normal' => 'ノーマル',
'Off' => 'オフ',
'Panning' => 'パンニング',
'Panorama' => 'パノラマ',
'Panorama Assist' => 'パノラマアシスト',
'Party' => 'パーティ',
'Pet' => 'ペット',
'Portrait' => 'ポートレート',
'Program' => 'プログラム',
'Scenery' => '風景',
'Self Portrait' => '自分撮り',
'Self Portrait+Self Timer' => '自分撮り+セルフタイマー',
'Self Protrait+Timer' => '自分撮り+セルフタイマー',
'Shoot & Select' => 'ショット&セレクト',
'Shoot & Select1' => 'ショット&セレクト1',
'Shoot & Select2' => 'ショット&セレクト2',
'Shooting Guide' => '撮影ガイド',
'Shutter Priority' => 'シャッター優先',
'Simple' => 'シンプル',
'Smile Shot' => 'スマイルショット',
'Snow' => 'スノー',
'Soft Skin' => 'ソフトスキン',
'Sport' => 'スポーツ',
'Sports' => 'スポーツ',
'Spot' => 'スポット',
'Standard' => 'スタンダード',
'Starry Night' => '星空',
'Sunset' => '夕日',
'Super Macro' => 'スーパーマクロ',
'Sweep Panorama' => 'スイングパノラマ',
'Text' => 'テキスト',
'Underwater' => '水中',
'Underwater Macro' => '水中マクロ',
'Underwater Snapshot' => '水中スナップ',
'Underwater Wide1' => '水中ワイド1',
'Underwater Wide2' => '水中ワイド2',
'Vivid' => 'ビビッド',
},
},
'SceneModeUsed' => {
Description => 'シーンモード',
PrintConv => {
'Aperture Priority' => '絞り優先',
'Beach' => 'ビーチ',
'Candlelight' => 'キャンドルライト',
'Fireworks' => '花火',
'Landscape' => '風景',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Night Portrait' => '人物夜景',
'Portrait' => 'ポートレート',
'Program' => 'プログラム',
'Shutter Priority' => 'シャッター優先',
'Snow' => 'スノー',
'Sunset' => '夕日',
'Text' => 'テキスト',
},
},
'SceneSelect' => {
Description => 'シーン選択',
PrintConv => {
'Lamp' => 'ランプ',
'Night' => '夜景',
'Off' => 'オフ',
'Sport' => 'スポーツ',
'TV' => 'テレビ',
'User 1' => 'ユーザー1',
'User 2' => 'ユーザー2',
},
},
'SceneType' => {
Description => 'シーンタイプ',
PrintConv => {
'Directly photographed' => '直接撮影画像',
},
},
'SecurityClassification' => {
Description => 'セキュリティ区分',
PrintConv => {
'Confidential' => '機密文書',
'Restricted' => '限定',
'Secret' => '秘密',
'Top Secret' => '最高機密',
'Unclassified' => '未分類',
},
},
'SelectableAFPoint' => {
Description => '任意選択可能なAFフレーム',
PrintConv => {
'11 points' => '11点',
'19 points' => '19点',
'45 points' => '45点',
'Inner 9 points' => '9点(内側)',
'Outer 9 points' => '9点(外側)',
},
},
'SelfTimer' => {
Description => 'セルフタイマー長',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'SelfTimer2' => 'セルフタイマー(2)',
'SelfTimerMode' => 'セルフタイマーモード',
'SelfTimerTime' => 'セルフタイマー遅延時間',
'SensingMethod' => {
Description => 'センサー方式',
PrintConv => {
'Color sequential area' => 'シーケンシャルカラーセンサー',
'Color sequential linear' => 'シーケンシャルカラーラインセンサー',
'Monochrome area' => 'モノクロエリアセンサー',
'Monochrome linear' => 'モノクロラインセンサー',
'Not defined' => '未定義',
'One-chip color area' => '単板式カラーセンサー',
'Three-chip color area' => '3板式カラーセンサー',
'Trilinear' => '3ラインセンサー',
'Two-chip color area' => '2板式カラーセンサー',
},
},
'SensitivityAdjust' => '感度調節',
'SensitivitySteps' => {
Description => '感度ステップ',
PrintConv => {
'1 EV Steps' => '1EVステップ',
'As EV Steps' => '露出ステップに従う',
},
},
'SensorCleaning' => {
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'SensorHeight' => 'センサー高さ',
'SensorImageHeight' => 'センサー高さ',
'SensorImageWidth' => 'センサー幅',
'SensorLeftBorder' => 'イメージ左部',
'SensorPixelSize' => 'センサーピクセルサイズ',
'SensorTemperature' => 'センサー温度',
'SensorTopBorder' => 'イメージ上部',
'SensorWidth' => 'センサー幅',
'Sequence' => 'シーケンス',
'SequenceNumber' => 'シーケンス番号',
'SequenceShotInterval' => 'シーケンスショットインターバル',
'SequentialShot' => {
Description => 'シーケンシャルショット',
PrintConv => {
'None' => '無し',
'Standard' => 'スタンダード',
},
},
'SerialNumber' => 'シリアル番号',
'SerialNumberFormat' => 'シリアル番号形式',
'ServiceIdentifier' => 'サービス識別子',
'SetButtonCrossKeysFunc' => {
Description => 'SETボタン/十字キー機能',
PrintConv => {
'Cross keys: AF point select' => '十字キー:AFフレーム選択',
'Normal' => '標準',
'Set: Flash Exposure Comp' => 'SET:調光補正',
'Set: Parameter' => 'SET:現像パラメーター選択',
'Set: Picture Style' => 'SET:ピクチャースタイル',
'Set: Playback' => 'SET:画像の再生',
'Set: Quality' => 'SET:記録画質',
},
},
'SetButtonWhenShooting' => {
Description => '撮影時のSETボタン',
PrintConv => {
'Change parameters' => '現像パラメーター選択',
'Default (no function)' => '通常(なし)',
'Disabled' => '無効',
'Flash exposure compensation' => '調光補正',
'ISO speed' => 'ISO感度',
'Image playback' => '画像再生',
'Image quality' => '記録画質選択',
'Image size' => '画像サイズ',
'LCD monitor On/Off' => '液晶モニターの入/切',
'Menu display' => 'メニュー表示',
'Normal (disabled)' => '通常(無効)',
'Picture style' => 'ピクチャースタイル',
'Quick control screen' => 'クイック設定画面',
'Record func. + media/folder' => '記録機能とメディア・フォルダ',
'Record movie (Live View)' => '動画撮影(ライブビュー)',
'White balance' => 'ホワイトバランス',
},
},
'SetFunctionWhenShooting' => {
Description => '撮影時のセットボタン機能',
PrintConv => {
'Change Parameters' => '現像パラメーター選択',
'Change quality' => '記録画質選択',
'Default (no function)' => '通常(なし)',
'Image replay' => '画像の再生',
'Menu display' => 'メニュー表示',
},
},
'ShadingCompensation' => {
Description => '陰影修正',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ShadingCompensation2' => {
Description => '陰影補正編集',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Shadow' => 'シャドウ',
'ShadowScale' => 'シャドウスケール',
'Shadows' => 'シャドウ',
'ShakeReduction' => {
Description => '手ぶれ補正(設定)',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ShakeReductionInfo' => 'SR効果',
'Sharpness' => {
Description => 'シャープネス',
PrintConv => {
'Film Simulation' => 'フィルムシミュレーション',
'Hard' => 'ハード',
'Hard2' => 'ハード2',
'Med Hard' => '少しハード',
'Med Soft' => '少しソフト',
'Medium Hard' => 'ミドルハード',
'Medium Soft' => 'ミドルソフト',
'Normal' => 'ノーマル',
'Sharp' => 'シャープ',
'Soft' => 'ソフト',
'Soft2' => 'ソフト2',
'Very Hard' => 'かなりハード',
'Very Soft' => 'かなりソフト',
'n/a' => '該当無し',
},
},
'SharpnessFactor' => 'シャープネス要因',
'SharpnessFaithful' => 'シャープネス忠実設定',
'SharpnessFrequency' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
'Standard' => 'スタンダード',
'n/a' => '該当無し',
},
},
'SharpnessLandscape' => 'シャープネス風景',
'SharpnessMonochrome' => 'シャープネスモノクロ',
'SharpnessNeutral' => 'シャープネスニュートラル',
'SharpnessPortrait' => 'シャープネスポートレート',
'SharpnessSetting' => 'シャープネス設定',
'SharpnessStandard' => 'シャープネススタンダード',
'SharpnessUserDef1' => 'シャープネスユーザ設定1',
'SharpnessUserDef2' => 'シャープネスユーザ設定2',
'SharpnessUserDef3' => 'シャープネスユーザ設定3',
'ShootingInfoDisplay' => {
Description => '撮影情報表示',
PrintConv => {
'Auto' => 'オート',
'Manual (dark on light)' => '手動-黒地に白',
'Manual (light on dark)' => '手動-白地に黒',
},
},
'ShootingMode' => {
Description => '撮影モード',
PrintConv => {
'Aerial Photo' => '空撮',
'Aperture Priority' => '絞り優先',
'Baby' => '赤ちゃん',
'Beach' => 'ビーチ',
'Candlelight' => 'キャンドルライト',
'Clipboard' => 'メモ',
'Color Effects' => 'カラーエフェクト',
'Economy' => 'エコモード',
'Fireworks' => '花火',
'Food' => '料理',
'High Sensitivity' => '高感度',
'High Speed Continuous Shooting' => '高速連写',
'Intelligent Auto' => 'インテリジェントオート',
'Intelligent ISO' => 'インテリジェントISO',
'Macro' => 'マクロ',
'Manual' => 'マニュアル',
'Movie Preview' => '動画プレビュー',
'Night Portrait' => '人物夜景',
'Night Scenery' => '夜景',
'Normal' => '標準',
'Panning' => 'パンニング',
'Panorama Assist' => 'パノラマアシスト',
'Party' => 'パーティ',
'Pet' => 'ペット',
'Portrait' => 'ポートレート',
'Program' => 'プログラム',
'Scenery' => '風景',
'Self Portrait' => '自分撮り',
'Shutter Priority' => 'シャッター優先',
'Simple' => 'シンプル',
'Snow' => 'スノー',
'Soft Skin' => 'ソフトスキン',
'Sports' => 'スポーツ',
'Spot' => 'スポット',
'Starry Night' => '星空',
'Sunset' => '夕日',
'Underwater' => '水中',
},
},
'ShootingModeSetting' => {
Description => '撮影モード',
PrintConv => {
'Continuous' => '連続撮影',
'Delayed Remote' => '遅延リモート',
'Quick-response Remote' => '即時リモート',
'Self-timer' => 'セルフタイマー',
'Single Frame' => '1コマ撮影',
},
},
'ShortDocumentID' => '短文書ID',
'ShortOwnerName' => '短いオーナー名',
'ShortReleaseTimeLag' => {
Description => 'レリーズタイムラグ最速化',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ShotInfoVersion' => 'ショット情報バージョン',
'Shutter-AELock' => {
Description => 'シャッターボタン/AEロックボタン',
PrintConv => {
'AE lock/AF' => 'AEロック/AF',
'AE/AF, No AE lock' => 'AE/AF(AEロックなし)',
'AF/AE lock' => 'AF/AEロック',
'AF/AF lock' => 'AF/AFロック',
'AF/AF lock, No AE lock' => 'AF/AFロック(AEロックなし)',
},
},
'ShutterAELButton' => 'シャッターボタン/AEロックボタン',
'ShutterButtonAFOnButton' => {
Description => 'シャッター/AF-ONボタン',
PrintConv => {
'AE lock/Metering + AF start' => 'AEロック/測光・AF開始',
'Metering + AF start' => '測光・AF開始',
'Metering + AF start/AF stop' => '測光・AF開始/AFストップ',
'Metering + AF start/disable' => '測光・AF開始/無効',
'Metering start/Meter + AF start' => '測光開始/測光・AF開始',
},
},
'ShutterCount' => 'シャッター回数',
'ShutterCurtainSync' => {
Description => 'ストロボのシンクロタイミング',
PrintConv => {
'1st-curtain sync' => '先幕シンクロ',
'2nd-curtain sync' => '後幕シンクロ',
},
},
'ShutterMode' => {
PrintConv => {
'Aperture Priority' => '絞り優先',
'Auto' => 'オート',
},
},
'ShutterReleaseButtonAE-L' => {
Description => 'シャッターレリーズボタン AE-L',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ShutterReleaseNoCFCard' => {
Description => 'CFカード未装填時のレリーズ',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ShutterSpeed' => '露出時間',
'ShutterSpeedRange' => {
Description => 'シャッター速度の制御範囲の設定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ShutterSpeedValue' => 'シャッタースピード',
'SimilarityIndex' => '類似インデックス',
'Site' => 'サイト',
'SlaveFlashMeteringSegments' => 'スレーブフラッシュ測光値',
'SlideShow' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'SlowShutter' => {
Description => 'スローシャッター',
PrintConv => {
'Night Scene' => '夜景',
'None' => '無し',
'Off' => 'オフ',
'On' => 'オン',
},
},
'SlowSync' => {
Description => 'スローシンクロ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Software' => 'ソフトウェア',
'SoftwareVersion' => 'ソフトウェアバージョン',
'Source' => 'ソース',
'SpatialFrequencyResponse' => '空間周波数特性',
'SpecialEffectsOpticalFilter' => {
PrintConv => {
'None' => '無し',
},
},
'SpecialInstructions' => '手順',
'SpecialMode' => 'スペシャルモード',
'SpectralSensitivity' => 'スペクトル感度',
'SpotFocusPointX' => 'スポットフォーカスポイントX',
'SpotFocusPointY' => 'スポットフォーカスポイントY',
'SpotMeterLinkToAFPoint' => {
Description => '測距点連動スポット測光',
PrintConv => {
'Disable (use center AF point)' => 'しない(中央固定',
'Enable (use active AF point)' => 'する(測距点連動)',
},
},
'SpotMeteringMode' => {
Description => 'スポットメーターモード',
PrintConv => {
'Center' => '中央',
},
},
'State' => '都道府県名',
'StoNits' => 'Stoニット',
'StraightenAngle' => 'ストレートアングル',
'StreamType' => {
PrintConv => {
'Text' => 'テキスト',
},
},
'StripByteCounts' => '圧縮片のバイト数',
'StripOffsets' => '画像データ位置',
'Sub-location' => '場所',
'SubSecCreateDate' => 'デジタルデータ作成日時',
'SubSecDateTimeOriginal' => 'オリジナルデータ作成日時',
'SubSecModifyDate' => 'ファイル作成日時',
'SubSecTime' => 'DateTimeサブ秒',
'SubSecTimeDigitized' => 'DateTimeDigitizedサブ秒',
'SubSecTimeOriginal' => 'DateTimeOriginalサブ秒',
'SubTileBlockSize' => 'サブタイトルブロックサイズ',
'SubfileType' => '新規サブファイルタイプ',
'SubimageColor' => {
PrintConv => {
'Monochrome' => 'モノトーン',
},
},
'Subject' => 'サブジェクト',
'SubjectArea' => '対象領域',
'SubjectDistance' => '対象距離',
'SubjectDistanceRange' => {
Description => '被写体距離範囲',
PrintConv => {
'Close' => '近景',
'Distant' => '遠景',
'Macro' => 'マクロ',
'Unknown' => '不明',
},
},
'SubjectLocation' => '対象領域',
'SubjectProgram' => {
Description => '被写体プログラム',
PrintConv => {
'Night portrait' => '人物夜景',
'None' => '無し',
'Portrait' => 'ポートレート',
'Sports action' => 'スポーツアクション',
'Sunset' => '夕日',
'Text' => 'テキスト',
},
},
'SubjectReference' => 'サブジェクトコード',
'Subsystem' => {
PrintConv => {
'Unknown' => '不明',
},
},
'SuperMacro' => {
Description => 'スーパーマクロ',
PrintConv => {
'Off' => 'オフ',
'On (1)' => 'オン(1)',
'On (2)' => 'オン(2)',
},
},
'SuperimposedDisplay' => {
Description => 'スーパーインポーズの表示',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'SupplementalCategories' => '補足カテゴリー',
'SupplementalType' => '補足タイプ',
'SvISOSetting' => 'SVISO感度設定',
'SwitchToRegisteredAFPoint' => {
Description => '登録AFフレームへの切り換え',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'T4Options' => 'T4オプション',
'T6Options' => 'T6オプション',
'TIFF-EPStandardID' => 'TIFF/EP標準ID',
'TTL_DA_ADown' => 'TTL D/A Aチャンネル ダウン',
'TTL_DA_AUp' => 'TTL D/A Aチャンネル アップ',
'TTL_DA_BDown' => 'TTL D/A Bチャンネル ダウン',
'TTL_DA_BUp' => 'TTL D/A Bチャンネル アップ',
'Tagged' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'TargetAperture' => 'ターゲット絞り',
'TargetExposureTime' => 'ターゲット露出時間',
'TargetPrinter' => '標的プリンタ',
'Technology' => {
Description => 'テクノロジー',
PrintConv => {
'Active Matrix Display' => 'アクティブマトリクス型ディスプレイ',
'Cathode Ray Tube Display' => 'CRTディスプレイ',
'Digital Camera' => 'デジタルカメラ',
'Dye Sublimation Printer' => '昇華型プリンター',
'Electrophotographic Printer' => '静電記録式プリンター',
'Electrostatic Printer' => '静電気プリンター',
'Film Scanner' => 'フイルムスキャナー',
'Film Writer' => 'フィルムライター',
'Flexography' => 'アニリン印刷',
'Gravure' => 'グラビア印刷',
'Ink Jet Printer' => 'インクジェットプリンター',
'Offset Lithography' => 'オフセット印刷',
'Passive Matrix Display' => '単純マトリクス型ディスプレイ',
'Photo CD' => 'フォトCD',
'Photo Image Setter' => 'フォトイメージセッター',
'Photographic Paper Printer' => '印画紙プリンター',
'Projection Television' => 'プロジェクションテレビ',
'Reflective Scanner' => '反射スキャナ',
'Silkscreen' => 'シルクスクリーン印刷',
'Thermal Wax Printer' => '熱転写プリンター',
'Video Camera' => 'ビデオカメラ',
'Video Monitor' => 'ビデオモニター',
},
},
'Teleconverter' => {
PrintConv => {
'None' => '無し',
},
},
'Text' => 'テキスト',
'TextInfo' => 'テキスト情報',
'TextStamp' => {
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Thresholding' => '閾値化',
'ThumbnailImage' => 'サムネイル画像',
'ThumbnailImageSize' => 'サムネイルサイズ',
'ThumbnailImageValidArea' => 'サムネイル画像有効領域',
'TileByteCounts' => 'タイルのバイト数',
'TileDepth' => 'タイルの深さ',
'TileLength' => 'タイルの長さ',
'TileOffsets' => 'タイルのオフセット',
'TileWidth' => 'タイルの幅',
'Time' => '時間',
'TimeCreated' => '作成時間',
'TimeScaleParamsQuality' => {
PrintConv => {
'High' => '高い',
'Low' => 'ソフト',
},
},
'TimeSent' => '発送時間',
'TimeSincePowerOn' => '電源オン経過時間',
'TimeStamp' => 'タイムスタンプ',
'TimeStamp1' => 'タイムスタンプ1',
'TimeZone' => 'タイムゾーン',
'TimeZoneOffset' => 'タイムゾーンオフセット',
'TimerFunctionButton' => {
Description => 'ファンクションボタン',
PrintConv => {
'ISO' => 'ISO感度',
'Image Quality/Size' => '画像品質/サイズ',
'Self-timer' => 'セルフタイマー',
'Shooting Mode' => '撮影モード',
'White Balance' => 'ホワイトバランス',
},
},
'TimerLength' => {
Description => '各種タイマー保持時間',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'Timezone' => 'タイムゾーン',
'Title' => 'タイトル',
'ToneComp' => 'トーン補正',
'ToneCurve' => {
Description => 'トーンカーブ',
PrintConv => {
'Custom' => 'カスタム',
'Manual' => 'マニュアル',
'Standard' => 'スタンダード',
},
},
'ToneCurveActive' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'ToneCurveName' => {
PrintConv => {
'Custom' => 'カスタム',
},
},
'ToneCurves' => 'トーンカーブ(s)',
'ToningEffect' => {
Description => 'トーン効果',
PrintConv => {
'B&W' => '白黒',
'Blue' => '青',
'Blue-green' => '青緑',
'Cyanotype' => '青写真',
'Green' => '緑',
'None' => '無し',
'Purple' => '紫',
'Purple-blue' => '青紫',
'Red' => '赤',
'Red-purple' => '赤紫',
'Sepia' => 'セピア',
'Yellow' => '黄色',
'n/a' => '該当無し',
},
},
'ToningEffectMonochrome' => {
Description => 'モノクロトーン効果',
PrintConv => {
'Blue' => '青',
'Green' => '緑',
'None' => '無し',
'Purple' => '紫',
'Sepia' => 'セピア',
},
},
'ToningSaturation' => '彩度トーン',
'TransferFunction' => '転送機能',
'TransferRange' => '転送範囲',
'Transformation' => {
Description => '変形',
PrintConv => {
'Horizontal (normal)' => '水平(標準)',
'Rotate 180' => '180度回転',
'Rotate 270 CW' => '270度回転 CW',
'Rotate 90 CW' => '90度回転 CW',
},
},
'TransmissionReference' => '送信元記録',
'TransparencyIndicator' => '透明度指標',
'TrapIndicator' => 'トラップインジケーター',
'Trapped' => {
PrintConv => {
'Unknown' => '不明',
},
},
'TravelDay' => 'トラベル日付',
'TvExposureTimeSetting' => 'Tv露出時間設定',
'Type' => 'タイプ',
'USMLensElectronicMF' => {
Description => 'USMレンズの電子式手動フォーカス',
PrintConv => {
'Disable after one-shot AF' => 'ワンショットAF作動後・不可',
'Disable in AF mode' => 'AF時すべて不可',
'Enable after one-shot AF' => 'ワンショットAF作動後・可',
},
},
'Uncompressed' => {
Description => '非圧縮',
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'UniqueCameraModel' => 'ユニークカメラモデル',
'UniqueDocumentID' => 'ユニーク文書ID',
'UniqueObjectName' => 'ユニーク・ネーム・オブ・オブジェクト',
'Unknown' => '不明',
'Unsharp1Color' => {
Description => 'アンシャープ1カラー',
PrintConv => {
'Blue' => '青',
'Cyan' => 'シアン',
'Green' => '緑',
'Magenta' => 'マゼンダ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'Unsharp1HaloWidth' => 'アンシャープ1円光幅',
'Unsharp1Intensity' => 'アンシャープ1強度',
'Unsharp1Threshold' => 'アンシャープ1起点',
'Unsharp2Color' => {
Description => 'アンシャープ2カラー',
PrintConv => {
'Blue' => '青',
'Cyan' => 'シアン',
'Green' => '緑',
'Magenta' => 'マゼンダ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'Unsharp2HaloWidth' => 'アンシャープ2円光幅',
'Unsharp2Intensity' => 'アンシャープ2強度',
'Unsharp2Threshold' => 'アンシャープ2起点',
'Unsharp3Color' => {
Description => 'アンシャープ3カラー',
PrintConv => {
'Blue' => '青',
'Cyan' => 'シアン',
'Green' => '緑',
'Magenta' => 'マゼンダ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'Unsharp3HaloWidth' => 'アンシャープ3円光幅',
'Unsharp3Intensity' => 'アンシャープ3強度',
'Unsharp3Threshold' => 'アンシャープ3起点',
'Unsharp4Color' => {
Description => 'アンシャープ4カラー',
PrintConv => {
'Blue' => '青',
'Cyan' => 'シアン',
'Green' => '緑',
'Magenta' => 'マゼンダ',
'Red' => '赤',
'Yellow' => '黄色',
},
},
'Unsharp4HaloWidth' => 'アンシャープ4円光幅',
'Unsharp4Intensity' => 'アンシャープ4強度',
'Unsharp4Threshold' => 'アンシャープ4起点',
'UnsharpCount' => 'アンシャープカウント',
'UnsharpData' => 'アンシャープデータ',
'UnsharpMask' => {
Description => 'アンシャープマスク',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Urgency' => '緊急性',
'UsableMeteringModes' => {
Description => '測光モードの限定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'UsableShootingModes' => {
Description => '撮影モードの限定',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'UserComment' => 'ユーザーコメント',
'UserDef1PictureStyle' => {
Description => 'ユーザ設定1 ピクチャースタイル',
PrintConv => {
'Faithful' => '忠実設定',
'Landscape' => '風景',
'Monochrome' => 'モノトーン',
'Neutral' => 'ニュートラル',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
},
},
'UserDef2PictureStyle' => {
Description => 'ユーザ設定2 ピクチャースタイル',
PrintConv => {
'Faithful' => '忠実設定',
'Landscape' => '風景',
'Monochrome' => 'モノトーン',
'Neutral' => 'ニュートラル',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
},
},
'UserDef3PictureStyle' => {
Description => 'ユーザ設定3 ピクチャースタイル',
PrintConv => {
'Faithful' => '忠実設定',
'Landscape' => '風景',
'Monochrome' => 'モノトーン',
'Neutral' => 'ニュートラル',
'Portrait' => 'ポートレート',
'Standard' => 'スタンダード',
},
},
'VRDVersion' => 'VRDバージョン',
'VRInfo' => 'VR(手振れ補正)情報',
'VRInfoVersion' => 'VR情報バージョン',
'VR_0x66' => {
PrintConv => {
'Off' => 'オフ',
'On (active)' => 'オン(アクティブ)',
'On (normal)' => 'オン(ノーマル)',
},
},
'ValidAFPoints' => '有効なAFポイント',
'ValidBits' => 'ピクセルにつき有効なビット',
'VariProgram' => 'バリプログラム',
'Version' => 'バージョン',
'VibrationReduction' => {
Description => '手振れ補正(VR)',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
'On (1)' => 'オン(1)',
'On (2)' => 'オン(2)',
'On (3)' => 'オン(3)',
'n/a' => '該当無し',
},
},
'VideoCardGamma' => 'ビデオカードガンマ',
'ViewInfoDuringExposure' => {
Description => '露光中のファインダー内表示',
PrintConv => {
'Disable' => 'しない',
'Enable' => 'する',
},
},
'ViewfinderWarning' => {
Description => 'ビューファインダー警告表示',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'ViewingCondDesc' => '視聴状態説明',
'ViewingCondIlluminant' => '視聴状態光源',
'ViewingCondIlluminantType' => '視聴状態光源タイプ',
'ViewingCondSurround' => '視聴状態周辺',
'ViewingConditions' => '視聴状態光源',
'VignetteControl' => {
Description => 'ビネットコントロール',
PrintConv => {
'High' => '高い',
'Low' => '低い',
'Normal' => '標準',
'Off' => 'オフ',
'On' => 'オン',
},
},
'VignetteControlIntensity' => 'ビネットコントロール強度',
'VoiceMemo' => {
Description => 'ボイスメモ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'WBAdjData' => 'ホワイトバランス調整データ',
'WBAdjLighting' => {
Description => 'ホワイトバランス調整、ライティング',
PrintConv => {
'Daylight' => '昼光',
'Flash' => 'ストロボ',
'High Color Rendering Fluorescent' => 'ハイカラーレンダリング蛍光灯',
'Incandescent' => '電球',
'None' => '無し',
'Standard Fluorescent' => '標準蛍光灯',
},
},
'WBAdjMode' => {
Description => 'ホワイトバランス調整モード',
PrintConv => {
'Calculate Automatically' => '自動計算',
'Recorded Value' => '記録値',
'Use Gray Point' => 'グレーポイント使用',
'Use Temperature' => '温度使用',
},
},
'WBAdjTemperature' => 'ホワイトバランス調整、色温度',
'WBBlueLevel' => 'ホワイトバランス青レベル',
'WBBracketMode' => {
Description => 'ホワイトバランスブラケットモード',
PrintConv => {
'Off' => 'オフ',
'On (shift AB)' => 'オン(シフトAB)',
'On (shift GM)' => 'オン(シフトGM)',
},
},
'WBBracketValueAB' => 'ホワイトバランスブラケット値AB',
'WBBracketValueGM' => 'ホワイトバランスブラケット値GM',
'WBFineTuneActive' => {
PrintConv => {
'No' => 'いいえ',
'Yes' => 'はい',
},
},
'WBGreenLevel' => 'ホワイトバランス緑レベル',
'WBMediaImageSizeSetting' => {
Description => 'WB/メディア・画像サイズの設定',
PrintConv => {
'LCD monitor' => '液晶モニター',
'Rear LCD panel' => '背面表示パネル',
},
},
'WBMode' => {
Description => 'ホワイトバランスモード',
PrintConv => {
'Auto' => 'オート',
},
},
'WBRedLevel' => 'ホワイトバランス赤レベル',
'WBShiftAB' => 'WB AB補正',
'WBShiftGM' => 'WB GM補正',
'WB_GBRGLevels' => 'WB GBRG レベル',
'WB_GRBGLevels' => 'WB GRBG レベル',
'WB_GRGBLevels' => 'WB GRGB レベル',
'WB_RBGGLevels' => 'WB RBGG レベル',
'WB_RBLevels' => 'WB RBレベル',
'WB_RBLevels3000K' => 'WB RGGB3000Kレベル',
'WB_RBLevels3300K' => 'WB RGGB3300Kレベル',
'WB_RBLevels3600K' => 'WB RGGB3600Kレベル',
'WB_RBLevels3900K' => 'WB RGGB3800Kレベル',
'WB_RBLevels4000K' => 'WB RGGB4000Kレベル',
'WB_RBLevels4300K' => 'WB RGGB4300Kレベル',
'WB_RBLevels4500K' => 'WB RGGB4500Kレベル',
'WB_RBLevels4800K' => 'WB RGGB4800Kレベル',
'WB_RBLevels5300K' => 'WB RGGB5300Kレベル',
'WB_RBLevels6000K' => 'WB RGGB6000Kレベル',
'WB_RBLevels6600K' => 'WB RGGB6600Kレベル',
'WB_RBLevels7500K' => 'WB RGGB7500Kレベル',
'WB_RBLevelsAuto' => 'WB RB レベル オート',
'WB_RBLevelsCloudy' => 'WB RB レベル 曇天',
'WB_RBLevelsCoolWhiteFluor' => 'WB RB レベル 冷白蛍光灯',
'WB_RBLevelsDayWhiteFluor' => 'WB RB レベル 昼白蛍光灯',
'WB_RBLevelsDaylightFluor' => 'WB RB レベル 昼光蛍光灯',
'WB_RBLevelsEveningSunlight' => 'WB RB レベル 夕日',
'WB_RBLevelsFineWeather' => 'WB RB レベル 晴天',
'WB_RBLevelsShade' => 'WB RB レベル 日陰',
'WB_RBLevelsTungsten' => 'WB RB レベル 白熱灯',
'WB_RBLevelsUsed' => 'WB RB レベル使用',
'WB_RBLevelsWhiteFluorescent' => 'WB RB レベル 白蛍光灯',
'WB_RGBGLevels' => 'WB RGBG レベル',
'WB_RGBLevels' => 'WB RGB レベル',
'WB_RGBLevelsCloudy' => 'WB RGB レベル 曇天',
'WB_RGBLevelsDaylight' => 'WB RGB レベル 昼光',
'WB_RGBLevelsFlash' => 'WB RGB レベル ストロボ',
'WB_RGBLevelsFluorescent' => 'WB RGGB レベル 蛍光灯',
'WB_RGBLevelsShade' => 'WB RGB レベル 日陰',
'WB_RGBLevelsTungsten' => 'WB RGB レベル 白熱灯',
'WB_RGGBLevels' => 'WB RGGB レベル',
'WB_RGGBLevelsCloudy' => 'WB RGGB レベル 曇天',
'WB_RGGBLevelsDaylight' => 'WB RGGB レベル 昼光',
'WB_RGGBLevelsFlash' => 'WB RGGB レベル ストロボ',
'WB_RGGBLevelsFluorescent' => 'WB RGGB レベル 蛍光灯',
'WB_RGGBLevelsFluorescentD' => 'WB RGGB レベル 蛍光灯(D)',
'WB_RGGBLevelsFluorescentN' => 'WB RGGB レベル 蛍光灯(N)',
'WB_RGGBLevelsFluorescentW' => 'WB RGGB レベル 蛍光灯(W)',
'WB_RGGBLevelsShade' => 'WB RGGB レベル 日陰',
'WB_RGGBLevelsTungsten' => 'WB RGGB レベル 白熱灯',
'WCSProfiles' => 'Windowsカラーシステムプロフィール',
'WhiteBalance' => {
Description => 'ホワイトバランス',
PrintConv => {
'Auto' => 'オート',
'Black & White' => '白黒',
'Cloudy' => '曇り',
'Color Temperature/Color Filter' => '色温度マニュアル指定',
'Cool White Fluorescent' => '白色蛍光灯',
'Custom' => 'カスタム',
'Custom 1' => 'カスタム1',
'Custom 2' => 'カスタム2',
'Custom 3' => 'カスタム3',
'Custom 4' => 'カスタム4',
'Custom2' => 'カスタム2',
'Custom3' => 'カスタム3',
'Custom4' => 'カスタム4',
'Custom5' => 'カスタム5',
'Day White Fluorescent' => '昼白色蛍光灯',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'Incandescent' => '電球',
'Kelvin' => 'ケルビン',
'Living Room Warm White Fluorescent' => 'リビング暖白光色蛍光灯',
'Manual' => 'マニュアル',
'Manual Temperature (Kelvin)' => 'マニュアル白熱灯(ケルビン)',
'PC Set1' => 'PC設定1',
'PC Set2' => 'PC設定2',
'PC Set3' => 'PC設定3',
'PC Set4' => 'PC設定4',
'PC Set5' => 'PC設定5',
'Shade' => '日陰',
'Tungsten' => 'タングステン(白熱灯)',
'Underwater' => '水中',
'Unknown' => '不明',
'User-Selected' => 'ユーザ選択',
'Warm White Fluorescent' => '暖白光色蛍光灯',
'White Fluorescent' => '温白色蛍光灯',
},
},
'WhiteBalance2' => {
Description => 'ホワイトバランス2',
PrintConv => {
'3000K (Tungsten light)' => '3000K (白熱電球)',
'3600K (Tungsten light-like)' => '3600K (白熱電球-like)',
'4000K (Cool white fluorescent)' => '4000K (蛍光灯1)',
'4500K (Neutral white fluorescent)' => '4500K (蛍光灯2)',
'5300K (Fine Weather)' => '5300K (晴天)',
'6000K (Cloudy)' => '6000K (曇り)',
'6600K (Daylight fluorescent)' => '6600K (蛍光灯3)',
'7500K (Fine Weather with Shade)' => '7500K (晴天と影)',
'Auto' => 'オート',
'Custom WB 1' => 'カスタムホワイトバランス1',
'Custom WB 2' => 'カスタムホワイトバランス2',
'Custom WB 2900K' => 'カスタムホワイトバランス2900K',
'Custom WB 3' => 'カスタムホワイトバランス3',
'Custom WB 4' => 'カスタムホワイトバランス4',
'Custom WB 5400K' => 'カスタムホワイトバランス5400K',
'Custom WB 8000K' => 'カスタムホワイトバランス8000K',
},
},
'WhiteBalanceAdj' => {
Description => 'ホワイトバランス調整',
PrintConv => {
'Auto' => 'オート',
'Cloudy' => '曇り',
'Daylight' => '昼光',
'Flash' => 'ストロボ',
'Fluorescent' => '蛍光灯',
'Off' => 'オフ',
'On' => 'オン',
'Shade' => '日陰',
'Tungsten' => 'タングステン(白熱灯)',
},
},
'WhiteBalanceBias' => 'ホワイトバランスバイアス',
'WhiteBalanceBracket' => 'ホワイトバランスブラケット',
'WhiteBalanceComp' => 'ホワイトバランス補正',
'WhiteBalanceFineTune' => 'ホワイトバランスファインチューン',
'WhiteBalanceMode' => {
Description => 'ホワイトバランスモード',
PrintConv => {
'Auto (Cloudy)' => 'オート(曇天)',
'Auto (Day White Fluorescent)' => 'オート(昼白色蛍光灯)',
'Auto (Daylight Fluorescent)' => 'オート(昼光色蛍光灯)',
'Auto (Daylight)' => 'オート(昼光)',
'Auto (Flash)' => 'オート(ストロボ)',
'Auto (Shade)' => 'オート(日陰)',
'Auto (Tungsten)' => 'オート(白熱灯)',
'Auto (White Fluorescent)' => 'オート(白色蛍光灯)',
'Unknown' => '不明',
'User-Selected' => 'ユーザー選択',
},
},
'WhiteBalanceSet' => {
Description => 'ホワイトバランス設定',
PrintConv => {
'Auto' => 'オート',
'Cloudy' => '曇り',
'Day White Fluorescent' => '昼白色蛍光灯',
'Daylight' => '昼光',
'Daylight Fluorescent' => '昼光色蛍光灯',
'Flash' => 'ストロボ',
'Manual' => 'マニュアル',
'Set Color Temperature 1' => '色温度設定1',
'Set Color Temperature 2' => '色温度設定2',
'Set Color Temperature 3' => '色温度設定3',
'Shade' => '日陰',
'Tungsten' => 'タングステン(白熱灯)',
'White Fluorescent' => '温白色蛍光灯',
},
},
'WhiteBalanceTemperature' => 'ホワイトバランス温度',
'WhiteBoard' => 'ホワイトボード',
'WhiteLevel' => '白レベル',
'WhitePoint' => '白点色度',
'Wide' => 'ワイド',
'WideFocusZone' => 'ワイドフォーカスゾーン',
'WideRange' => {
Description => 'ワイドレンジ',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'WidthResolution' => '幅方向の画像解像度',
'WorldTime' => 'タイムゾーン',
'WorldTimeLocation' => {
Description => 'ワールドタイム位置',
PrintConv => {
'Destination' => '目的地',
'Home' => '自宅',
'Hometown' => '現在地',
},
},
'Writer-Editor' => '表題/説明の作家',
'X3FillLight' => 'X3光を満たす',
'XClipPathUnits' => 'Xクリップパス単位',
'XMP' => 'XMPメタデータ',
'XPAuthor' => '作者',
'XPComment' => 'コメント',
'XPKeywords' => 'キーワード',
'XPSubject' => 'サブジェクト',
'XPTitle' => 'タイトル',
'XPosition' => 'X位置',
'XResolution' => '画像幅の解像度',
'YCbCrCoefficients' => 'カラースペース変化マトリックス係数',
'YCbCrPositioning' => {
Description => 'YとCの位置',
PrintConv => {
'Centered' => '中央',
'Co-sited' => '相互配置',
},
},
'YCbCrSubSampling' => 'YとCのサブサンプリング比率',
'YClipPathUnits' => 'Yクリップパス単位',
'YPosition' => 'Y位置',
'YResolution' => '画像高さの解像度',
'ZoneMatching' => {
Description => 'ゾーンマッチング',
PrintConv => {
'High Key' => 'ハイキー',
'ISO Setting Used' => 'オフ(ISO設定使用)',
'Low Key' => 'ローキー',
},
},
'ZoneMatchingOn' => {
Description => 'ゾーンマッチング',
PrintConv => {
'Off' => 'オフ',
'On' => 'オン',
},
},
'Zoom' => 'ズーム',
'ZoomSourceWidth' => 'ズームソース幅',
'ZoomStepCount' => 'ズームステップ数',
'ZoomTargetWidth' => 'ズームターゲット幅',
);
1; # end
__END__
=head1 NAME
Image::ExifTool::Lang::ja.pm - ExifTool Japanese language translations
=head1 DESCRIPTION
This file is used by Image::ExifTool to generate localized tag descriptions
and values.
=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 ACKNOWLEDGEMENTS
Thanks to Jens Duttke and Kazunari Nishina for providing this translation.
=head1 SEE ALSO
L<Image::ExifTool(3pm)|Image::ExifTool>,
L<Image::ExifTool::TagInfoXML(3pm)|Image::ExifTool::TagInfoXML>
=cut
| wilg/mini_exiftool_vendored | vendor/Image-ExifTool-9.27/lib/Image/ExifTool/Lang/ja.pm | Perl | mit | 207,422 |
package SDBM_File;
use strict;
use warnings;
require Tie::Hash;
require XSLoader;
our @ISA = qw(Tie::Hash);
our $VERSION = "1.14";
our @EXPORT_OK = qw(PAGFEXT DIRFEXT PAIRMAX);
use Exporter "import";
XSLoader::load();
1;
__END__
=head1 NAME
SDBM_File - Tied access to sdbm files
=head1 SYNOPSIS
use Fcntl; # For O_RDWR, O_CREAT, etc.
use SDBM_File;
tie(%h, 'SDBM_File', 'filename', O_RDWR|O_CREAT, 0666)
or die "Couldn't tie SDBM file 'filename': $!; aborting";
# Now read and change the hash
$h{newkey} = newvalue;
print $h{oldkey};
...
untie %h;
=head1 DESCRIPTION
C<SDBM_File> establishes a connection between a Perl hash variable and
a file in SDBM_File format. You can manipulate the data in the file
just as if it were in a Perl hash, but when your program exits, the
data will remain in the file, to be used the next time your program
runs.
=head2 Tie
Use C<SDBM_File> with the Perl built-in C<tie> function to establish
the connection between the variable and the file.
tie %hash, 'SDBM_File', $basename, $modeflags, $perms;
tie %hash, 'SDBM_File', $dirfile, $modeflags, $perms, $pagfilename;
C<$basename> is the base filename for the database. The database is two
files with ".dir" and ".pag" extensions appended to C<$basename>,
$basename.dir (or .sdbm_dir on VMS, per DIRFEXT constant)
$basename.pag
The two filenames can also be given separately in full as C<$dirfile>
and C<$pagfilename>. This suits for two files without ".dir" and ".pag"
extensions, perhaps for example two files from L<File::Temp>.
C<$modeflags> can be the following constants from the C<Fcntl> module (in
the style of the L<open(2)> system call),
O_RDONLY read-only access
O_WRONLY write-only access
O_RDWR read and write access
If you want to create the file if it does not already exist then bitwise-OR
(C<|>) C<O_CREAT> too. If you omit C<O_CREAT> and the database does not
already exist then the C<tie> call will fail.
O_CREAT create database if doesn't already exist
C<$perms> is the file permissions bits to use if new database files are
created. This parameter is mandatory even when not creating a new database.
The permissions will be reduced by the user's umask so the usual value here
would be 0666, or if some very private data then 0600. (See
L<perlfunc/umask>.)
=head1 EXPORTS
SDBM_File optionally exports the following constants:
=over
=item *
C<PAGFEXT> - the extension used for the page file, usually C<.pag>.
=item *
C<DIRFEXT> - the extension used for the directory file, C<.dir>
everywhere but VMS, where it is C<.sdbm_dir>.
=item *
C<PAIRMAX> - the maximum size of a stored hash entry, including the
length of both the key and value.
=back
These constants can also be used with fully qualified names,
eg. C<SDBM_File::PAGFEXT>.
=head1 DIAGNOSTICS
On failure, the C<tie> call returns an undefined value and probably
sets C<$!> to contain the reason the file could not be tied.
=head2 C<sdbm store returned -1, errno 22, key "..." at ...>
This warning is emitted when you try to store a key or a value that
is too long. It means that the change was not recorded in the
database. See BUGS AND WARNINGS below.
=head1 BUGS AND WARNINGS
There are a number of limits on the size of the data that you can
store in the SDBM file. The most important is that the length of a
key, plus the length of its associated value, may not exceed 1008
bytes.
See L<perlfunc/tie>, L<perldbmfilter>, L<Fcntl>
=cut
| operepo/ope | bin/usr/lib/perl5/core_perl/SDBM_File.pm | Perl | mit | 3,540 |
#!/usr/bin/perl -w
use strict;
use encoding 'utf8';
binmode(STDIN, ":utf8");
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
print "[+] Checking whether docker is running.\n";
my $service_status = `systemctl status docker.service`;
#print $service_status;
if($service_status =~ m/Active: inactive/) {
print "[+] Docker was inactive, starting it now.\n";
`sudo systemctl start docker.service`;
} else {
print "[+] Docker is already active.\n";
}
1;
| xunzhang/dynet | examples/tensorboard/rundocker.perl | Perl | apache-2.0 | 471 |
package HTTP::AppServer;
# Simple CRUD server for JSON objects and plain files.
# 2010 by Tom Kirchner
#
# routes:
# POST /create = erzeugt neues JSON-Dokument, liefert UUId zurueck
# GET /read/<uuid> = liefert JSON-Dokument oder Fehler zurueck
# POST /update/<uuid> = aendert JSON-Dokument (erzeugt neue Revision)
# GET /delete/<uuid> = loescht JSON-Dokument
# GET /file/<filename> = gibt Datei innerhalb Document-Root zurueck
#use 5.010000;
use strict;
use warnings;
use Data::Dumper;
use HTTP::AppServer::Base;
our $VERSION = '0.04';
sub new
{
my ($class, @args) = @_;
my $self = bless {}, $class;
return $self->init(@args);
}
sub init
{
my ($self, %opts) = @_;
# server options defaults
my %defaults = (StartBackground => 0, ServerPort => 3000, IPV6 => 0);
# set options or use defaults
map { $self->{$_} = (exists $opts{$_} ? $opts{$_} : $defaults{$_}) }
keys %defaults;
if ($self->{'IPV6'}) {
$self->{'server'} = HTTP::AppServer::Base->new($self->{'ServerPort'}, Socket::AF_INET6);
}
else {
$self->{'server'} = HTTP::AppServer::Base->new($self->{'ServerPort'});
}
return $self;
}
sub handle
{
my ($self, %pairs) = @_;
map { $self->{'server'}->handle($_, $pairs{$_}) } keys %pairs;
return 1;
}
sub plugin
{
my ($self, $name, %options) = @_;
# load module
eval('use HTTP::AppServer::Plugin::'.$name);
die "Failed to load plugin '$name': $@\n" if $@;
# call init() method of module to get the handlers of the plugin
eval('$self->handle( HTTP::AppServer::Plugin::'.$name.'->init($self->{"server"}, %options))');
die "Failed to install handlers for plugin '$name': $@\n" if $@;
}
sub start
{
my ($self) = @_;
$self->{'server'}->debug();
# start the server on port
if ($self->{'StartBackground'}) {
my $pid = $self->{'server'}->background();
print "Server started (http://localhost:$self->{'ServerPort'}) with PID $pid\n";
} else {
print "Server started (http://localhost:$self->{'ServerPort'})\n";
my $pid = $self->{'server'}->run();
}
}
1;
__END__
# Below is stub documentation for your module. You'd better edit it!
=head1 NAME
HTTP::AppServer - Pure-Perl web application server framework
=head1 SYNOPSIS
use HTTP::AppServer;
# create server instance at localhost:3000
my $server = HTTP::AppServer->new( StartBackground => 0, ServerPort => 3000 );
# alias URL
$server->handle('^\/$', '/index.html');
# load plugin for simple file retrieving from a document root
$server->plugin('FileRetriever', DocRoot => '/path/to/docroot');
# start server
$server->start;
=head1 DESCRIPTION
HTTP::AppServer was created because a stripped down Perl based
web server was needed that is extendable and really simple to use.
=head2 Creating server
To create a server instance, call the new() class method of
HTTP::AppServer, e.g.:
my $server = HTTP::AppServer->new( StartBackground => 0, ServerPort => 3000 );
=head3 Constructor options
=head4 StartBackground => 1/0
Defines if the server should be startet in background mode or not.
Default is to NOT start in background.
=head4 ServerPort => I<Port>
Defines the local port the server listens to.
Default is to listen at port 3000.
=head2 Installing URL handlers
The main purpose of having a webserver is to make it able to
bind URLs to server side logic or content. To install such a
binding in your instance of HTTP::AppServer, you can use
the handle() method.
The URL is given as a Perl regular expression, e.g.
'^\/hi'
matches all URLs starting with '/hi' and anything coming after that.
You can either install a perl code reference that handles the URL:
$server->handle('^\/hello$', sub {
my ($server, $cgi) = @_;
print "HTTP/1.0 200 Ok\r\n";
print $cgi->header('text/html');
print "Hello, visitor!";
});
Or you can
$server->handle('^\/$', '/index.html');
In this example: whenever a URL matches a '/' at the beginning, the URL
is transformed into '/index.html' and HTTP::AppServer tries to find
a handler that handles that URL.
In case of a code reference handler (first example) the parameters
passed to the code reference are first the serve instance and
second the cgi object (instance of CGI). The second comes in handy
when creating HTTP headers and such.
Additional parameters are the groups defined in the regular expression
that matches the URL which brings us to the variable URL parts...
=head3 Variable URL parts
Suppose you want to match a URL that contains a variable ID of
some sort and another part that is variable. You could do it
this way:
$server->handle('^\/(a|b|c)\/(\d+)', sub {
my ($server, $cgi, $category, $id) = @_;
# ...
});
As you can see, the two groups in the regular expression are passed
as additional parameters to the code reference.
=head3 Multimatching vs. Singlematching
Each called handler (code reference) can tell HTTP::AppServer if
it should continue looking for another matching handler or not.
To make HTTP::AppServer continue searching after the handler,
the handler has to return 0. If anything else is returned,
HTTP::AppServer tries to find another matching handler.
A handler is executed once at most (even if it matches multiple
times).
=head2 Using plugins
Use the plugin() method to load and configure a plugin, e.g.:
$server->plugin('FileRetriever', DocRoot => '/path/to/docroot');
The first parameter is the name of the plugin, a class
in the HTTP::AppServer::Plugin:: namespace. After that configuration
options follow, see plugin documentation for details on that.
=head3 Plugin development
See HTTP::AppServer::Plugin
=head2 Handler precedence
When HTTP::AppServer tries to find a handler for an URL it goes
through the list of installed handlers (either by user or a plugin)
and the first that matches, is used.
As described above, each handler can tell if he wants the output
beeing delivered to the client OR continue find another handler.
=head2 Core plugins
These plugins are delivered with HTTP::AppServer itself:
=head3 HTTP::AppServer::Plugin::HTTPAuth
See HTTP::AppServer::Plugin::HTTPAuth for documentation.
=head3 HTTP::AppServer::Plugin::CustomError
See HTTP::AppServer::Plugin::CustomError for documentation.
=head3 HTTP::AppServer::Plugin::Database
See for HTTP::AppServer::Plugin::Database documentation.
=head3 HTTP::AppServer::Plugin::FileRetriever
See for HTTP::AppServer::Plugin::FileRetriever documentation.
=head3 HTTP::AppServer::Plugin::PlainHTML
See for HTTP::AppServer::Plugin::PlainHTML documentation.
=head1 SEE ALSO
HTTP::Server::Simple::CGI
=head1 AUTHOR
Tom Kirchner, E<lt>tom@tkirchner.comE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2010 by Tom Kirchner
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.
=cut
| btovar/cvmfs | test/mock_services/HTTP/AppServer.pm | Perl | bsd-3-clause | 6,913 |
=head1 NAME
perlfaq4 - Data Manipulation
=head1 DESCRIPTION
This section of the FAQ answers questions related to manipulating
numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
=head1 Data: Numbers
=head2 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
For the long explanation, see David Goldberg's "What Every Computer
Scientist Should Know About Floating-Point Arithmetic"
(L<http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf>).
Internally, your computer represents floating-point numbers in binary.
Digital (as in powers of two) computers cannot store all numbers
exactly. Some real numbers lose precision in the process. This is a
problem with how computers store numbers and affects all computer
languages, not just Perl.
L<perlnumber> shows the gory details of number representations and
conversions.
To limit the number of decimal places in your numbers, you can use the
C<printf> or C<sprintf> function. See
L<perlop/"Floating-point Arithmetic"> for more details.
printf "%.2f", 10/3;
my $number = sprintf "%.2f", 10/3;
=head2 Why is int() broken?
Your C<int()> is most probably working just fine. It's the numbers that
aren't quite what you think.
First, see the answer to "Why am I getting long decimals
(eg, 19.9499999999999) instead of the numbers I should be getting
(eg, 19.95)?".
For example, this
print int(0.6/0.2-2), "\n";
will in most computers print 0, not 1, because even such simple
numbers as 0.6 and 0.2 cannot be presented exactly by floating-point
numbers. What you think in the above as 'three' is really more like
2.9999999999999995559.
=head2 Why isn't my octal data interpreted correctly?
(contributed by brian d foy)
You're probably trying to convert a string to a number, which Perl only
converts as a decimal number. When Perl converts a string to a number, it
ignores leading spaces and zeroes, then assumes the rest of the digits
are in base 10:
my $string = '0644';
print $string + 0; # prints 644
print $string + 44; # prints 688, certainly not octal!
This problem usually involves one of the Perl built-ins that has the
same name a Unix command that uses octal numbers as arguments on the
command line. In this example, C<chmod> on the command line knows that
its first argument is octal because that's what it does:
%prompt> chmod 644 file
If you want to use the same literal digits (644) in Perl, you have to tell
Perl to treat them as octal numbers either by prefixing the digits with
a C<0> or using C<oct>:
chmod( 0644, $filename ); # right, has leading zero
chmod( oct(644), $filename ); # also correct
The problem comes in when you take your numbers from something that Perl
thinks is a string, such as a command line argument in C<@ARGV>:
chmod( $ARGV[0], $filename ); # wrong, even if "0644"
chmod( oct($ARGV[0]), $filename ); # correct, treat string as octal
You can always check the value you're using by printing it in octal
notation to ensure it matches what you think it should be. Print it
in octal and decimal format:
printf "0%o %d", $number, $number;
=head2 Does Perl have a round() function? What about ceil() and floor()? Trig functions?
Remember that C<int()> merely truncates toward 0. For rounding to a
certain number of digits, C<sprintf()> or C<printf()> is usually the
easiest route.
printf("%.3f", 3.1415926535); # prints 3.142
The L<POSIX> module (part of the standard Perl distribution)
implements C<ceil()>, C<floor()>, and a number of other mathematical
and trigonometric functions.
use POSIX;
my $ceil = ceil(3.5); # 4
my $floor = floor(3.5); # 3
In 5.000 to 5.003 perls, trigonometry was done in the L<Math::Complex>
module. With 5.004, the L<Math::Trig> module (part of the standard Perl
distribution) implements the trigonometric functions. Internally it
uses the L<Math::Complex> module and some functions can break out from
the real axis into the complex plane, for example the inverse sine of
2.
Rounding in financial applications can have serious implications, and
the rounding method used should be specified precisely. In these
cases, it probably pays not to trust whichever system of rounding is
being used by Perl, but instead to implement the rounding function you
need yourself.
To see why, notice how you'll still have an issue on half-way-point
alternation:
for (my $i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}
0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
0.8 0.8 0.9 0.9 1.0 1.0
Don't blame Perl. It's the same as in C. IEEE says we have to do
this. Perl numbers whose absolute values are integers under 2**31 (on
32-bit machines) will work pretty much like mathematical integers.
Other numbers are not guaranteed.
=head2 How do I convert between numeric representations/bases/radixes?
As always with Perl there is more than one way to do it. Below are a
few examples of approaches to making common conversions between number
representations. This is intended to be representational rather than
exhaustive.
Some of the examples later in L<perlfaq4> use the L<Bit::Vector>
module from CPAN. The reason you might choose L<Bit::Vector> over the
perl built-in functions is that it works with numbers of ANY size,
that it is optimized for speed on some operations, and for at least
some programmers the notation might be familiar.
=over 4
=item How do I convert hexadecimal into decimal
Using perl's built in conversion of C<0x> notation:
my $dec = 0xDEADBEEF;
Using the C<hex> function:
my $dec = hex("DEADBEEF");
Using C<pack>:
my $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8)));
Using the CPAN module C<Bit::Vector>:
use Bit::Vector;
my $vec = Bit::Vector->new_Hex(32, "DEADBEEF");
my $dec = $vec->to_Dec();
=item How do I convert from decimal to hexadecimal
Using C<sprintf>:
my $hex = sprintf("%X", 3735928559); # upper case A-F
my $hex = sprintf("%x", 3735928559); # lower case a-f
Using C<unpack>:
my $hex = unpack("H*", pack("N", 3735928559));
Using L<Bit::Vector>:
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $hex = $vec->to_Hex();
And L<Bit::Vector> supports odd bit counts:
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(33, 3735928559);
$vec->Resize(32); # suppress leading 0 if unwanted
my $hex = $vec->to_Hex();
=item How do I convert from octal to decimal
Using Perl's built in conversion of numbers with leading zeros:
my $dec = 033653337357; # note the leading 0!
Using the C<oct> function:
my $dec = oct("33653337357");
Using L<Bit::Vector>:
use Bit::Vector;
my $vec = Bit::Vector->new(32);
$vec->Chunk_List_Store(3, split(//, reverse "33653337357"));
my $dec = $vec->to_Dec();
=item How do I convert from decimal to octal
Using C<sprintf>:
my $oct = sprintf("%o", 3735928559);
Using L<Bit::Vector>:
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $oct = reverse join('', $vec->Chunk_List_Read(3));
=item How do I convert from binary to decimal
Perl 5.6 lets you write binary numbers directly with
the C<0b> notation:
my $number = 0b10110110;
Using C<oct>:
my $input = "10110110";
my $decimal = oct( "0b$input" );
Using C<pack> and C<ord>:
my $decimal = ord(pack('B8', '10110110'));
Using C<pack> and C<unpack> for larger strings:
my $int = unpack("N", pack("B32",
substr("0" x 32 . "11110101011011011111011101111", -32)));
my $dec = sprintf("%d", $int);
# substr() is used to left-pad a 32-character string with zeros.
Using L<Bit::Vector>:
my $vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111");
my $dec = $vec->to_Dec();
=item How do I convert from decimal to binary
Using C<sprintf> (perl 5.6+):
my $bin = sprintf("%b", 3735928559);
Using C<unpack>:
my $bin = unpack("B*", pack("N", 3735928559));
Using L<Bit::Vector>:
use Bit::Vector;
my $vec = Bit::Vector->new_Dec(32, -559038737);
my $bin = $vec->to_Bin();
The remaining transformations (e.g. hex -> oct, bin -> hex, etc.)
are left as an exercise to the inclined reader.
=back
=head2 Why doesn't & work the way I want it to?
The behavior of binary arithmetic operators depends on whether they're
used on numbers or strings. The operators treat a string as a series
of bits and work with that (the string C<"3"> is the bit pattern
C<00110011>). The operators work with the binary form of a number
(the number C<3> is treated as the bit pattern C<00000011>).
So, saying C<11 & 3> performs the "and" operation on numbers (yielding
C<3>). Saying C<"11" & "3"> performs the "and" operation on strings
(yielding C<"1">).
Most problems with C<&> and C<|> arise because the programmer thinks
they have a number but really it's a string or vice versa. To avoid this,
stringify the arguments explicitly (using C<""> or C<qq()>) or convert them
to numbers explicitly (using C<0+$arg>). The rest arise because
the programmer says:
if ("\020\020" & "\101\101") {
# ...
}
but a string consisting of two null bytes (the result of C<"\020\020"
& "\101\101">) is not a false value in Perl. You need:
if ( ("\020\020" & "\101\101") !~ /[^\000]/) {
# ...
}
=head2 How do I multiply matrices?
Use the L<Math::Matrix> or L<Math::MatrixReal> modules (available from CPAN)
or the L<PDL> extension (also available from CPAN).
=head2 How do I perform an operation on a series of integers?
To call a function on each element in an array, and collect the
results, use:
my @results = map { my_func($_) } @array;
For example:
my @triple = map { 3 * $_ } @single;
To call a function on each element of an array, but ignore the
results:
foreach my $iterator (@array) {
some_func($iterator);
}
To call a function on each integer in a (small) range, you B<can> use:
my @results = map { some_func($_) } (5 .. 25);
but you should be aware that in this form, the C<..> operator
creates a list of all integers in the range, which can take a lot of
memory for large ranges. However, the problem does not occur when
using C<..> within a C<for> loop, because in that case the range
operator is optimized to I<iterate> over the range, without creating
the entire list. So
my @results = ();
for my $i (5 .. 500_005) {
push(@results, some_func($i));
}
or even
push(@results, some_func($_)) for 5 .. 500_005;
will not create an intermediate list of 500,000 integers.
=head2 How can I output Roman numerals?
Get the L<http://www.cpan.org/modules/by-module/Roman> module.
=head2 Why aren't my random numbers random?
If you're using a version of Perl before 5.004, you must call C<srand>
once at the start of your program to seed the random number generator.
BEGIN { srand() if $] < 5.004 }
5.004 and later automatically call C<srand> at the beginning. Don't
call C<srand> more than once--you make your numbers less random,
rather than more.
Computers are good at being predictable and bad at being random
(despite appearances caused by bugs in your programs :-). The
F<random> article in the "Far More Than You Ever Wanted To Know"
collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz>, courtesy
of Tom Phoenix, talks more about this. John von Neumann said, "Anyone
who attempts to generate random numbers by deterministic means is, of
course, living in a state of sin."
Perl relies on the underlying system for the implementation of
C<rand> and C<srand>; on some systems, the generated numbers are
not random enough (especially on Windows : see
L<http://www.perlmonks.org/?node_id=803632>).
Several CPAN modules in the C<Math> namespace implement better
pseudorandom generators; see for example
L<Math::Random::MT> ("Mersenne Twister", fast), or
L<Math::TrulyRandom> (uses the imperfections in the system's
timer to generate random numbers, which is rather slow).
More algorithms for random numbers are described in
"Numerical Recipes in C" at L<http://www.nr.com/>
=head2 How do I get a random number between X and Y?
To get a random number between two values, you can use the C<rand()>
built-in to get a random number between 0 and 1. From there, you shift
that into the range that you want.
C<rand($x)> returns a number such that C<< 0 <= rand($x) < $x >>. Thus
what you want to have perl figure out is a random number in the range
from 0 to the difference between your I<X> and I<Y>.
That is, to get a number between 10 and 15, inclusive, you want a
random number between 0 and 5 that you can then add to 10.
my $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )
Hence you derive the following simple function to abstract
that. It selects a random integer between the two given
integers (inclusive), For example: C<random_int_between(50,120)>.
sub random_int_between {
my($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}
=head1 Data: Dates
=head2 How do I find the day or week of the year?
The day of the year is in the list returned
by the C<localtime> function. Without an
argument C<localtime> uses the current time.
my $day_of_year = (localtime)[7];
The L<POSIX> module can also format a date as the day of the year or
week of the year.
use POSIX qw/strftime/;
my $day_of_year = strftime "%j", localtime;
my $week_of_year = strftime "%W", localtime;
To get the day of year for any date, use L<POSIX>'s C<mktime> to get
a time in epoch seconds for the argument to C<localtime>.
use POSIX qw/mktime strftime/;
my $week_of_year = strftime "%W",
localtime( mktime( 0, 0, 0, 18, 11, 87 ) );
You can also use L<Time::Piece>, which comes with Perl and provides a
C<localtime> that returns an object:
use Time::Piece;
my $day_of_year = localtime->yday;
my $week_of_year = localtime->week;
The L<Date::Calc> module provides two functions to calculate these, too:
use Date::Calc;
my $day_of_year = Day_of_Year( 1987, 12, 18 );
my $week_of_year = Week_of_Year( 1987, 12, 18 );
=head2 How do I find the current century or millennium?
Use the following simple functions:
sub get_century {
return int((((localtime(shift || time))[5] + 1999))/100);
}
sub get_millennium {
return 1+int((((localtime(shift || time))[5] + 1899))/1000);
}
On some systems, the L<POSIX> module's C<strftime()> function has been
extended in a non-standard way to use a C<%C> format, which they
sometimes claim is the "century". It isn't, because on most such
systems, this is only the first two digits of the four-digit year, and
thus cannot be used to determine reliably the current century or
millennium.
=head2 How can I compare two dates and find the difference?
(contributed by brian d foy)
You could just store all your dates as a number and then subtract.
Life isn't always that simple though.
The L<Time::Piece> module, which comes with Perl, replaces L<localtime>
with a version that returns an object. It also overloads the comparison
operators so you can compare them directly:
use Time::Piece;
my $date1 = localtime( $some_time );
my $date2 = localtime( $some_other_time );
if( $date1 < $date2 ) {
print "The date was in the past\n";
}
You can also get differences with a subtraction, which returns a
L<Time::Seconds> object:
my $diff = $date1 - $date2;
print "The difference is ", $date_diff->days, " days\n";
If you want to work with formatted dates, the L<Date::Manip>,
L<Date::Calc>, or L<DateTime> modules can help you.
=head2 How can I take a string and turn it into epoch seconds?
If it's a regular enough string that it always has the same format,
you can split it up and pass the parts to C<timelocal> in the standard
L<Time::Local> module. Otherwise, you should look into the L<Date::Calc>,
L<Date::Parse>, and L<Date::Manip> modules from CPAN.
=head2 How can I find the Julian Day?
(contributed by brian d foy and Dave Cross)
You can use the L<Time::Piece> module, part of the Standard Library,
which can convert a date/time to a Julian Day:
$ perl -MTime::Piece -le 'print localtime->julian_day'
2455607.7959375
Or the modified Julian Day:
$ perl -MTime::Piece -le 'print localtime->mjd'
55607.2961226851
Or even the day of the year (which is what some people think of as a
Julian day):
$ perl -MTime::Piece -le 'print localtime->yday'
45
You can also do the same things with the L<DateTime> module:
$ perl -MDateTime -le'print DateTime->today->jd'
2453401.5
$ perl -MDateTime -le'print DateTime->today->mjd'
53401
$ perl -MDateTime -le'print DateTime->today->doy'
31
You can use the L<Time::JulianDay> module available on CPAN. Ensure
that you really want to find a Julian day, though, as many people have
different ideas about Julian days (see L<http://www.hermetic.ch/cal_stud/jdn.htm>
for instance):
$ perl -MTime::JulianDay -le 'print local_julian_day( time )'
55608
=head2 How do I find yesterday's date?
X<date> X<yesterday> X<DateTime> X<Date::Calc> X<Time::Local>
X<daylight saving time> X<day> X<Today_and_Now> X<localtime>
X<timelocal>
(contributed by brian d foy)
To do it correctly, you can use one of the C<Date> modules since they
work with calendars instead of times. The L<DateTime> module makes it
simple, and give you the same time of day, only the day before,
despite daylight saving time changes:
use DateTime;
my $yesterday = DateTime->now->subtract( days => 1 );
print "Yesterday was $yesterday\n";
You can also use the L<Date::Calc> module using its C<Today_and_Now>
function.
use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 );
print "@date_time\n";
Most people try to use the time rather than the calendar to figure out
dates, but that assumes that days are twenty-four hours each. For
most people, there are two days a year when they aren't: the switch to
and from summer time throws this off. For example, the rest of the
suggestions will be wrong sometimes:
Starting with Perl 5.10, L<Time::Piece> and L<Time::Seconds> are part
of the standard distribution, so you might think that you could do
something like this:
use Time::Piece;
use Time::Seconds;
my $yesterday = localtime() - ONE_DAY; # WRONG
print "Yesterday was $yesterday\n";
The L<Time::Piece> module exports a new C<localtime> that returns an
object, and L<Time::Seconds> exports the C<ONE_DAY> constant that is a
set number of seconds. This means that it always gives the time 24
hours ago, which is not always yesterday. This can cause problems
around the end of daylight saving time when there's one day that is 25
hours long.
You have the same problem with L<Time::Local>, which will give the wrong
answer for those same special cases:
# contributed by Gunnar Hjalmarsson
use Time::Local;
my $today = timelocal 0, 0, 12, ( localtime )[3..5];
my ($d, $m, $y) = ( localtime $today-86400 )[3..5]; # WRONG
printf "Yesterday: %d-%02d-%02d\n", $y+1900, $m+1, $d;
=head2 Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?
(contributed by brian d foy)
Perl itself never had a Y2K problem, although that never stopped people
from creating Y2K problems on their own. See the documentation for
C<localtime> for its proper use.
Starting with Perl 5.12, C<localtime> and C<gmtime> can handle dates past
03:14:08 January 19, 2038, when a 32-bit based time would overflow. You
still might get a warning on a 32-bit C<perl>:
% perl5.12 -E 'say scalar localtime( 0x9FFF_FFFFFFFF )'
Integer overflow in hexadecimal number at -e line 1.
Wed Nov 1 19:42:39 5576711
On a 64-bit C<perl>, you can get even larger dates for those really long
running projects:
% perl5.12 -E 'say scalar gmtime( 0x9FFF_FFFFFFFF )'
Thu Nov 2 00:42:39 5576711
You're still out of luck if you need to keep track of decaying protons
though.
=head1 Data: Strings
=head2 How do I validate input?
(contributed by brian d foy)
There are many ways to ensure that values are what you expect or
want to accept. Besides the specific examples that we cover in the
perlfaq, you can also look at the modules with "Assert" and "Validate"
in their names, along with other modules such as L<Regexp::Common>.
Some modules have validation for particular types of input, such
as L<Business::ISBN>, L<Business::CreditCard>, L<Email::Valid>,
and L<Data::Validate::IP>.
=head2 How do I unescape a string?
It depends just what you mean by "escape". URL escapes are dealt
with in L<perlfaq9>. Shell escapes with the backslash (C<\>)
character are removed with
s/\\(.)/$1/g;
This won't expand C<"\n"> or C<"\t"> or any other special escapes.
=head2 How do I remove consecutive pairs of characters?
(contributed by brian d foy)
You can use the substitution operator to find pairs of characters (or
runs of characters) and replace them with a single instance. In this
substitution, we find a character in C<(.)>. The memory parentheses
store the matched character in the back-reference C<\g1> and we use
that to require that the same thing immediately follow it. We replace
that part of the string with the character in C<$1>.
s/(.)\g1/$1/g;
We can also use the transliteration operator, C<tr///>. In this
example, the search list side of our C<tr///> contains nothing, but
the C<c> option complements that so it contains everything. The
replacement list also contains nothing, so the transliteration is
almost a no-op since it won't do any replacements (or more exactly,
replace the character with itself). However, the C<s> option squashes
duplicated and consecutive characters in the string so a character
does not show up next to itself
my $str = 'Haarlem'; # in the Netherlands
$str =~ tr///cs; # Now Harlem, like in New York
=head2 How do I expand function calls in a string?
(contributed by brian d foy)
This is documented in L<perlref>, and although it's not the easiest
thing to read, it does work. In each of these examples, we call the
function inside the braces used to dereference a reference. If we
have more than one return value, we can construct and dereference an
anonymous array. In this case, we call the function in list context.
print "The time values are @{ [localtime] }.\n";
If we want to call the function in scalar context, we have to do a bit
more work. We can really have any code we like inside the braces, so
we simply have to end with the scalar reference, although how you do
that is up to you, and you can use code inside the braces. Note that
the use of parens creates a list context, so we need C<scalar> to
force the scalar context on the function:
print "The time is ${\(scalar localtime)}.\n"
print "The time is ${ my $x = localtime; \$x }.\n";
If your function already returns a reference, you don't need to create
the reference yourself.
sub timestamp { my $t = localtime; \$t }
print "The time is ${ timestamp() }.\n";
The C<Interpolation> module can also do a lot of magic for you. You can
specify a variable name, in this case C<E>, to set up a tied hash that
does the interpolation for you. It has several other methods to do this
as well.
use Interpolation E => 'eval';
print "The time values are $E{localtime()}.\n";
In most cases, it is probably easier to simply use string concatenation,
which also forces scalar context.
print "The time is " . localtime() . ".\n";
=head2 How do I find matching/nesting anything?
To find something between two single
characters, a pattern like C</x([^x]*)x/> will get the intervening
bits in $1. For multiple ones, then something more like
C</alpha(.*?)omega/> would be needed. For nested patterns
and/or balanced expressions, see the so-called
L<< (?PARNO)|perlre/C<(?PARNO)> C<(?-PARNO)> C<(?+PARNO)> C<(?R)> C<(?0)> >>
construct (available since perl 5.10).
The CPAN module L<Regexp::Common> can help to build such
regular expressions (see in particular
L<Regexp::Common::balanced> and L<Regexp::Common::delimited>).
More complex cases will require to write a parser, probably
using a parsing module from CPAN, like
L<Regexp::Grammars>, L<Parse::RecDescent>, L<Parse::Yapp>,
L<Text::Balanced>, or L<Marpa::XS>.
=head2 How do I reverse a string?
Use C<reverse()> in scalar context, as documented in
L<perlfunc/reverse>.
my $reversed = reverse $string;
=head2 How do I expand tabs in a string?
You can do it yourself:
1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
Or you can just use the L<Text::Tabs> module (part of the standard Perl
distribution).
use Text::Tabs;
my @expanded_lines = expand(@lines_with_tabs);
=head2 How do I reformat a paragraph?
Use L<Text::Wrap> (part of the standard Perl distribution):
use Text::Wrap;
print wrap("\t", ' ', @paragraphs);
The paragraphs you give to L<Text::Wrap> should not contain embedded
newlines. L<Text::Wrap> doesn't justify the lines (flush-right).
Or use the CPAN module L<Text::Autoformat>. Formatting files can be
easily done by making a shell alias, like so:
alias fmt="perl -i -MText::Autoformat -n0777 \
-e 'print autoformat $_, {all=>1}' $*"
See the documentation for L<Text::Autoformat> to appreciate its many
capabilities.
=head2 How can I access or change N characters of a string?
You can access the first characters of a string with substr().
To get the first character, for example, start at position 0
and grab the string of length 1.
my $string = "Just another Perl Hacker";
my $first_char = substr( $string, 0, 1 ); # 'J'
To change part of a string, you can use the optional fourth
argument which is the replacement string.
substr( $string, 13, 4, "Perl 5.8.0" );
You can also use substr() as an lvalue.
substr( $string, 13, 4 ) = "Perl 5.8.0";
=head2 How do I change the Nth occurrence of something?
You have to keep track of N yourself. For example, let's say you want
to change the fifth occurrence of C<"whoever"> or C<"whomever"> into
C<"whosoever"> or C<"whomsoever">, case insensitively. These
all assume that $_ contains the string to be altered.
$count = 0;
s{((whom?)ever)}{
++$count == 5 # is it the 5th?
? "${2}soever" # yes, swap
: $1 # renege and leave it there
}ige;
In the more general case, you can use the C</g> modifier in a C<while>
loop, keeping count of matches.
$WANT = 3;
$count = 0;
$_ = "One fish two fish red fish blue fish";
while (/(\w+)\s+fish\b/gi) {
if (++$count == $WANT) {
print "The third fish is a $1 one.\n";
}
}
That prints out: C<"The third fish is a red one."> You can also use a
repetition count and repeated pattern like this:
/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;
=head2 How can I count the number of occurrences of a substring within a string?
There are a number of ways, with varying efficiency. If you want a
count of a certain single character (X) within a string, you can use the
C<tr///> function like so:
my $string = "ThisXlineXhasXsomeXx'sXinXit";
my $count = ($string =~ tr/X//);
print "There are $count X characters in the string";
This is fine if you are just looking for a single character. However,
if you are trying to count multiple character substrings within a
larger string, C<tr///> won't work. What you can do is wrap a while()
loop around a global pattern match. For example, let's count negative
integers:
my $string = "-9 55 48 -2 23 -76 4 14 -44";
my $count = 0;
while ($string =~ /-\d+/g) { $count++ }
print "There are $count negative numbers in the string";
Another version uses a global match in list context, then assigns the
result to a scalar, producing a count of the number of matches.
my $count = () = $string =~ /-\d+/g;
=head2 How do I capitalize all the words on one line?
X<Text::Autoformat> X<capitalize> X<case, title> X<case, sentence>
(contributed by brian d foy)
Damian Conway's L<Text::Autoformat> handles all of the thinking
for you.
use Text::Autoformat;
my $x = "Dr. Strangelove or: How I Learned to Stop ".
"Worrying and Love the Bomb";
print $x, "\n";
for my $style (qw( sentence title highlight )) {
print autoformat($x, { case => $style }), "\n";
}
How do you want to capitalize those words?
FRED AND BARNEY'S LODGE # all uppercase
Fred And Barney's Lodge # title case
Fred and Barney's Lodge # highlight case
It's not as easy a problem as it looks. How many words do you think
are in there? Wait for it... wait for it.... If you answered 5
you're right. Perl words are groups of C<\w+>, but that's not what
you want to capitalize. How is Perl supposed to know not to capitalize
that C<s> after the apostrophe? You could try a regular expression:
$string =~ s/ (
(^\w) #at the beginning of the line
| # or
(\s\w) #preceded by whitespace
)
/\U$1/xg;
$string =~ s/([\w']+)/\u\L$1/g;
Now, what if you don't want to capitalize that "and"? Just use
L<Text::Autoformat> and get on with the next problem. :)
=head2 How can I split a [character]-delimited string except when inside [character]?
Several modules can handle this sort of parsing--L<Text::Balanced>,
L<Text::CSV>, L<Text::CSV_XS>, and L<Text::ParseWords>, among others.
Take the example case of trying to split a string that is
comma-separated into its different fields. You can't use C<split(/,/)>
because you shouldn't split if the comma is inside quotes. For
example, take a data line like this:
SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
Due to the restriction of the quotes, this is a fairly complex
problem. Thankfully, we have Jeffrey Friedl, author of
I<Mastering Regular Expressions>, to handle these for us. He
suggests (assuming your string is contained in C<$text>):
my @new = ();
push(@new, $+) while $text =~ m{
"([^\"\\]*(?:\\.[^\"\\]*)*)",? # groups the phrase inside the quotes
| ([^,]+),?
| ,
}gx;
push(@new, undef) if substr($text,-1,1) eq ',';
If you want to represent quotation marks inside a
quotation-mark-delimited field, escape them with backslashes (eg,
C<"like \"this\"">.
Alternatively, the L<Text::ParseWords> module (part of the standard
Perl distribution) lets you say:
use Text::ParseWords;
@new = quotewords(",", 0, $text);
For parsing or generating CSV, though, using L<Text::CSV> rather than
implementing it yourself is highly recommended; you'll save yourself odd bugs
popping up later by just using code which has already been tried and tested in
production for years.
=head2 How do I strip blank space from the beginning/end of a string?
(contributed by brian d foy)
A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. You
can do that with a pair of substitutions:
s/^\s+//;
s/\s+$//;
You can also write that as a single substitution, although it turns
out the combined statement is slower than the separate ones. That
might not matter to you, though:
s/^\s+|\s+$//g;
In this regular expression, the alternation matches either at the
beginning or the end of the string since the anchors have a lower
precedence than the alternation. With the C</g> flag, the substitution
makes all possible matches, so it gets both. Remember, the trailing
newline matches the C<\s+>, and the C<$> anchor can match to the
absolute end of the string, so the newline disappears too. Just add
the newline to the output, which has the added benefit of preserving
"blank" (consisting entirely of whitespace) lines which the C<^\s+>
would remove all by itself:
while( <> ) {
s/^\s+|\s+$//g;
print "$_\n";
}
For a multi-line string, you can apply the regular expression to each
logical line in the string by adding the C</m> flag (for
"multi-line"). With the C</m> flag, the C<$> matches I<before> an
embedded newline, so it doesn't remove it. This pattern still removes
the newline at the end of the string:
$string =~ s/^\s+|\s+$//gm;
Remember that lines consisting entirely of whitespace will disappear,
since the first part of the alternation can match the entire string
and replace it with nothing. If you need to keep embedded blank lines,
you have to do a little more work. Instead of matching any whitespace
(since that includes a newline), just match the other whitespace:
$string =~ s/^[\t\f ]+|[\t\f ]+$//mg;
=head2 How do I pad a string with blanks or pad a number with zeroes?
In the following examples, C<$pad_len> is the length to which you wish
to pad the string, C<$text> or C<$num> contains the string to be padded,
and C<$pad_char> contains the padding character. You can use a single
character string constant instead of the C<$pad_char> variable if you
know what it is in advance. And in the same way you can use an integer in
place of C<$pad_len> if you know the pad length in advance.
The simplest method uses the C<sprintf> function. It can pad on the left
or right with blanks and on the left with zeroes and it will not
truncate the result. The C<pack> function can only pad strings on the
right with blanks and it will truncate the result to a maximum length of
C<$pad_len>.
# Left padding a string with blanks (no truncation):
my $padded = sprintf("%${pad_len}s", $text);
my $padded = sprintf("%*s", $pad_len, $text); # same thing
# Right padding a string with blanks (no truncation):
my $padded = sprintf("%-${pad_len}s", $text);
my $padded = sprintf("%-*s", $pad_len, $text); # same thing
# Left padding a number with 0 (no truncation):
my $padded = sprintf("%0${pad_len}d", $num);
my $padded = sprintf("%0*d", $pad_len, $num); # same thing
# Right padding a string with blanks using pack (will truncate):
my $padded = pack("A$pad_len",$text);
If you need to pad with a character other than blank or zero you can use
one of the following methods. They all generate a pad string with the
C<x> operator and combine that with C<$text>. These methods do
not truncate C<$text>.
Left and right padding with any character, creating a new string:
my $padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
my $padded = $text . $pad_char x ( $pad_len - length( $text ) );
Left and right padding with any character, modifying C<$text> directly:
substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
$text .= $pad_char x ( $pad_len - length( $text ) );
=head2 How do I extract selected columns from a string?
(contributed by brian d foy)
If you know the columns that contain the data, you can
use C<substr> to extract a single column.
my $column = substr( $line, $start_column, $length );
You can use C<split> if the columns are separated by whitespace or
some other delimiter, as long as whitespace or the delimiter cannot
appear as part of the data.
my $line = ' fred barney betty ';
my @columns = split /\s+/, $line;
# ( '', 'fred', 'barney', 'betty' );
my $line = 'fred||barney||betty';
my @columns = split /\|/, $line;
# ( 'fred', '', 'barney', '', 'betty' );
If you want to work with comma-separated values, don't do this since
that format is a bit more complicated. Use one of the modules that
handle that format, such as L<Text::CSV>, L<Text::CSV_XS>, or
L<Text::CSV_PP>.
If you want to break apart an entire line of fixed columns, you can use
C<unpack> with the A (ASCII) format. By using a number after the format
specifier, you can denote the column width. See the C<pack> and C<unpack>
entries in L<perlfunc> for more details.
my @fields = unpack( $line, "A8 A8 A8 A16 A4" );
Note that spaces in the format argument to C<unpack> do not denote literal
spaces. If you have space separated data, you may want C<split> instead.
=head2 How do I find the soundex value of a string?
(contributed by brian d foy)
You can use the C<Text::Soundex> module. If you want to do fuzzy or close
matching, you might also try the L<String::Approx>, and
L<Text::Metaphone>, and L<Text::DoubleMetaphone> modules.
=head2 How can I expand variables in text strings?
(contributed by brian d foy)
If you can avoid it, don't, or if you can use a templating system,
such as L<Text::Template> or L<Template> Toolkit, do that instead. You
might even be able to get the job done with C<sprintf> or C<printf>:
my $string = sprintf 'Say hello to %s and %s', $foo, $bar;
However, for the one-off simple case where I don't want to pull out a
full templating system, I'll use a string that has two Perl scalar
variables in it. In this example, I want to expand C<$foo> and C<$bar>
to their variable's values:
my $foo = 'Fred';
my $bar = 'Barney';
$string = 'Say hello to $foo and $bar';
One way I can do this involves the substitution operator and a double
C</e> flag. The first C</e> evaluates C<$1> on the replacement side and
turns it into C<$foo>. The second /e starts with C<$foo> and replaces
it with its value. C<$foo>, then, turns into 'Fred', and that's finally
what's left in the string:
$string =~ s/(\$\w+)/$1/eeg; # 'Say hello to Fred and Barney'
The C</e> will also silently ignore violations of strict, replacing
undefined variable names with the empty string. Since I'm using the
C</e> flag (twice even!), I have all of the same security problems I
have with C<eval> in its string form. If there's something odd in
C<$foo>, perhaps something like C<@{[ system "rm -rf /" ]}>, then
I could get myself in trouble.
To get around the security problem, I could also pull the values from
a hash instead of evaluating variable names. Using a single C</e>, I
can check the hash to ensure the value exists, and if it doesn't, I
can replace the missing value with a marker, in this case C<???> to
signal that I missed something:
my $string = 'This has $foo and $bar';
my %Replacements = (
foo => 'Fred',
);
# $string =~ s/\$(\w+)/$Replacements{$1}/g;
$string =~ s/\$(\w+)/
exists $Replacements{$1} ? $Replacements{$1} : '???'
/eg;
print $string;
=head2 What's wrong with always quoting "$vars"?
The problem is that those double-quotes force
stringification--coercing numbers and references into strings--even
when you don't want them to be strings. Think of it this way:
double-quote expansion is used to produce new strings. If you already
have a string, why do you need more?
If you get used to writing odd things like these:
print "$var"; # BAD
my $new = "$old"; # BAD
somefunc("$var"); # BAD
You'll be in trouble. Those should (in 99.8% of the cases) be
the simpler and more direct:
print $var;
my $new = $old;
somefunc($var);
Otherwise, besides slowing you down, you're going to break code when
the thing in the scalar is actually neither a string nor a number, but
a reference:
func(\@array);
sub func {
my $aref = shift;
my $oref = "$aref"; # WRONG
}
You can also get into subtle problems on those few operations in Perl
that actually do care about the difference between a string and a
number, such as the magical C<++> autoincrement operator or the
syscall() function.
Stringification also destroys arrays.
my @lines = `command`;
print "@lines"; # WRONG - extra blanks
print @lines; # right
=head2 Why don't my E<lt>E<lt>HERE documents work?
Here documents are found in L<perlop>. Check for these three things:
=over 4
=item There must be no space after the E<lt>E<lt> part.
=item There (probably) should be a semicolon at the end of the opening token
=item You can't (easily) have any space in front of the tag.
=item There needs to be at least a line separator after the end token.
=back
If you want to indent the text in the here document, you
can do this:
# all in one
(my $VAR = <<HERE_TARGET) =~ s/^\s+//gm;
your text
goes here
HERE_TARGET
But the HERE_TARGET must still be flush against the margin.
If you want that indented also, you'll have to quote
in the indentation.
(my $quote = <<' FINIS') =~ s/^\s+//gm;
...we will have peace, when you and all your works have
perished--and the works of your dark master to whom you
would deliver us. You are a liar, Saruman, and a corrupter
of men's hearts. --Theoden in /usr/src/perl/taint.c
FINIS
$quote =~ s/\s+--/\n--/;
A nice general-purpose fixer-upper function for indented here documents
follows. It expects to be called with a here document as its argument.
It looks to see whether each line begins with a common substring, and
if so, strips that substring off. Otherwise, it takes the amount of leading
whitespace found on the first line and removes that much off each
subsequent line.
sub fix {
local $_ = shift;
my ($white, $leader); # common whitespace and common leading string
if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\g1\g2?.*\n)+$/) {
($white, $leader) = ($2, quotemeta($1));
} else {
($white, $leader) = (/^(\s+)/, '');
}
s/^\s*?$leader(?:$white)?//gm;
return $_;
}
This works with leading special strings, dynamically determined:
my $remember_the_main = fix<<' MAIN_INTERPRETER_LOOP';
@@@ int
@@@ runops() {
@@@ SAVEI32(runlevel);
@@@ runlevel++;
@@@ while ( op = (*op->op_ppaddr)() );
@@@ TAINT_NOT;
@@@ return 0;
@@@ }
MAIN_INTERPRETER_LOOP
Or with a fixed amount of leading whitespace, with remaining
indentation correctly preserved:
my $poem = fix<<EVER_ON_AND_ON;
Now far ahead the Road has gone,
And I must follow, if I can,
Pursuing it with eager feet,
Until it joins some larger way
Where many paths and errands meet.
And whither then? I cannot say.
--Bilbo in /usr/src/perl/pp_ctl.c
EVER_ON_AND_ON
=head1 Data: Arrays
=head2 What is the difference between a list and an array?
(contributed by brian d foy)
A list is a fixed collection of scalars. An array is a variable that
holds a variable collection of scalars. An array can supply its collection
for list operations, so list operations also work on arrays:
# slices
( 'dog', 'cat', 'bird' )[2,3];
@animals[2,3];
# iteration
foreach ( qw( dog cat bird ) ) { ... }
foreach ( @animals ) { ... }
my @three = grep { length == 3 } qw( dog cat bird );
my @three = grep { length == 3 } @animals;
# supply an argument list
wash_animals( qw( dog cat bird ) );
wash_animals( @animals );
Array operations, which change the scalars, rearrange them, or add
or subtract some scalars, only work on arrays. These can't work on a
list, which is fixed. Array operations include C<shift>, C<unshift>,
C<push>, C<pop>, and C<splice>.
An array can also change its length:
$#animals = 1; # truncate to two elements
$#animals = 10000; # pre-extend to 10,001 elements
You can change an array element, but you can't change a list element:
$animals[0] = 'Rottweiler';
qw( dog cat bird )[0] = 'Rottweiler'; # syntax error!
foreach ( @animals ) {
s/^d/fr/; # works fine
}
foreach ( qw( dog cat bird ) ) {
s/^d/fr/; # Error! Modification of read only value!
}
However, if the list element is itself a variable, it appears that you
can change a list element. However, the list element is the variable, not
the data. You're not changing the list element, but something the list
element refers to. The list element itself doesn't change: it's still
the same variable.
You also have to be careful about context. You can assign an array to
a scalar to get the number of elements in the array. This only works
for arrays, though:
my $count = @animals; # only works with arrays
If you try to do the same thing with what you think is a list, you
get a quite different result. Although it looks like you have a list
on the righthand side, Perl actually sees a bunch of scalars separated
by a comma:
my $scalar = ( 'dog', 'cat', 'bird' ); # $scalar gets bird
Since you're assigning to a scalar, the righthand side is in scalar
context. The comma operator (yes, it's an operator!) in scalar
context evaluates its lefthand side, throws away the result, and
evaluates it's righthand side and returns the result. In effect,
that list-lookalike assigns to C<$scalar> it's rightmost value. Many
people mess this up because they choose a list-lookalike whose
last element is also the count they expect:
my $scalar = ( 1, 2, 3 ); # $scalar gets 3, accidentally
=head2 What is the difference between $array[1] and @array[1]?
(contributed by brian d foy)
The difference is the sigil, that special character in front of the
array name. The C<$> sigil means "exactly one item", while the C<@>
sigil means "zero or more items". The C<$> gets you a single scalar,
while the C<@> gets you a list.
The confusion arises because people incorrectly assume that the sigil
denotes the variable type.
The C<$array[1]> is a single-element access to the array. It's going
to return the item in index 1 (or undef if there is no item there).
If you intend to get exactly one element from the array, this is the
form you should use.
The C<@array[1]> is an array slice, although it has only one index.
You can pull out multiple elements simultaneously by specifying
additional indices as a list, like C<@array[1,4,3,0]>.
Using a slice on the lefthand side of the assignment supplies list
context to the righthand side. This can lead to unexpected results.
For instance, if you want to read a single line from a filehandle,
assigning to a scalar value is fine:
$array[1] = <STDIN>;
However, in list context, the line input operator returns all of the
lines as a list. The first line goes into C<@array[1]> and the rest
of the lines mysteriously disappear:
@array[1] = <STDIN>; # most likely not what you want
Either the C<use warnings> pragma or the B<-w> flag will warn you when
you use an array slice with a single index.
=head2 How can I remove duplicate elements from a list or array?
(contributed by brian d foy)
Use a hash. When you think the words "unique" or "duplicated", think
"hash keys".
If you don't care about the order of the elements, you could just
create the hash then extract the keys. It's not important how you
create that hash: just that you use C<keys> to get the unique
elements.
my %hash = map { $_, 1 } @array;
# or a hash slice: @hash{ @array } = ();
# or a foreach: $hash{$_} = 1 foreach ( @array );
my @unique = keys %hash;
If you want to use a module, try the C<uniq> function from
L<List::MoreUtils>. In list context it returns the unique elements,
preserving their order in the list. In scalar context, it returns the
number of unique elements.
use List::MoreUtils qw(uniq);
my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7
my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7
You can also go through each element and skip the ones you've seen
before. Use a hash to keep track. The first time the loop sees an
element, that element has no key in C<%Seen>. The C<next> statement
creates the key and immediately uses its value, which is C<undef>, so
the loop continues to the C<push> and increments the value for that
key. The next time the loop sees that same element, its key exists in
the hash I<and> the value for that key is true (since it's not 0 or
C<undef>), so the next skips that iteration and the loop goes to the
next element.
my @unique = ();
my %seen = ();
foreach my $elem ( @array ) {
next if $seen{ $elem }++;
push @unique, $elem;
}
You can write this more briefly using a grep, which does the
same thing.
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @array;
=head2 How can I tell whether a certain element is contained in a list or array?
(portions of this answer contributed by Anno Siegel and brian d foy)
Hearing the word "in" is an I<in>dication that you probably should have
used a hash, not a list or array, to store your data. Hashes are
designed to answer this question quickly and efficiently. Arrays aren't.
That being said, there are several ways to approach this. In Perl 5.10
and later, you can use the smart match operator to check that an item is
contained in an array or a hash:
use 5.010;
if( $item ~~ @array ) {
say "The array contains $item"
}
if( $item ~~ %hash ) {
say "The hash contains $item"
}
With earlier versions of Perl, you have to do a bit more work. If you
are going to make this query many times over arbitrary string values,
the fastest way is probably to invert the original array and maintain a
hash whose keys are the first array's values:
my @blues = qw/azure cerulean teal turquoise lapis-lazuli/;
my %is_blue = ();
for (@blues) { $is_blue{$_} = 1 }
Now you can check whether C<$is_blue{$some_color}>. It might have
been a good idea to keep the blues all in a hash in the first place.
If the values are all small integers, you could use a simple indexed
array. This kind of an array will take up less space:
my @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
my @is_tiny_prime = ();
for (@primes) { $is_tiny_prime[$_] = 1 }
# or simply @istiny_prime[@primes] = (1) x @primes;
Now you check whether $is_tiny_prime[$some_number].
If the values in question are integers instead of strings, you can save
quite a lot of space by using bit strings instead:
my @articles = ( 1..10, 150..2000, 2017 );
undef $read;
for (@articles) { vec($read,$_,1) = 1 }
Now check whether C<vec($read,$n,1)> is true for some C<$n>.
These methods guarantee fast individual tests but require a re-organization
of the original list or array. They only pay off if you have to test
multiple values against the same array.
If you are testing only once, the standard module L<List::Util> exports
the function C<first> for this purpose. It works by stopping once it
finds the element. It's written in C for speed, and its Perl equivalent
looks like this subroutine:
sub first (&@) {
my $code = shift;
foreach (@_) {
return $_ if &{$code}();
}
undef;
}
If speed is of little concern, the common idiom uses grep in scalar context
(which returns the number of items that passed its condition) to traverse the
entire list. This does have the benefit of telling you how many matches it
found, though.
my $is_there = grep $_ eq $whatever, @array;
If you want to actually extract the matching elements, simply use grep in
list context.
my @matches = grep $_ eq $whatever, @array;
=head2 How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each
element is unique in a given array:
my (@union, @intersection, @difference);
my %count = ();
foreach my $element (@array1, @array2) { $count{$element}++ }
foreach my $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
Note that this is the I<symmetric difference>, that is, all elements
in either A or in B but not in both. Think of it as an xor operation.
=head2 How do I test whether two arrays or hashes are equal?
With Perl 5.10 and later, the smart match operator can give you the answer
with the least amount of work:
use 5.010;
if( @array1 ~~ @array2 ) {
say "The arrays are the same";
}
if( %hash1 ~~ %hash2 ) # doesn't check values! {
say "The hash keys are the same";
}
The following code works for single-level arrays. It uses a
stringwise comparison, and does not distinguish defined versus
undefined empty strings. Modify if you have other needs.
$are_equal = compare_arrays(\@frogs, \@toads);
sub compare_arrays {
my ($first, $second) = @_;
no warnings; # silence spurious -w undef complaints
return 0 unless @$first == @$second;
for (my $i = 0; $i < @$first; $i++) {
return 0 if $first->[$i] ne $second->[$i];
}
return 1;
}
For multilevel structures, you may wish to use an approach more
like this one. It uses the CPAN module L<FreezeThaw>:
use FreezeThaw qw(cmpStr);
my @a = my @b = ( "this", "that", [ "more", "stuff" ] );
printf "a and b contain %s arrays\n",
cmpStr(\@a, \@b) == 0
? "the same"
: "different";
This approach also works for comparing hashes. Here we'll demonstrate
two different answers:
use FreezeThaw qw(cmpStr cmpStrHard);
my %a = my %b = ( "this" => "that", "extra" => [ "more", "stuff" ] );
$a{EXTRA} = \%b;
$b{EXTRA} = \%a;
printf "a and b contain %s hashes\n",
cmpStr(\%a, \%b) == 0 ? "the same" : "different";
printf "a and b contain %s hashes\n",
cmpStrHard(\%a, \%b) == 0 ? "the same" : "different";
The first reports that both those the hashes contain the same data,
while the second reports that they do not. Which you prefer is left as
an exercise to the reader.
=head2 How do I find the first array element for which a condition is true?
To find the first array element which satisfies a condition, you can
use the C<first()> function in the L<List::Util> module, which comes
with Perl 5.8. This example finds the first element that contains
"Perl".
use List::Util qw(first);
my $element = first { /Perl/ } @array;
If you cannot use L<List::Util>, you can make your own loop to do the
same thing. Once you find the element, you stop the loop with last.
my $found;
foreach ( @array ) {
if( /Perl/ ) { $found = $_; last }
}
If you want the array index, use the C<firstidx()> function from
C<List::MoreUtils>:
use List::MoreUtils qw(firstidx);
my $index = firstidx { /Perl/ } @array;
Or write it yourself, iterating through the indices
and checking the array element at each index until you find one
that satisfies the condition:
my( $found, $index ) = ( undef, -1 );
for( $i = 0; $i < @array; $i++ ) {
if( $array[$i] =~ /Perl/ ) {
$found = $array[$i];
$index = $i;
last;
}
}
=head2 How do I handle linked lists?
(contributed by brian d foy)
Perl's arrays do not have a fixed size, so you don't need linked lists
if you just want to add or remove items. You can use array operations
such as C<push>, C<pop>, C<shift>, C<unshift>, or C<splice> to do
that.
Sometimes, however, linked lists can be useful in situations where you
want to "shard" an array so you have have many small arrays instead of
a single big array. You can keep arrays longer than Perl's largest
array index, lock smaller arrays separately in threaded programs,
reallocate less memory, or quickly insert elements in the middle of
the chain.
Steve Lembark goes through the details in his YAPC::NA 2009 talk "Perly
Linked Lists" ( L<http://www.slideshare.net/lembark/perly-linked-lists> ),
although you can just use his L<LinkedList::Single> module.
=head2 How do I handle circular lists?
X<circular> X<array> X<Tie::Cycle> X<Array::Iterator::Circular>
X<cycle> X<modulus>
(contributed by brian d foy)
If you want to cycle through an array endlessly, you can increment the
index modulo the number of elements in the array:
my @array = qw( a b c );
my $i = 0;
while( 1 ) {
print $array[ $i++ % @array ], "\n";
last if $i > 20;
}
You can also use L<Tie::Cycle> to use a scalar that always has the
next element of the circular array:
use Tie::Cycle;
tie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];
print $cycle; # FFFFFF
print $cycle; # 000000
print $cycle; # FFFF00
The L<Array::Iterator::Circular> creates an iterator object for
circular arrays:
use Array::Iterator::Circular;
my $color_iterator = Array::Iterator::Circular->new(
qw(red green blue orange)
);
foreach ( 1 .. 20 ) {
print $color_iterator->next, "\n";
}
=head2 How do I shuffle an array randomly?
If you either have Perl 5.8.0 or later installed, or if you have
Scalar-List-Utils 1.03 or later installed, you can say:
use List::Util 'shuffle';
@shuffled = shuffle(@list);
If not, you can use a Fisher-Yates shuffle.
sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to an array
return unless @$deck; # must not be empty!
my $i = @$deck;
while (--$i) {
my $j = int rand ($i+1);
@$deck[$i,$j] = @$deck[$j,$i];
}
}
# shuffle my mpeg collection
#
my @mpeg = <audio/*/*.mp3>;
fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
print @mpeg;
Note that the above implementation shuffles an array in place,
unlike the C<List::Util::shuffle()> which takes a list and returns
a new shuffled list.
You've probably seen shuffling algorithms that work using splice,
randomly picking another element to swap the current element with
srand;
@new = ();
@old = 1 .. 10; # just a demo
while (@old) {
push(@new, splice(@old, rand @old, 1));
}
This is bad because splice is already O(N), and since you do it N
times, you just invented a quadratic algorithm; that is, O(N**2).
This does not scale, although Perl is so efficient that you probably
won't notice this until you have rather largish arrays.
=head2 How do I process/modify each element of an array?
Use C<for>/C<foreach>:
for (@lines) {
s/foo/bar/; # change that word
tr/XZ/ZX/; # swap those letters
}
Here's another; let's compute spherical volumes:
my @volumes = @radii;
for (@volumes) { # @volumes has changed parts
$_ **= 3;
$_ *= (4/3) * 3.14159; # this will be constant folded
}
which can also be done with C<map()> which is made to transform
one list into another:
my @volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;
If you want to do the same thing to modify the values of the
hash, you can use the C<values> function. As of Perl 5.6
the values are not copied, so if you modify $orbit (in this
case), you modify the value.
for my $orbit ( values %orbits ) {
($orbit **= 3) *= (4/3) * 3.14159;
}
Prior to perl 5.6 C<values> returned copies of the values,
so older perl code often contains constructions such as
C<@orbits{keys %orbits}> instead of C<values %orbits> where
the hash is to be modified.
=head2 How do I select a random element from an array?
Use the C<rand()> function (see L<perlfunc/rand>):
my $index = rand @array;
my $element = $array[$index];
Or, simply:
my $element = $array[ rand @array ];
=head2 How do I permute N elements of a list?
X<List::Permutor> X<permute> X<Algorithm::Loops> X<Knuth>
X<The Art of Computer Programming> X<Fischer-Krause>
Use the L<List::Permutor> module on CPAN. If the list is actually an
array, try the L<Algorithm::Permute> module (also on CPAN). It's
written in XS code and is very efficient:
use Algorithm::Permute;
my @array = 'a'..'d';
my $p_iterator = Algorithm::Permute->new ( \@array );
while (my @perm = $p_iterator->next) {
print "next permutation: (@perm)\n";
}
For even faster execution, you could do:
use Algorithm::Permute;
my @array = 'a'..'d';
Algorithm::Permute::permute {
print "next permutation: (@array)\n";
} @array;
Here's a little program that generates all permutations of all the
words on each line of input. The algorithm embodied in the
C<permute()> function is discussed in Volume 4 (still unpublished) of
Knuth's I<The Art of Computer Programming> and will work on any list:
#!/usr/bin/perl -n
# Fischer-Krause ordered permutation generator
sub permute (&@) {
my $code = shift;
my @idx = 0..$#_;
while ( $code->(@_[@idx]) ) {
my $p = $#idx;
--$p while $idx[$p-1] > $idx[$p];
my $q = $p or return;
push @idx, reverse splice @idx, $p;
++$q while $idx[$p-1] > $idx[$q];
@idx[$p-1,$q]=@idx[$q,$p-1];
}
}
permute { print "@_\n" } split;
The L<Algorithm::Loops> module also provides the C<NextPermute> and
C<NextPermuteNum> functions which efficiently find all unique permutations
of an array, even if it contains duplicate values, modifying it in-place:
if its elements are in reverse-sorted order then the array is reversed,
making it sorted, and it returns false; otherwise the next
permutation is returned.
C<NextPermute> uses string order and C<NextPermuteNum> numeric order, so
you can enumerate all the permutations of C<0..9> like this:
use Algorithm::Loops qw(NextPermuteNum);
my @list= 0..9;
do { print "@list\n" } while NextPermuteNum @list;
=head2 How do I sort an array by (anything)?
Supply a comparison function to sort() (described in L<perlfunc/sort>):
@list = sort { $a <=> $b } @list;
The default sort function is cmp, string comparison, which would
sort C<(1, 2, 10)> into C<(1, 10, 2)>. C<< <=> >>, used above, is
the numerical comparison operator.
If you have a complicated function needed to pull out the part you
want to sort on, then don't do it inside the sort function. Pull it
out first, because the sort BLOCK can be called many times for the
same element. Here's an example of how to pull out the first word
after the first number on each item, and then sort those words
case-insensitively.
my @idx;
for (@data) {
my $item;
($item) = /\d+\s*(\S+)/;
push @idx, uc($item);
}
my @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
which could also be written this way, using a trick
that's come to be known as the Schwartzian Transform:
my @sorted = map { $_->[0] }
sort { $a->[1] cmp $b->[1] }
map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;
If you need to sort on several fields, the following paradigm is useful.
my @sorted = sort {
field1($a) <=> field1($b) ||
field2($a) cmp field2($b) ||
field3($a) cmp field3($b)
} @data;
This can be conveniently combined with precalculation of keys as given
above.
See the F<sort> article in the "Far More Than You Ever Wanted
To Know" collection in L<http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz> for
more about this approach.
See also the question later in L<perlfaq4> on sorting hashes.
=head2 How do I manipulate arrays of bits?
Use C<pack()> and C<unpack()>, or else C<vec()> and the bitwise
operations.
For example, you don't have to store individual bits in an array
(which would mean that you're wasting a lot of space). To convert an
array of bits to a string, use C<vec()> to set the right bits. This
sets C<$vec> to have bit N set only if C<$ints[N]> was set:
my @ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... )
my $vec = '';
foreach( 0 .. $#ints ) {
vec($vec,$_,1) = 1 if $ints[$_];
}
The string C<$vec> only takes up as many bits as it needs. For
instance, if you had 16 entries in C<@ints>, C<$vec> only needs two
bytes to store them (not counting the scalar variable overhead).
Here's how, given a vector in C<$vec>, you can get those bits into
your C<@ints> array:
sub bitvec_to_list {
my $vec = shift;
my @ints;
# Find null-byte density then select best algorithm
if ($vec =~ tr/\0// / length $vec > 0.95) {
use integer;
my $i;
# This method is faster with mostly null-bytes
while($vec =~ /[^\0]/g ) {
$i = -9 + 8 * pos $vec;
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
push @ints, $i if vec($vec, ++$i, 1);
}
}
else {
# This method is a fast general algorithm
use integer;
my $bits = unpack "b*", $vec;
push @ints, 0 if $bits =~ s/^(\d)// && $1;
push @ints, pos $bits while($bits =~ /1/g);
}
return \@ints;
}
This method gets faster the more sparse the bit vector is.
(Courtesy of Tim Bunce and Winfried Koenig.)
You can make the while loop a lot shorter with this suggestion
from Benjamin Goldberg:
while($vec =~ /[^\0]+/g ) {
push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
}
Or use the CPAN module L<Bit::Vector>:
my $vector = Bit::Vector->new($num_of_bits);
$vector->Index_List_Store(@ints);
my @ints = $vector->Index_List_Read();
L<Bit::Vector> provides efficient methods for bit vector, sets of
small integers and "big int" math.
Here's a more extensive illustration using vec():
# vec demo
my $vector = "\xff\x0f\xef\xfe";
print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ",
unpack("N", $vector), "\n";
my $is_set = vec($vector, 23, 1);
print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n";
pvec($vector);
set_vec(1,1,1);
set_vec(3,1,1);
set_vec(23,1,1);
set_vec(3,1,3);
set_vec(3,2,3);
set_vec(3,4,3);
set_vec(3,4,7);
set_vec(3,8,3);
set_vec(3,8,7);
set_vec(0,32,17);
set_vec(1,32,17);
sub set_vec {
my ($offset, $width, $value) = @_;
my $vector = '';
vec($vector, $offset, $width) = $value;
print "offset=$offset width=$width value=$value\n";
pvec($vector);
}
sub pvec {
my $vector = shift;
my $bits = unpack("b*", $vector);
my $i = 0;
my $BASE = 8;
print "vector length in bytes: ", length($vector), "\n";
@bytes = unpack("A8" x length($vector), $bits);
print "bits are: @bytes\n\n";
}
=head2 Why does defined() return true on empty arrays and hashes?
The short story is that you should probably only use defined on scalars or
functions, not on aggregates (arrays and hashes). See L<perlfunc/defined>
in the 5.004 release or later of Perl for more detail.
=head1 Data: Hashes (Associative Arrays)
=head2 How do I process an entire hash?
(contributed by brian d foy)
There are a couple of ways that you can process an entire hash. You
can get a list of keys, then go through each key, or grab a one
key-value pair at a time.
To go through all of the keys, use the C<keys> function. This extracts
all of the keys of the hash and gives them back to you as a list. You
can then get the value through the particular key you're processing:
foreach my $key ( keys %hash ) {
my $value = $hash{$key}
...
}
Once you have the list of keys, you can process that list before you
process the hash elements. For instance, you can sort the keys so you
can process them in lexical order:
foreach my $key ( sort keys %hash ) {
my $value = $hash{$key}
...
}
Or, you might want to only process some of the items. If you only want
to deal with the keys that start with C<text:>, you can select just
those using C<grep>:
foreach my $key ( grep /^text:/, keys %hash ) {
my $value = $hash{$key}
...
}
If the hash is very large, you might not want to create a long list of
keys. To save some memory, you can grab one key-value pair at a time using
C<each()>, which returns a pair you haven't seen yet:
while( my( $key, $value ) = each( %hash ) ) {
...
}
The C<each> operator returns the pairs in apparently random order, so if
ordering matters to you, you'll have to stick with the C<keys> method.
The C<each()> operator can be a bit tricky though. You can't add or
delete keys of the hash while you're using it without possibly
skipping or re-processing some pairs after Perl internally rehashes
all of the elements. Additionally, a hash has only one iterator, so if
you mix C<keys>, C<values>, or C<each> on the same hash, you risk resetting
the iterator and messing up your processing. See the C<each> entry in
L<perlfunc> for more details.
=head2 How do I merge two hashes?
X<hash> X<merge> X<slice, hash>
(contributed by brian d foy)
Before you decide to merge two hashes, you have to decide what to do
if both hashes contain keys that are the same and if you want to leave
the original hashes as they were.
If you want to preserve the original hashes, copy one hash (C<%hash1>)
to a new hash (C<%new_hash>), then add the keys from the other hash
(C<%hash2> to the new hash. Checking that the key already exists in
C<%new_hash> gives you a chance to decide what to do with the
duplicates:
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 ) {
if( exists $new_hash{$key2} ) {
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else {
$new_hash{$key2} = $hash2{$key2};
}
}
If you don't want to create a new hash, you can still use this looping
technique; just change the C<%new_hash> to C<%hash1>.
foreach my $key2 ( keys %hash2 ) {
if( exists $hash1{$key2} ) {
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else {
$hash1{$key2} = $hash2{$key2};
}
}
If you don't care that one hash overwrites keys and values from the other, you
could just use a hash slice to add one hash to another. In this case, values
from C<%hash2> replace values from C<%hash1> when they have keys in common:
@hash1{ keys %hash2 } = values %hash2;
=head2 What happens if I add or remove keys from a hash while iterating over it?
(contributed by brian d foy)
The easy answer is "Don't do that!"
If you iterate through the hash with each(), you can delete the key
most recently returned without worrying about it. If you delete or add
other keys, the iterator may skip or double up on them since perl
may rearrange the hash table. See the
entry for C<each()> in L<perlfunc>.
=head2 How do I look up a hash element by value?
Create a reverse hash:
my %by_value = reverse %by_key;
my $key = $by_value{$value};
That's not particularly efficient. It would be more space-efficient
to use:
while (my ($key, $value) = each %by_key) {
$by_value{$value} = $key;
}
If your hash could have repeated values, the methods above will only find
one of the associated keys. This may or may not worry you. If it does
worry you, you can always reverse the hash into a hash of arrays instead:
while (my ($key, $value) = each %by_key) {
push @{$key_list_by_value{$value}}, $key;
}
=head2 How can I know how many entries are in a hash?
(contributed by brian d foy)
This is very similar to "How do I process an entire hash?", also in
L<perlfaq4>, but a bit simpler in the common cases.
You can use the C<keys()> built-in function in scalar context to find out
have many entries you have in a hash:
my $key_count = keys %hash; # must be scalar context!
If you want to find out how many entries have a defined value, that's
a bit different. You have to check each value. A C<grep> is handy:
my $defined_value_count = grep { defined } values %hash;
You can use that same structure to count the entries any way that
you like. If you want the count of the keys with vowels in them,
you just test for that instead:
my $vowel_count = grep { /[aeiou]/ } keys %hash;
The C<grep> in scalar context returns the count. If you want the list
of matching items, just use it in list context instead:
my @defined_values = grep { defined } values %hash;
The C<keys()> function also resets the iterator, which means that you may
see strange results if you use this between uses of other hash operators
such as C<each()>.
=head2 How do I sort a hash (optionally by value instead of key)?
(contributed by brian d foy)
To sort a hash, start with the keys. In this example, we give the list of
keys to the sort function which then compares them ASCIIbetically (which
might be affected by your locale settings). The output list has the keys
in ASCIIbetical order. Once we have the keys, we can go through them to
create a report which lists the keys in ASCIIbetical order.
my @keys = sort { $a cmp $b } keys %hash;
foreach my $key ( @keys ) {
printf "%-20s %6d\n", $key, $hash{$key};
}
We could get more fancy in the C<sort()> block though. Instead of
comparing the keys, we can compute a value with them and use that
value as the comparison.
For instance, to make our report order case-insensitive, we use
C<lc> to lowercase the keys before comparing them:
my @keys = sort { lc $a cmp lc $b } keys %hash;
Note: if the computation is expensive or the hash has many elements,
you may want to look at the Schwartzian Transform to cache the
computation results.
If we want to sort by the hash value instead, we use the hash key
to look it up. We still get out a list of keys, but this time they
are ordered by their value.
my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
From there we can get more complex. If the hash values are the same,
we can provide a secondary sort on the hash key.
my @keys = sort {
$hash{$a} <=> $hash{$b}
or
"\L$a" cmp "\L$b"
} keys %hash;
=head2 How can I always keep my hash sorted?
X<hash tie sort DB_File Tie::IxHash>
You can look into using the C<DB_File> module and C<tie()> using the
C<$DB_BTREE> hash bindings as documented in L<DB_File/"In Memory
Databases">. The L<Tie::IxHash> module from CPAN might also be
instructive. Although this does keep your hash sorted, you might not
like the slowdown you suffer from the tie interface. Are you sure you
need to do this? :)
=head2 What's the difference between "delete" and "undef" with hashes?
Hashes contain pairs of scalars: the first is the key, the
second is the value. The key will be coerced to a string,
although the value can be any kind of scalar: string,
number, or reference. If a key C<$key> is present in
%hash, C<exists($hash{$key})> will return true. The value
for a given key can be C<undef>, in which case
C<$hash{$key}> will be C<undef> while C<exists $hash{$key}>
will return true. This corresponds to (C<$key>, C<undef>)
being in the hash.
Pictures help... Here's the C<%hash> table:
keys values
+------+------+
| a | 3 |
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
And these conditions hold
$hash{'a'} is true
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is true
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true
If you now say
undef $hash{'a'}
your table now reads:
keys values
+------+------+
| a | undef|
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
and these conditions now hold; changes in caps:
$hash{'a'} is FALSE
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is FALSE
exists $hash{'a'} is true (Perl 5 only)
grep ($_ eq 'a', keys %hash) is true
Notice the last two: you have an undef value, but a defined key!
Now, consider this:
delete $hash{'a'}
your table now reads:
keys values
+------+------+
| x | 7 |
| d | 0 |
| e | 2 |
+------+------+
and these conditions now hold; changes in caps:
$hash{'a'} is false
$hash{'d'} is false
defined $hash{'d'} is true
defined $hash{'a'} is false
exists $hash{'a'} is FALSE (Perl 5 only)
grep ($_ eq 'a', keys %hash) is FALSE
See, the whole entry is gone!
=head2 Why don't my tied hashes make the defined/exists distinction?
This depends on the tied hash's implementation of EXISTS().
For example, there isn't the concept of undef with hashes
that are tied to DBM* files. It also means that exists() and
defined() do the same thing with a DBM* file, and what they
end up doing is not what they do with ordinary hashes.
=head2 How do I reset an each() operation part-way through?
(contributed by brian d foy)
You can use the C<keys> or C<values> functions to reset C<each>. To
simply reset the iterator used by C<each> without doing anything else,
use one of them in void context:
keys %hash; # resets iterator, nothing else.
values %hash; # resets iterator, nothing else.
See the documentation for C<each> in L<perlfunc>.
=head2 How can I get the unique keys from two hashes?
First you extract the keys from the hashes into lists, then solve
the "removing duplicates" problem described above. For example:
my %seen = ();
for my $element (keys(%foo), keys(%bar)) {
$seen{$element}++;
}
my @uniq = keys %seen;
Or more succinctly:
my @uniq = keys %{{%foo,%bar}};
Or if you really want to save space:
my %seen = ();
while (defined ($key = each %foo)) {
$seen{$key}++;
}
while (defined ($key = each %bar)) {
$seen{$key}++;
}
my @uniq = keys %seen;
=head2 How can I store a multidimensional array in a DBM file?
Either stringify the structure yourself (no fun), or else
get the MLDBM (which uses Data::Dumper) module from CPAN and layer
it on top of either DB_File or GDBM_File. You might also try DBM::Deep, but
it can be a bit slow.
=head2 How can I make my hash remember the order I put elements into it?
Use the L<Tie::IxHash> from CPAN.
use Tie::IxHash;
tie my %myhash, 'Tie::IxHash';
for (my $i=0; $i<20; $i++) {
$myhash{$i} = 2*$i;
}
my @keys = keys %myhash;
# @keys = (0,1,2,3,...)
=head2 Why does passing a subroutine an undefined element in a hash create it?
(contributed by brian d foy)
Are you using a really old version of Perl?
Normally, accessing a hash key's value for a nonexistent key will
I<not> create the key.
my %hash = ();
my $value = $hash{ 'foo' };
print "This won't print\n" if exists $hash{ 'foo' };
Passing C<$hash{ 'foo' }> to a subroutine used to be a special case, though.
Since you could assign directly to C<$_[0]>, Perl had to be ready to
make that assignment so it created the hash key ahead of time:
my_sub( $hash{ 'foo' } );
print "This will print before 5.004\n" if exists $hash{ 'foo' };
sub my_sub {
# $_[0] = 'bar'; # create hash key in case you do this
1;
}
Since Perl 5.004, however, this situation is a special case and Perl
creates the hash key only when you make the assignment:
my_sub( $hash{ 'foo' } );
print "This will print, even after 5.004\n" if exists $hash{ 'foo' };
sub my_sub {
$_[0] = 'bar';
}
However, if you want the old behavior (and think carefully about that
because it's a weird side effect), you can pass a hash slice instead.
Perl 5.004 didn't make this a special case:
my_sub( @hash{ qw/foo/ } );
=head2 How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?
Usually a hash ref, perhaps like this:
$record = {
NAME => "Jason",
EMPNO => 132,
TITLE => "deputy peon",
AGE => 23,
SALARY => 37_000,
PALS => [ "Norbert", "Rhys", "Phineas"],
};
References are documented in L<perlref> and L<perlreftut>.
Examples of complex data structures are given in L<perldsc> and
L<perllol>. Examples of structures and object-oriented classes are
in L<perltoot>.
=head2 How can I use a reference as a hash key?
(contributed by brian d foy and Ben Morrow)
Hash keys are strings, so you can't really use a reference as the key.
When you try to do that, perl turns the reference into its stringified
form (for instance, C<HASH(0xDEADBEEF)>). From there you can't get
back the reference from the stringified form, at least without doing
some extra work on your own.
Remember that the entry in the hash will still be there even if
the referenced variable goes out of scope, and that it is entirely
possible for Perl to subsequently allocate a different variable at
the same address. This will mean a new variable might accidentally
be associated with the value for an old.
If you have Perl 5.10 or later, and you just want to store a value
against the reference for lookup later, you can use the core
Hash::Util::Fieldhash module. This will also handle renaming the
keys if you use multiple threads (which causes all variables to be
reallocated at new addresses, changing their stringification), and
garbage-collecting the entries when the referenced variable goes out
of scope.
If you actually need to be able to get a real reference back from
each hash entry, you can use the Tie::RefHash module, which does the
required work for you.
=head2 How can I check if a key exists in a multilevel hash?
(contributed by brian d foy)
The trick to this problem is avoiding accidental autovivification. If
you want to check three keys deep, you might naE<0xEF>vely try this:
my %hash;
if( exists $hash{key1}{key2}{key3} ) {
...;
}
Even though you started with a completely empty hash, after that call to
C<exists> you've created the structure you needed to check for C<key3>:
%hash = (
'key1' => {
'key2' => {}
}
);
That's autovivification. You can get around this in a few ways. The
easiest way is to just turn it off. The lexical C<autovivification>
pragma is available on CPAN. Now you don't add to the hash:
{
no autovivification;
my %hash;
if( exists $hash{key1}{key2}{key3} ) {
...;
}
}
The L<Data::Diver> module on CPAN can do it for you too. Its C<Dive>
subroutine can tell you not only if the keys exist but also get the
value:
use Data::Diver qw(Dive);
my @exists = Dive( \%hash, qw(key1 key2 key3) );
if( ! @exists ) {
...; # keys do not exist
}
elsif( ! defined $exists[0] ) {
...; # keys exist but value is undef
}
You can easily do this yourself too by checking each level of the hash
before you move onto the next level. This is essentially what
L<Data::Diver> does for you:
if( check_hash( \%hash, qw(key1 key2 key3) ) ) {
...;
}
sub check_hash {
my( $hash, @keys ) = @_;
return unless @keys;
foreach my $key ( @keys ) {
return unless eval { exists $hash->{$key} };
$hash = $hash->{$key};
}
return 1;
}
=head2 How can I prevent addition of unwanted keys into a hash?
Since version 5.8.0, hashes can be I<restricted> to a fixed number
of given keys. Methods for creating and dealing with restricted hashes
are exported by the L<Hash::Util> module.
=head1 Data: Misc
=head2 How do I handle binary data correctly?
Perl is binary-clean, so it can handle binary data just fine.
On Windows or DOS, however, you have to use C<binmode> for binary
files to avoid conversions for line endings. In general, you should
use C<binmode> any time you want to work with binary data.
Also see L<perlfunc/"binmode"> or L<perlopentut>.
If you're concerned about 8-bit textual data then see L<perllocale>.
If you want to deal with multibyte characters, however, there are
some gotchas. See the section on Regular Expressions.
=head2 How do I determine whether a scalar is a number/whole/integer/float?
Assuming that you don't care about IEEE notations like "NaN" or
"Infinity", you probably just want to use a regular expression:
use 5.010;
given( $number ) {
when( /\D/ )
{ say "\thas nondigits"; continue }
when( /^\d+\z/ )
{ say "\tis a whole number"; continue }
when( /^-?\d+\z/ )
{ say "\tis an integer"; continue }
when( /^[+-]?\d+\z/ )
{ say "\tis a +/- integer"; continue }
when( /^-?(?:\d+\.?|\.\d)\d*\z/ )
{ say "\tis a real number"; continue }
when( /^[+-]?(?=\.?\d)\d*\.?\d*(?:e[+-]?\d+)?\z/i)
{ say "\tis a C float" }
}
There are also some commonly used modules for the task.
L<Scalar::Util> (distributed with 5.8) provides access to perl's
internal function C<looks_like_number> for determining whether a
variable looks like a number. L<Data::Types> exports functions that
validate data types using both the above and other regular
expressions. Thirdly, there is L<Regexp::Common> which has regular
expressions to match various types of numbers. Those three modules are
available from the CPAN.
If you're on a POSIX system, Perl supports the C<POSIX::strtod>
function for converting strings to doubles (and also C<POSIX::strtol>
for longs). Its semantics are somewhat cumbersome, so here's a
C<getnum> wrapper function for more convenient access. This function
takes a string and returns the number it found, or C<undef> for input
that isn't a C float. The C<is_numeric> function is a front end to
C<getnum> if you just want to say, "Is this a float?"
sub getnum {
use POSIX qw(strtod);
my $str = shift;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
$! = 0;
my($num, $unparsed) = strtod($str);
if (($str eq '') || ($unparsed != 0) || $!) {
return undef;
}
else {
return $num;
}
}
sub is_numeric { defined getnum($_[0]) }
Or you could check out the L<String::Scanf> module on the CPAN
instead.
=head2 How do I keep persistent data across program calls?
For some specific applications, you can use one of the DBM modules.
See L<AnyDBM_File>. More generically, you should consult the L<FreezeThaw>
or L<Storable> modules from CPAN. Starting from Perl 5.8, L<Storable> is part
of the standard distribution. Here's one example using L<Storable>'s C<store>
and C<retrieve> functions:
use Storable;
store(\%hash, "filename");
# later on...
$href = retrieve("filename"); # by ref
%hash = %{ retrieve("filename") }; # direct to hash
=head2 How do I print out or copy a recursive data structure?
The L<Data::Dumper> module on CPAN (or the 5.005 release of Perl) is great
for printing out data structures. The L<Storable> module on CPAN (or the
5.8 release of Perl), provides a function called C<dclone> that recursively
copies its argument.
use Storable qw(dclone);
$r2 = dclone($r1);
Where C<$r1> can be a reference to any kind of data structure you'd like.
It will be deeply copied. Because C<dclone> takes and returns references,
you'd have to add extra punctuation if you had a hash of arrays that
you wanted to copy.
%newhash = %{ dclone(\%oldhash) };
=head2 How do I define methods for every class/object?
(contributed by Ben Morrow)
You can use the C<UNIVERSAL> class (see L<UNIVERSAL>). However, please
be very careful to consider the consequences of doing this: adding
methods to every object is very likely to have unintended
consequences. If possible, it would be better to have all your object
inherit from some common base class, or to use an object system like
Moose that supports roles.
=head2 How do I verify a credit card checksum?
Get the L<Business::CreditCard> module from CPAN.
=head2 How do I pack arrays of doubles or floats for XS code?
The arrays.h/arrays.c code in the L<PGPLOT> module on CPAN does just this.
If you're doing a lot of float or double processing, consider using
the L<PDL> module from CPAN instead--it makes number-crunching easy.
See L<http://search.cpan.org/dist/PGPLOT> for the code.
=head1 AUTHOR AND COPYRIGHT
Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
other authors as noted. All rights reserved.
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain. You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit. A simple comment in the code giving
credit would be courteous but is not required.
| Dokaponteam/ITF_Project | xampp/perl/lib/perlfaq4.pod | Perl | mit | 89,487 |
#use strict;
# usage perl harness.pl [testNum]
# where testNum is an integer from 1 to 41
# testNum may also be a list of integers denoting tests to be run
# ommitting testNum will lead to all tests being run
#
# this harness outputs the results to the file results.html as well
# as reporting them to stderr.
#
# note that the XInclude sample application must be discoverable on
# the current PATH.
#
# Find out the platform from 'uname -s'
#
open(PLATFORM, "uname -s|");
$platform = <PLATFORM>;
chomp($platform);
close (PLATFORM);
if ($platform =~ m/Windows/i || $platform =~ m/CYGWIN/i) {
$pathsep = "\\";
}
else {
$pathsep = "/";
}
@CORRECT_TEST_RESULTS = (
-3,
1, 1, 1, 1, 1, 1, 0, 1, 0, 1,
0, 0, 0, 0, 1, 1, 1, 0, 1, 1,
1, 0, 1, 0, 0, 0, 1, 1, 0, 1,
1, 0, 1, 1, 1, 1, 1, 1, 0, 0,
1
);
# private static boolean[] TEST_RESULTS = new boolean[] {
# // one value for each test
# true, true, true, true, true, true, false, true, false, true, // 10
# false, false, false, false, true, true, true, false, true, true, // 20
# true, false, true, false, false, false, true, true, false, true, // 30
# true, false, true, true, true, true, true, true, false, false, // 40
# true, };
#no need to add one to this value since there is a dummy value in the tables
$NUM_TESTS = $#CORRECT_TEST_RESULTS;
@ACTUAL_TEST_RESULTS = (
-3,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1
);
print "Running XInclude Tests\n";
$dateAndTime = localtime();
open(outfile, ">results.html");
print outfile "<html><head><title>XInclude results generated at $dateAndTime </title>";
print outfile "</head><body bgcolor=\"black\" text=\"white\"><center>";
print outfile "<table border cellspacing=\"0\" cellpadding=\"5\"><caption align=\"bottom\">Results of XI Test Run</caption>";
print outfile "<tr><th>Test Number</th><th>Test Input File</th><th>Generated Output File</th>";
print outfile "<th>Reference Result File</th><th>Result</th><th>Expected Result</th><th>Test Status</th></tr>";
$successes = 0;
$correct = 0;
$numTestsToRun = $#ARGV + 1;
while (<@ARGV>){
$i = $_;
if ($i < 10) {
$testNum = "0$i";
} else {
$testNum = "$i";
}
$input_file = "tests".$pathsep."xinclude".$pathsep."tests".$pathsep."test$testNum.xml";
if ($CORRECT_TEST_RESULTS[$i] == 1) {
$output_file = "tests".$pathsep."xinclude".$pathsep."written".$pathsep."test$testNum.xml";
$expected_result_file = "tests".$pathsep."xinclude".$pathsep."cppoutput".$pathsep."test$testNum.xml";
} else {
$output_file = "tests".$pathsep."xinclude".$pathsep."written".$pathsep."test$testNum.txt";
$expected_result_file = "tests".$pathsep."xinclude".$pathsep."cppoutput".$pathsep."test$testNum.txt";
}
# run the tests and apture the output
$command = "XInclude $input_file $output_file";
print "R[$command]\n";
system("$command");
$outcome = 0;
if (! -e $output_file) {
$ACTUAL_TEST_RESULTS[$i] = 0;
# we didn't generate an output, we are correct if the test was expected to fail
if($CORRECT_TEST_RESULTS[$i] eq 0) {
$outcome = 1;
}
} else {
$ACTUAL_TEST_RESULTS[$i] = 1;
# we generated an output, we are correct if our result matches
if($CORRECT_TEST_RESULTS[$i] eq 1) {
$outcome = &compareFiles($expected_result_file, $output_file);
}
}
print outfile "<tr bgcolor=";
if ($outcome eq 1) {
print outfile "green";
} else {
print outfile "red";
}
print outfile ">";
#test number
print outfile "<td>$testNum</td>";
print outfile "<td>";
$anchor = &createHTMLAnchor("$input_file");
print outfile "$anchor";
print outfile "</td><td>";
$anchor = &createHTMLAnchor("$output_file");
print outfile "$anchor";
print outfile "</td><td>";
$anchor = &createHTMLAnchor("$expected_result_file");
print outfile "$anchor";
print outfile "</td>";
# actual result
$result = (($ACTUAL_TEST_RESULTS[$i])?"true":"false");
print outfile "<td>$result</td>";
# correct result
$result = (($CORRECT_TEST_RESULTS[$i])?"true":"false");
print outfile "<td>$result</td>";
if ($outcome eq 1) {
$successes++;
$result = "Passed";
print "[test $testNum PASSED]\n";
$correct++;
} else {
$result = "Failed";
print "[test $testNum FAILED]\n";
}
print outfile "<td>$result</td></tr>";
}
print outfile "</table>";
print "Tests Passed: $correct\n";
$percentSucceeding = $correct / $numTestsToRun * 100.0;
print outfile "<hr/><h2>$percentSucceeding% of tests that were run passed ($correct out of $numTestsToRun).</h2>";
$shPass = 0;
$shFail = 0;
for ($i = 1; $i < $NUM_TESTS+1; $i++){
if ($CORRECT_TEST_RESULTS[$i]){
$shPass++;
} else {
$shFail++;
}
}
print outfile "<h2>$shPass should pass ($successes) did</h2>";
$failures = $NUM_TESTS - $successes;
print outfile "<h2>$shFail should fail ($failures) did</h2>";
$percentSucceeding = $correct / $NUM_TESTS * 100.0;
print outfile "<h2>$percentSucceeding% of all available tests passed ($correct out of $NUM_TESTS).</h2>";
$percentSucceeding = $numTestsToRun / $NUM_TESTS * 100.0;
print outfile "<h2>$percentSucceeding% of all available tests were run ($numTestsToRun out of $NUM_TESTS).</h2>";
print outfile "</center><hr/></body></html>";
close(outfile);
# quick and dirty but functional
sub compareFiles
{
$result = 1;
print "C[$_[0]]:[$_[1]]\n";
if (! -e $_[0]) {
print "No such file as $_[0] - cannot compare\n";
return 0;
}
if (! -e $_[1]) {
print "No such file as $_[1] - cannot compare\n";
return 0;
}
open(expected, "<$_[0]");
open(actual, "<$_[1]");
#compare the files
@expectedData = <expected>;
@actualData = <actual>;
close(expected);
close(actual);
for ($x = 0, $a = 0; $x < $#expectedData && $a < $#actualData; $x++, $a++){
$dataLineEx = $expectedData[$x];
$dataLineAc = $actualData[$a];
chomp($dataLineEx);
chomp($dataLineAc);
if ($dataLineEx ne $dataLineAc) {
# check if its a warning and can be ignored at this stage
if ($dataLineEx =~ /Warning/) {
print "probably just a warning line:\n";
print "[$dataLineEx]\n";
$a--
} elsif ( $dataLineEx =~ m/^\s*$/ && $dataLineAc =~ m/^\s*$/ ) {
$line_num = $x + 1;
print "Line $line_num ws difference: \n[$dataLineEx] != \n[$dataLineAc]\n";
print "probably just white space on both lines\n";
$a--
} else {
$line_num = $x + 1;
print "Line $line_num difference: \n[$dataLineEx] != \n[$dataLineAc]\n";
print "From files: $_[0] $_[1]\n";
return 0;
}
}
}
return 1;
}
sub createHTMLAnchor {
"<a target=\"_blank\" href=\"$_[0]\">$_[0]</a>";
}
| Distrotech/xerces-c | tests/src/xinclude/harness.pl | Perl | apache-2.0 | 7,327 |
% Loads all tests. Names are relative to CWD.
:- load_files([
tests/link,
tests/header,
tests/list_item,
tests/block,
tests/span_link,
tests/span,
tests/html,
tests/file
], [ if(not_loaded) ]).
| rla/prolog-markdown | tests/tests.pl | Perl | mit | 227 |
package Win32::Service;
#
# Service.pm
# Written by Douglas_Lankshear@ActiveWare.com
#
# subsequently hacked by Gurusamy Sarathy <gsar@cpan.org>
#
$VERSION = '0.06';
require Exporter;
require DynaLoader;
require Win32 unless defined &Win32::IsWinNT;
die "The Win32::Service module works only on Windows NT" unless Win32::IsWinNT();
@ISA= qw( Exporter DynaLoader );
@EXPORT_OK =
qw(
StartService
StopService
GetStatus
PauseService
ResumeService
GetServices
);
=head1 NAME
Win32::Service - Manage system services in Perl
=head1 SYNOPSIS
use Win32::Service;
=head1 DESCRIPTION
This module offers control over the administration of system services.
=head1 FUNCTIONS
=head2 NOTE:
All of the functions return false if they fail, unless otherwise noted.
If hostName is an empty string, the local machine is assumed.
=over 10
=item StartService(hostName, serviceName)
Start the service serviceName on machine hostName.
=item StopService(hostName, serviceName)
Stop the service serviceName on the machine hostName.
=item GetStatus(hostName, serviceName, status)
Get the status of a service. The third argument must be a hash
reference that will be populated with entries corresponding
to the SERVICE_STATUS structure of the Win32 API. See the
Win32 Platform SDK documentation for details of this structure.
=item PauseService(hostName, serviceName)
=item ResumeService(hostName, serviceName)
=item GetServices(hostName, hashref)
Enumerates both active and inactive Win32 services at the specified host.
The hashref is populated with the descriptive service names as keys
and the short names as the values.
=back
=cut
sub AUTOLOAD
{
my($constname);
($constname = $AUTOLOAD) =~ s/.*:://;
#reset $! to zero to reset any current errors.
local $! = 0;
my $val = constant($constname);
if ($! != 0) {
if($! =~ /Invalid/) {
$AutoLoader::AUTOLOAD = $AUTOLOAD;
goto &AutoLoader::AUTOLOAD;
}
else {
($pack,$file,$line) = caller;
die "Your vendor has not defined Win32::Service macro $constname, used in $file at line $line.";
}
}
eval "sub $AUTOLOAD { $val }";
goto &$AUTOLOAD;
}
bootstrap Win32::Service;
1;
__END__
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/Win32/Service.pm | Perl | mit | 2,206 |
use strict;
use CXGN::MasonFactory;
my $m = CXGN::MasonFactory->new();
$m->exec("/homepage/oldhighlights.mas");
| solgenomics/sgn | cgi-bin/oldhighlights.pl | Perl | mit | 116 |
:- module(main, []).
% Catch uncaught errors/warnings and shut down
% when they occur.
:- dynamic(loading/1).
:- asserta(loading(0)).
% The first hook is for detecting
% loading state.
user:message_hook(Term, _, _):-
( Term = load_file(start(Level, _))
-> asserta(loading(Level))
; ( Term = load_file(done(Level, _, _, _, _, _))
-> retractall(loading(Level))
; true)),
fail.
% The second hook shuts down SWI when
% error occurs during loading.
user:message_hook(Term, Type, _):-
loading(_),
( Type = error ; Type = warning ),
message_to_string(Term, String),
writeln(user_error, String),
halt(1).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_error)).
:- use_module(library(http/http_session)).
:- use_module(library(http/http_wrapper)).
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_unix_daemon)).
:- use_module(library(http/http_parameters)).
:- use_module(library(debug)).
:- use_module(library(docstore)).
:- use_module(library(arouter)).
:- use_module(library(st/st_render)).
:- use_module(library(st/st_file)).
:- use_module(api).
:- use_module(auth).
% Log errors to stderr.
:- debug(http(error)).
% Set session options.
:- http_set_session_options([
create(auto),
timeout(86400)
]).
% Sends front page.
:- route_get(/, do_auth, front).
front:-
format('Content-type: text/html; charset=UTF-8~n~n'),
current_output(Stream),
st_render_file(views/index, _{}, Stream,
_{ strip: true, cache: true }).
% Shows the login form.
:- route_get(login, login_form).
login_form:-
format('Content-type: text/html; charset=UTF-8~n~n'),
current_output(Stream),
st_render_file(views/login, _{}, Stream,
_{ strip: true, cache: true }).
% Runs authentication.
:- route_post(login, login_check).
login_check:-
http_current_request(Request),
http_parameters(Request, [
username(Username, [atom, default('')]),
password(Password, [atom, default('')])
]),
( auth(Username, Password)
-> http_session_assert(login),
http_redirect(see_other, '/', Request)
; http_redirect(see_other, '/login#invalid', Request)).
% Handles logout.
:- route_get(logout, logout).
logout:-
http_current_request(Request),
http_session_retractall(login),
http_redirect(see_other, '/login', Request).
% Main routing predicate.
top_route(Request):-
( route(Request)
-> true
; ( serve_file(Request)
-> true
; http_404([], Request))).
serve_file(Request):-
memberchk(path(Path), Request),
atom_concat(public, Path, File),
exists_file(File),
http_reply_file(File, [], Request).
http_unix_daemon:http_server_hook(Options):-
ds_open('data.docstore'),
http_server(top_route, Options).
% Provides toplevel for non-forking daemon.
toplevel:-
on_signal(int, _, quit),
on_signal(hup, _, quit),
on_signal(term, _, quit),
repeat,
thread_get_message(Msg),
Msg == quit,
halt(0).
quit(_) :-
thread_send_message(main, quit).
:- dynamic(started).
start:-
( started
-> true
; assertz(started),
http_daemon).
:- start.
| rla/expenses | main.pl | Perl | mit | 3,285 |
use strict;
use warnings;
package DashboardPassport;
use lib ".", "..", "../..";
use base qw(Passport);
use Crypt::CBC;
use Digest::MD5 qw(md5_base64);
use POSIX qw(strftime);
use DashboardUtils qw(:constants);
use Data::Dumper;
use Log;
sub getLoginParams {
my $self = shift;
my ($additional_params) = @_;
my %params = (
'lu' => DASHBOARD_LOGIN_URL,
'lt' => $self->getLoginToken(),
);
if ($additional_params) {
for my $k ( keys %{$additional_params} ) {
$params{$k} = $additional_params->{$k};
}
}
return \%params;
}
sub getLogoutParams {
my $self = shift;
my $cgi = new CGI;
my $sessionkey = $cgi->cookie(DASHBOARD_COOKIE_PASSPORT) || '';
my %params = (
'sk' => $sessionkey,
);
return \%params;
}
sub verifyCallbackToken {
my $self = shift;
my ( $Data, $callback_token, $errors ) = @_;
my $l = $Data->{'lang'};
my %result = (
'Result' => '',
'TimeStamp' => '',
'FailureReason' => CALLBACK_TOKEN_INVALID,
);
if ( !$callback_token ) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_INVALID;
}
else {
my $cipher = Crypt::CBC->new( -key => CALLBACK_ENCRYPTION_KEY,
-cipher => "Crypt::Blowfish" );
my $now = strftime '%Y%m%d%H%M', gmtime;
my $decrypted_token = $cipher->decrypt_hex($callback_token);
my ( $md5, $timestamp, $token_id ) = split( /\./, $decrypted_token );
$result{'TimeStamp'} = $timestamp || '';
if ( !( $md5 && $timestamp && $token_id ) ) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_INVALID;
push @{$errors}, $l->txt('Token invalid');
}
elsif ( ( $timestamp <= ( $now - 60 ) ) || $timestamp >= ( $now + 60 ) ) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_EXPIRED;
push @{$errors}, $l->txt('<div class="alert alert-warning">Your login session has expired</div>');
}
else {
my $md5_verify = md5_base64( CALLBACK_HASH_SECRET . $timestamp );
if ( $md5_verify ne $md5 ) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_INVALID;
push @{$errors}, $l->txt('Token failed verification step 1');
}
else {
my $st = qq[
SELECT strPassportCallbackToken, dtExpired
FROM tblPassportLoginToken
WHERE intPassportLoginTokenID = ?
];
my $q = $Data->{'db'}->prepare($st);
$q->execute($token_id);
my ( $md5_verify2, $date_expired ) = $q->fetchrow_array();
$q->finish();
if ($md5_verify2) {
$st = qq[
UPDATE tblPassportLoginToken
SET dtExpired = now()
WHERE intPassportLoginTokenID = ?
];
$q = $Data->{'db'}->prepare($st);
$q->execute($token_id);
$q->finish();
if ($date_expired) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_EXPIRED;
push @{$errors}, $l->txt('Your login session has expired.');
}
elsif ( $md5_verify2 ne $md5 ) {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_INVALID;
push @{$errors}, $l->txt('Token failed verification step 2');
}
else {
$result{'Result'} = 'SUCCESS';
$result{'FailureReason'} = 0;
}
}
else {
$result{'Result'} = 'FAILURE';
$result{'FailureReason'} = CALLBACK_TOKEN_INVALID;
push @{$errors}, $l->txt('Token not found');
}
}
}
}
return \%result;
}
sub getLoginToken {
my $self = shift;
my $now = strftime '%Y%m%d%H%M', gmtime;
my $md5 = md5_base64( CALLBACK_HASH_SECRET . $now );
my $cipher = Crypt::CBC->new( -key => CALLBACK_ENCRYPTION_KEY,
-cipher => "Crypt::Blowfish" );
my $st = qq[
INSERT INTO tblPassportLoginToken (strPassportCallbackToken,dtCreated)
VALUES (?,now());
];
my $q = $self->{'db'}->prepare($st);
$q->execute($md5);
my $token_id = $q->{'mysql_insertid'};
$q->finish();
my $token = $cipher->encrypt_hex("$md5.$now.$token_id");
my ( $tokenreq_ok, $tokenreq ) =
$self->_connect(
'GetLoginToken',
{
'CallbackURL' => DASHBOARD_LOGIN_URL,
'CallbackToken' => $token,
'Timestamp' => $now,
}
);
my $login_token = $tokenreq->{'Response'}{'Data'}{'LoginToken'} || '';
return $login_token;
}
sub loadSession {
my $self = shift;
my ($sessionK) = @_;
# This function returns information about the passport account
# currently logged in
my $output = new CGI;
my $sessionkey = $sessionK || $output->cookie(DASHBOARD_COOKIE_PASSPORT) || '';
return undef if !$sessionkey;
my $cache = $self->{'cache'} || undef;
my ( $tokenreq_ok, $tokenreq ) = ( '', '' );
if ($cache) {
my $cacheval = $cache->get( 'dash', 'DPSKEY_' . $sessionkey );
if ($cacheval) {
$tokenreq_ok = $cacheval->[0];
$tokenreq = $cacheval->[1];
}
}
if ( !$tokenreq_ok ) {
( $tokenreq_ok, $tokenreq ) =
$self->_connect(
'GetToken',
{
SessionKey => $sessionkey,
}
);
return undef if !$tokenreq_ok;
$cache->set( 'dash', "DPSKEY_$sessionkey", [ $tokenreq_ok, $tokenreq ], undef, 60 * 10 ) if $cache; #Cache for 10min
}
return undef if !$tokenreq_ok;
my $token = $tokenreq->{'Response'}{'Data'}{'PassportToken'} || '';
my $id = $tokenreq->{'Response'}{'Data'}{'PassportID'} || '';
$self->{'ID'} = $id if $id;
if ( $token and $id ) {
my ( $inforeq_ok, $inforeq ) = ( '', '' );
if ($cache) {
my $cacheval2 = $cache->get( 'dash', 'DPTOK_' . $token );
if ($cacheval2) {
$inforeq_ok = $cacheval2->[0];
$inforeq = $cacheval2->[1];
}
}
if ( !$inforeq_ok ) {
( $inforeq_ok, $inforeq ) =
$self->_connect(
'PassportInfo',
{
PassportToken => $token,
},
);
$cache->set( 'dash', "DPTOK_$token", [ $inforeq_ok, $inforeq ], undef, 60 * 10 ) if $cache; #Cache for 10min
}
if ($inforeq_ok) {
$self->{'Info'} = $inforeq->{'Response'}{'Data'};
}
}
}
1;
| facascante/slimerp | fifs/web/dashboard/DashboardPassport.pm | Perl | mit | 7,616 |
use strict;
use warnings;
# handler for custom size format eg: v32x16, 32x2
NODE SZ => {terminal => 1, mapto => 'size',
handler => sub{
local($_)=@_;
my $first = '';
s/^([vp]\d+x?)// and $first = $1;
again: s/(\d+)x(\d+)/$1*$2/e and goto again;
uc $first.$_;
}
};
NODE ENCODEDIN => {terminal => 1, lowercase => 1};
NODE LDACC => {terminal => 1, lowercase => 1};
NODE STACC => {terminal => 1, lowercase => 1};
# for all other nodes, we lowercase them:
NODE '*' => {lowercase => 1,};
1;
| MahdiSafsafi/opcodesDB | db/aarch64/nodes.pl | Perl | mit | 519 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.