answer
stringlengths
15
1.25M
<?php defined('_JEXEC') or die(); /** * Database Table filter Model class * */ class AkeebaModelDbefs extends FOFModel { /** * Returns a list of the database tables, views, procedures, functions and triggers, * along with their filter status in array format, for use in the GUI * @return array */ public function make_listing($root) { // Get database inclusion filters $filters = AEFactory::getFilters(); $database_list = $filters->getInclusions('db'); // Load the database object for the selected database $config = $database_list[$root]; $config['user'] = $config['username']; $db = AEFactory::getDatabase($config); // Load the table data $table_data = $db->getTables(); // Process filters $tables = array(); if(!empty($table_data)) { foreach($table_data as $table_name => $table_type) { $status = array(); // Add table type $status['type'] = $table_type; // Check dbobject/all filter (exclude) $result = $filters->isFilteredExtended($table_name, $root, 'dbobject', 'all', $byFilter); $status['tables'] = (!$result) ? 0 : (( $byFilter == 'tables' ) ? 1 : 2 ); // Check dbobject/content filter (skip table data) $result = $filters->isFilteredExtended($table_name, $root, 'dbobject', 'content', $byFilter); $status['tabledata'] = (!$result) ? 0 : (( $byFilter == 'tabledata' ) ? 1 : 2 ); if( $table_type != 'table' ) $status['tabledata'] = 2; // We can't filter contents of views, merge tables, black holes, procedures, functions and triggers :) $tables[$table_name] = $status; } } return array( 'tables' => $tables, 'root' => $root ); } /** * Returns an array containing a mapping of db root names and their human-readable representation * @return array Array of objects; "value" contains the root name, "text" the human-readable text */ public function get_roots() { // Get database inclusion filters $filters = AEFactory::getFilters(); $database_list = $filters->getInclusions('db'); $ret = array(); foreach($database_list as $name => $definition) { $root = $definition['host']; if(!empty($definition['port'])) $root.=':'.$definition['port']; $root.='/'.$definition['database']; if($name == '[SITEDB]') $root = JText::_('<API key>'); $entry = new stdClass(); $entry->value = $name; $entry->text = $root; $ret[] = $entry; } return $ret; } /** * Toggle a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to toggle the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function toggle($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->toggle($root, $item, $new_status); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $new_status ); } /** * Set a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function remove($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->remove($root, $item); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => !$success // The new state of the filter. It is removed if and only if the transaction succeeded ); } /** * Set a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function set($root, $item, $filter) { if(empty($item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter $success = $filter->set($root, $item); // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $success // The new state of the filter. It is set if and only if the transaction succeeded ); } /** * Swap a filter * @param string $root Root directory * @param string $item The child item of the current directory we want to set the filter for * @param string $filter The name of the filter to apply (directories, skipfiles, skipdirs, files) * @return array */ public function swap($root, $old_item, $new_item, $filter) { if(empty($new_item)) return array( 'success' => false, 'newstate'=> false ); // Get a reference to the global Filters object $filters = AEFactory::getFilters(); // Get the specific filter object $filter = AEFactory::getFilterObject($filter); // Toggle the filter if(!empty($old_item)) { $success = $filter->remove($root, $old_item); } else { $success = true; } if($success) { $success = $filter->set($root, $new_item); } // Save the data on success if($success) $filters->save(); // Make a return array return array( 'success' => $success, 'newstate' => $success // The new state of the filter. It is set if and only if the transaction succeeded ); } /** * Retrieves the filters as an array. Used for the tabular filter editor. * @param string $root The root node to search filters on * @return array A collection of hash arrays containing node and type for each filtered element */ public function &get_filters($root) { // A reference to the global Akeeba Engine filter object $filters = AEFactory::getFilters(); // Initialize the return array $ret = array(); // Define the known filter types and loop through them $filter_types = array('tables', 'tabledata'); foreach($filter_types as $type) { $rawFilterData = $filters->getFilterData($type); if( array_key_exists($root, $rawFilterData) ) { if(!empty($rawFilterData[$root])) { foreach($rawFilterData[$root] as $node) { $ret[] = array ( 'node' => substr($node,0), // Make sure we get a COPY, not a reference to the original data 'type' => $type ); } } } } /* * Return array format: * [array] : * [array] : * 'node' => 'somedir' * 'type' => 'directories' * [array] : * 'node' => 'somefile' * 'type' => 'files' * ... */ return $ret; } /** * Resets the filters * @param string $root Root directory * @return array */ public function resetFilters($root) { // Get a reference to the global Filters object $filters = AEFactory::getFilters(); $filter = AEFactory::getFilterObject('tables'); $filter->reset($root); $filter = AEFactory::getFilterObject('tabledata'); $filter->reset($root); $filters->save(); return $this->make_listing($root); } function doAjax() { $action = $this->getState('action'); $verb = array_key_exists('verb', get_object_vars($action)) ? $action->verb : null; $ret_array = array(); switch($verb) { // Return a listing for the normal view case 'list': $ret_array = $this->make_listing($action->root, $action->node); break; // Toggle a filter's state case 'toggle': $ret_array = $this->toggle($action->root, $action->node, $action->filter); break; // Set a filter (used by the editor) case 'set': $ret_array = $this->set($action->root, $action->node, $action->filter); break; // Remove a filter (used by the editor) case 'remove': $ret_array = $this->remove($action->root, $action->node, $action->filter); break; // Swap a filter (used by the editor) case 'swap': $ret_array = $this->swap($action->root, $action->old_node, $action->new_node, $action->filter); break; // Tabular view case 'tab': $ret_array = $this->get_filters($action->root); break; // Reset filters case 'reset': $ret_array = $this->resetFilters($action->root); break; } return $ret_array; } }
<?php namespace eZ\Publish\Core\MVC\Legacy\Templating\Converter; /** * Interface for multiple object converters. * This is useful if one needs to convert several objects at once. */ interface <API key> extends ObjectConverter { /** * Registers an object to the converter. * $alias is the variable name that will be exposed in the legacy template. * * @param mixed $object * @param string $alias * * @throws \<API key> If $object is not an object * * @return void */ public function register( $object, $alias ); /** * Converts all registered objects and returns them in a hash where the object's alias is the key. * * @return array|\eZ\Publish\Core\MVC\Legacy\Templating\LegacyCompatible[] */ public function convertAll(); }
#!/usr/bin/env perl # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # This library is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # You should have received a copy of the GNU Library General Public # Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, # MA 02110-1335 USA # Test of creating a simple table and inserting $record_count records in it, # $opt_loop_count rows in order, $opt_loop_count rows in reverse order and # $opt_loop_count rows in random order # changes made for Oracle compatibility # - $limits->{'func_odbc_mod'} is OK from crash-me, but it fails here so set we # set it to 0 in server-cfg # - the default server config runs out of rollback segments, so we added a # couple of disconnect/connects to reset use Cwd; use DBI; use Benchmark; use Data::Dumper; $opt_loop_count=100000; # number of rows/3 $small_loop_count=10; # Loop for full table retrieval $range_loop_count=$small_loop_count*50; $<API key>=$opt_loop_count; $<API key>=$opt_loop_count; $pwd = cwd(); $pwd = "." if ($pwd eq ''); require "$pwd/bench-init.pl" || die "Can't read Configuration file: $!\n"; if ($opt_small_test) { $opt_loop_count/=100; $<API key>=$opt_loop_count/10; $range_loop_count=10; $<API key>=10; } elsif ($opt_small_tables) { $opt_loop_count=10000; # number of rows/3 $<API key>=$opt_loop_count; $<API key>=10; } elsif ($<API key>) { $<API key>/=10; } if ($opt_loop_count < 100) { $opt_loop_count=100; # Some tests must have some data to work! } $range_loop_count=min($opt_loop_count,$range_loop_count); print "Testing the speed of inserting data into 1 table and do some selects on it.\n"; print "The tests are done with a table that has $opt_loop_count rows.\n\n"; # Generating random keys print "Generating random keys\n"; $random[$opt_loop_count]=0; for ($i=0 ; $i < $opt_loop_count ; $i++) { $random[$i]=$i+$opt_loop_count; } my $tmpvar=1; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $swap=$tmpvar % $opt_loop_count; $tmp=$random[$i]; $random[$i]=$random[$swap]; $random[$swap]=$tmp; } $total_rows=$opt_loop_count*3; # Connect and start timeing $start_time=new Benchmark; $dbh = $server->connect(); # Create needed tables goto keys_test if ($opt_stage == 2); goto select_test if ($opt_skip_create); print "Creating tables\n"; $dbh->do("drop table bench1" . $server->{'drop_attr'}); $dbh->do("drop table bench2" . $server->{'drop_attr'}); $dbh->do("drop table bench3" . $server->{'drop_attr'}); do_many($dbh,$server->create("bench1", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index ix_id3 (id3)"])); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } # Insert $total_rows records in order, in reverse order and random. $loop_time=new Benchmark; if ($opt_fast_insert) { $query="insert into bench1 values "; } else { $query="insert into bench1 (id,id2,id3,dummy1) values "; } if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; print "Transactions enabled\n" if ($opt_debug); } if (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'}) { $query_size=$server->{'limits'}->{'query_size'}; print "Inserting $opt_loop_count multiple-value rows in order\n"; $res=$query; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "($i,$i,$i,'ABCDEFGHIJ'),"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } print "Inserting $opt_loop_count multiple-value rows in reverse order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "(" . ($total_rows-1-$i) . "," .($total_rows-1-$i) . "," .($total_rows-1-$i) . ",'BCDEFGHIJK'),"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } print "Inserting $opt_loop_count multiple-value rows in random order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmp= "(" . $random[$i] . "," . $random[$i] . "," . $random[$i] . ",'CDEFGHIJKL')," or die $DBI::errstr; if (length($tmp)+length($res) < $query_size) { $res.= $tmp; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp; } } $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; } else { print "Inserting $opt_loop_count rows in order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "($i,$i,$i,'ABCDEFGHIJ')") or die $DBI::errstr; } print "Inserting $opt_loop_count rows in reverse order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "(" . ($total_rows-1-$i) . "," . ($total_rows-1-$i) . "," . ($total_rows-1-$i) . ",'BCDEFGHIJK')") or die $DBI::errstr; } print "Inserting $opt_loop_count rows in random order\n"; for ($i=0 ; $i < $opt_loop_count ; $i++) { $sth = $dbh->do($query . "(". $random[$i] . "," . $random[$i] . "," . $random[$i] . ",'CDEFGHIJKL')") or die $DBI::errstr; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert (" . ($total_rows) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } # insert $opt_loop_count records with duplicate id if ($limits->{'unique_index'}) { print "Testing insert of duplicates\n"; $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } for ($i=0 ; $i < $opt_loop_count ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); $tmpquery = "$query ($tmp,$tmp,2,'D')"; if ($dbh->do($tmpquery)) { die "Didn't get an error when inserting duplicate record $tmp\n"; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert_duplicates (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } # Do some selects on the table select_test: print "Test of prepared+execute/once prepared many execute selects\n"; $loop_time=new Benchmark; for ($i=1 ; $i <= $opt_loop_count ; $i++) { my ($key_value)=$random[$i]; my ($query)= "select * from bench1 where id=$key_value"; print "$query\n" if ($opt_debug); $sth = $dbh->prepare($query); if (! $sth) { die "error in prepare select with id = $key_value : $DBI::errstr"; }; if (! $sth->execute) { die "cannot execute prepare select with id = $key_value : $DBI::errstr"; } while ($sth->fetchrow_arrayref) { }; $sth->finish; }; $end_time=new Benchmark; print "Time for prepared_select ($opt_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $query= "select * from bench1 where id=?"; $sth = $dbh->prepare($query); if (! $sth) { die "cannot prepare select: $DBI::errstr"; }; for ($i=1 ; $i <= $opt_loop_count ; $i++) { my ($key_value)=$random[$i]; $sth->bind_param(1,$key_value); print "$query , id = $key_value\n" if ($opt_debug); if (! $sth->execute) { die "cannot execute prepare select with id = $key_value : $DBI::errstr"; } while ($sth->fetchrow_arrayref) { }; }; $sth->finish; $end_time=new Benchmark; print "Time for <API key> ($opt_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "Retrieving data from the table\n"; $loop_time=new Benchmark; $error=0; # It's really a small table, so we can try a select on everything $count=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { if (($found_rows=fetch_all_rows($dbh,"select id from bench1")) != $total_rows) { if (!$error++) { print "Warning: Got $found_rows rows when selecting a whole table of " . ($total_rows) . " rows\nContact the database or DBD author!\n"; } } $count+=$found_rows; } $end_time=new Benchmark; print "Time for select_big ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # Do a lot of different ORDER BY queries $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id,id2 from bench1 order by id,id2",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id,id2 from bench1 order by id desc, id2 desc",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for <API key> ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id from bench1 order by id desc",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for <API key> ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select id3 from bench1 order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big_key2 ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id2" : "*"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select $sel from bench1 order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for <API key> ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id" : "*"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $small_loop_count ; $i++) { $rows+=fetch_all_rows($dbh,"select $sel from bench1 order by id2,id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_big ($small_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "dummy1" : "dummy1,id3"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$i; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id>=$start and id <= $end order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_range ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "dummy1" : "dummy1,id"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$i; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id>=$start and id <= $end order by id",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_key_prefix ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $sel=$limits->{'order_by_unused'} ? "id2" : "id2,id3"; $loop_time=new Benchmark; $estimated=$rows=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { $start=$opt_loop_count/$range_loop_count*$i; $end=$start+$range_loop_count; $rows+=fetch_all_rows($dbh,"select $sel from bench1 where id3>=$start and id3 <= $end order by id3",1); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for order_by_key2_diff ($range_loop_count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # Test of select on 2 different keys with or # (In this case database can only use keys if they do an automatic union). $loop_time=new Benchmark; $estimated=0; $rows=0; $count=0; for ($i=1 ; $i <= $range_loop_count ; $i++) { my $rnd=$i; my $rnd2=$random[$i]; $rows+=fetch_all_rows($dbh,"select id2 from bench1 where id=$rnd or id3=$rnd2",1); $count++; $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$count, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for select_diff_key ($count:$rows): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # Test select that is very popular when using ODBC check_or_range("id","select_range_prefix"); check_or_range("id3","select_range_key2"); # Check reading on direct key on id and id3 check_select_key("*","id","select_key_prefix"); check_select_key2("*","id","id2","select_key"); check_select_key2("id,id2","id","id2","<API key>"); check_select_key("*","id3","select_key2"); check_select_key("id3","id3","<API key>"); check_select_key("id,id2","id3","<API key>"); # A lot of simple selects on ranges @Q=("select * from bench1 where !id!=3 or !id!=2 or !id!=1 or !id!=4 or !id!=16 or !id!=10", 6, "select * from bench1 where !id!>=" . ($total_rows-1) ." or !id!<1", 2, "select * from bench1 where !id!>=1 and !id!<=2", 2, "select * from bench1 where (!id!>=1 and !id!<=2) or (!id!>=1 and !id!<=2)", 2, "select * from bench1 where !id!>=1 and !id!<=10 and !id!<=5", 5, "select * from bench1 where (!id!>0 and !id!<2) or !id!>=" . ($total_rows-1), 2, "select * from bench1 where (!id!>0 and !id!<2) or (!id!>= " . ($opt_loop_count/2) . " and !id! <= " . ($opt_loop_count/2+2) . ") or !id! = " . ($opt_loop_count/2-1), 5, "select * from bench1 where (!id!>=5 and !id!<=10) or (!id!>=1 and !id!<=4)", 10, "select * from bench1 where (!id!=1 or !id!=2) and (!id!=3 or !id!=4)", 0, "select * from bench1 where (!id!=1 or !id!=2) and (!id!=2 or !id!=3)", 1, "select * from bench1 where (!id!=1 or !id!=5 or !id!=20 or !id!=40) and (!id!=1 or !id!>=20 or !id!=4)", 3, "select * from bench1 where ((!id!=1 or !id!=3) or (!id!>1 and !id!<3)) and !id!<=2", 2, "select * from bench1 where (!id! >= 0 and !id! < 4) or (!id! >=4 and !id! < 6)", 6, "select * from bench1 where !id! <= -1 or (!id! >= 0 and !id! <= 5) or (!id! >=4 and !id! < 6) or (!id! >=6 and !id! <=7) or (!id!>7 and !id! <= 8)", 9, "select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>=0 and !id! <=10)", 11, "select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>2 and !id! <=10)", 10, "select * from bench1 where (!id!>1 or !id! <1) and !id!<=2", 2, "select * from bench1 where !id! <= 2 and (!id!>1 or !id! <=1)", 3, "select * from bench1 where (!id!>=1 or !id! <1) and !id!<=2", 3, "select * from bench1 where (!id!>=1 or !id! <=2) and !id!<=2", 3 ); print "\nTest of compares with simple ranges\n"; check_select_range("id","select_range_prefix"); check_select_range("id3","select_range_key2"); # Some group queries if ($limits->{'group_functions'}) { $loop_time=new Benchmark; $count=1; $estimated=0; for ($tests=0 ; $tests < $small_loop_count ; $tests++) { $sth=$dbh->prepare($query="select count(*) from bench1") or die $DBI::errstr; $sth->execute or die $sth->errstr; if (($sth->fetchrow_array)[0] != $total_rows) { print "Warning: '$query' returned wrong result\n"; } $sth->finish; # min, max in keys are very normal $count+=7; fetch_all_rows($dbh,"select min(id) from bench1"); fetch_all_rows($dbh,"select max(id) from bench1"); fetch_all_rows($dbh,"select sum(id+0.0) from bench1"); fetch_all_rows($dbh,"select min(id3),max(id3),sum(id3-0.0) from bench1"); if ($limits->{'<API key>'}) { fetch_all_rows($dbh,"select min(dummy1),max(dummy1) from bench1"); } $count++; $sth=$dbh->prepare($query="select count(*) from bench1 where id >= " . ($opt_loop_count*2)) or die $DBI::errstr; $sth->execute or die $DBI::errstr; if (($sth->fetchrow_array)[0] != $opt_loop_count) { print "Warning: '$query' returned wrong result\n"; } $sth->finish; $count++; $sth=$dbh->prepare($query="select count(*),sum(id+0.0),min(id),max(id),avg(id-0.0) from bench1") or die $DBI::errstr; $sth->execute or die $DBI::errstr; @row=$sth->fetchrow_array; if ($row[0] != $total_rows || int($row[1]+0.5) != int((($total_rows-1)/2*$total_rows)+0.5) || $row[2] != 0 || $row[3] != $total_rows-1 || 1-$row[4]/(($total_rows-1)/2) > 0.001) { # PostgreSQL 6.3 fails here print "Warning: '$query' returned wrong result: @row\n"; } $sth->finish; if ($limits->{'func_odbc_mod'}) { $tmp="mod(id,10)"; if ($limits->{'func_extra_%'}) { $tmp="id % 10"; # For postgreSQL } $count++; if ($limits->{'group_by_alias'}) { if (fetch_all_rows($dbh,$query=$server->query("select $tmp as last_digit,count(*) from bench1 group by last_digit")) != 10) { print "Warning: '$query' returned wrong number of rows\n"; } } elsif ($limits->{'group_by_position'}) { if (fetch_all_rows($dbh,$query=$server->query("select $tmp,count(*) from bench1 group by 1")) != 10) { print "Warning: '$query' returned wrong number of rows\n"; } } } if ($limits->{'order_by_position'} && $limits->{'group_by_position'}) { $count++; if (fetch_all_rows($dbh, $query="select id,id3,dummy1 from bench1 where id < 100+$count-$count group by id,id3,dummy1 order by id desc,id3,dummy1") != 100) { print "Warning: '$query' returned wrong number of rows\n"; } } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $small_loop_count)); } print_time($estimated); print " for select_group ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $range_loop_count*5 ; $tests++) { $count+=6; fetch_all_rows($dbh,"select min(id) from bench1"); fetch_all_rows($dbh,"select max(id) from bench1"); fetch_all_rows($dbh,"select min(id2) from bench1 where id=$tests"); fetch_all_rows($dbh,"select max(id2) from bench1 where id=$tests"); if ($limits->{'<API key>'}) { fetch_all_rows($dbh,"select min(dummy1) from bench1 where id=$tests"); fetch_all_rows($dbh,"select max(dummy1) from bench1 where id=$tests"); } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $range_loop_count*5)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for min_max_on_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $small_loop_count ; $tests++) { $count+=6; fetch_all_rows($dbh,"select min(id2) from bench1"); fetch_all_rows($dbh,"select max(id2) from bench1"); fetch_all_rows($dbh,"select min(id3) from bench1 where id2=$tests"); fetch_all_rows($dbh,"select max(id3) from bench1 where id2=$tests"); if ($limits->{'<API key>'}) { fetch_all_rows($dbh,"select min(dummy1) from bench1 where id2=$tests"); fetch_all_rows($dbh,"select max(dummy1) from bench1 where id2=$tests"); } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for min_max ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; $total=$opt_loop_count*3; for ($tests=0 ; $tests < $total ; $tests+=$total/100) { $count+=1; fetch_all_rows($dbh,"select count(id) from bench1 where id < $tests"); } $end_time=new Benchmark; print "Time for count_on_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($tests=0 ; $tests < $total ; $tests+=$total/100) { $count+=1; fetch_all_rows($dbh,"select count(dummy1) from bench1 where id2 < $tests"); } $end_time=new Benchmark; print "Time for count ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($limits->{'<API key>'}) { $loop_time=new Benchmark; $count=$estimated=0; for ($tests=1 ; $tests <= $small_loop_count ; $tests++) { $count+=2; fetch_all_rows($dbh,"select count(distinct dummy1) from bench1"); fetch_all_rows($dbh,"select dummy1,count(distinct id) from bench1 group by dummy1"); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$tests, $small_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for count_distinct_big ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } # Some updates on the table $loop_time=new Benchmark; if ($limits->{'functions'}) { print "\nTesting update of keys with functions\n"; my $update_loop_count=$opt_loop_count/2; for ($i=0 ; $i < $update_loop_count ; $i++) { my $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows $sth = $dbh->do("update bench1 set id3=-$tmp where id3=$tmp") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_of_key ($update_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $loop_time=new Benchmark; $count=0; $step=int($opt_loop_count/$range_loop_count+1); for ($i= 0 ; $i < $opt_loop_count ; $i+= $step) { $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= 0 and id3 <= $i") or die $DBI::errstr; } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= 0 and id3 < $opt_loop_count") or die $DBI::errstr; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count++; $sth=$dbh->do("update bench1 set id3= 0-id3 where id3 >= $opt_loop_count and id3 < ". ($opt_loop_count*2)) or die $DBI::errstr; # Check that everything was updated # In principle we shouldn't time this in the update loop.. if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $row_count=0; if (($sth=$dbh->prepare("select count(*) from bench1 where id3>=0")) && $sth->execute) { ($row_count)=$sth->fetchrow; } $result=1 + $opt_loop_count-$update_loop_count; if ($row_count != $result) { print "Warning: Update check returned $row_count instead of $result\n"; } $sth->finish; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } #restore id3 to 0 <= id3 < $total_rows/10 or 0<= id3 < $total_rows my $func=($limits->{'func_odbc_floor'}) ? "floor((0-id3)/20)" : "0-id3"; $count++; $sth=$dbh->do($query="update bench1 set id3=$func where id3<0") or die $DBI::errstr; $end_time=new Benchmark; print "Time for update_of_key_big ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } else { print "\nTesting update of keys in loops\n"; # This is for mSQL that doesn't have functions. Do we really need this ???? $sth=$dbh->prepare("select id3 from bench1 where id3 >= 0") or die $DBI::errstr; $sth->execute or die $DBI::errstr; $count=0; while (@tmp = $sth->fetchrow_array) { my $tmp1 = "-$tmp[0]"; my $sth1 = $dbh->do("update bench1 set id3 = $tmp1 where id3 = $tmp[0]"); $count++; $end_time=new Benchmark; if (($end_time->[0] - $loop_time->[0]) > $opt_time_limit) { print "note: Aborting update loop because of timeout\n"; last; } } $sth->finish; # Check that everything except id3=0 was updated # In principle we shouldn't time this in the update loop.. if (fetch_all_rows($dbh,$query="select * from bench1 where id3>=0") != 1) { if ($count == $total_rows) { print "Warning: Wrong information after update: Found '$row_count' rows, but should have been: 1\n"; } } #restore id3 to 0 <= id3 < $total_rows $sth=$dbh->prepare("select id3 from bench1 where id3 < 0") or die $DBI::errstr; $sth->execute or die $DBI::errstr; while (@tmp = $sth->fetchrow_array) { $count++; my $tmp1 = floor((0-$tmp[0])/10); my $sth1 = $dbh->do("update bench1 set id3 = $tmp1 where id3 = $tmp[0]"); } $sth->finish; $end_time=new Benchmark; $estimated=predict_query_time($loop_time,$end_time,\$count,$count, $opt_loop_count*6); if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for update_of_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # Testing some simple updates print "Testing update with key\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $opt_loop_count*3 ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i and id2=$i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_with_key (" . ($opt_loop_count*3) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "Testing update with key, no changes in data\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $opt_loop_count*3 ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i and id2=$i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for <API key> (" . ($opt_loop_count*3) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i < $opt_loop_count*3 ; $i+=3) { $sth = $dbh->do("update bench1 set dummy1='really updated' where id=$i") or die $DBI::errstr; $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$i,($i-1)/3, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for <API key> (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; print "\nTesting update of all rows\n"; $loop_time=new Benchmark; for ($i=0 ; $i < $small_loop_count ; $i++) { $sth = $dbh->do("update bench1 set dummy1='updated $i'") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for update_big ($small_loop_count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; # Testing left outer join if ($limits->{'func_odbc_floor'} && $limits->{'left_outer_join'}) { if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 a READ, bench1 b READ") || die $DBI::errstr; } print "\nTesting left outer join\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(*) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)"); } $end_time=new Benchmark; print "Time for outer_join_on_key ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)"); } $end_time=new Benchmark; print "Time for outer_join ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $count=0; $loop_time=new Benchmark; for ($i=0 ; $i < $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is not null"); } $end_time=new Benchmark; print "Time for outer_join_found ($small_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $count=$estimated=0; $loop_time=new Benchmark; for ($i=1 ; $i <= $small_loop_count ; $i++) { $count+=fetch_all_rows($dbh,"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is null"); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time, \$count,$i, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for <API key> ($range_loop_count:$count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } Test speed of IN( value list) if ($limits->{'left_outer_join'}) { if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "\n"; do_many($dbh,$server->create("bench2", ["id int NOT NULL"], ["primary key (id)"])); $max_tests=min(($limits->{'query_size'}-50)/6, $opt_loop_count); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 READ, bench2 WRITE") || die $DBI::errstr; } test_where_in("bench1","bench2","id",1,10); test_where_in("bench1","bench2","id",11,min(100,$max_tests)); test_where_in("bench1","bench2","id",101,min(1000,$max_tests)); if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } $sth = $dbh->do("DROP TABLE bench2" . $server->{'drop_attr'}) || die $DBI::errstr; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # Test INSERT INTO ... SELECT if ($limits->{'insert_select'}) { if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "\nTesting INSERT INTO ... SELECT\n"; do_many($dbh,$server->create("bench2", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)"])); do_many($dbh,$server->create("bench3", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index index_id3 (id3)"])); $loop_time=new Benchmark; $sth = $dbh->do("INSERT INTO bench2 SELECT * from bench1") || die $DBI::errstr; $end_time=new Benchmark; print "Time for insert_select_1_key (1): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $sth = $dbh->do("INSERT INTO bench3 SELECT * from bench1") || die $DBI::errstr; $end_time=new Benchmark; print "Time for <API key> (1): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; $loop_time=new Benchmark; $sth = $dbh->do("DROP TABLE bench2" . $server->{'drop_attr'}) || die $DBI::errstr; $sth = $dbh->do("DROP TABLE bench3" . $server->{'drop_attr'}) || die $DBI::errstr; $end_time=new Benchmark; print "Time for drop table(2): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # Do some deletes on the table if (!$opt_skip_delete) { print "\nTesting delete\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < $opt_loop_count ; $i+=10) { $count++; $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows $dbh->do("delete from bench1 where id3=$tmp") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_key ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $count=0; $loop_time=new Benchmark; for ($i= 0 ; $i < $opt_loop_count ; $i+=$opt_loop_count/10) { $sth=$dbh->do("delete from bench1 where id3 >= 0 and id3 <= $i") or die $DBI::errstr; $count++; } $count+=2; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $sth=$dbh->do("delete from bench1 where id3 >= 0 and id3 <= $opt_loop_count") or die $DBI::errstr; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $sth=$dbh->do("delete from bench1 where id >= $opt_loop_count and id <= " . ($opt_loop_count*2) ) or die $DBI::errstr; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast) { $sth=$dbh->do("delete from bench1") or die $DBI::errstr; } else { $sth = $dbh->do("delete from bench1 where id3 < " . ($total_rows)) or die $DBI::errstr; } $end_time=new Benchmark; print "Time for delete_range ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } keys_test: # Test of insert in table with many keys # This test assumes that the server really create the keys! my @fields=(); my @keys=(); $keys=min($limits->{'max_index'},16); # 16 is more than enough $seg= min($limits->{'max_index_parts'},$keys,16); # 16 is more than enough print "Insert into table with $keys keys and with a primary key with $seg parts\n"; # Make keys on the most important types @types=(0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1); # A 1 for each char field push(@fields,"field1 tinyint not null"); push(@fields,"field_search tinyint not null"); push(@fields,"field2 mediumint not null"); push(@fields,"field3 smallint not null"); push(@fields,"field4 char(16) not null"); push(@fields,"field5 integer not null"); push(@fields,"field6 float not null"); push(@fields,"field7 double not null"); for ($i=8 ; $i <= $keys ; $i++) { push(@fields,"field$i char(6) not null"); # Should be relatively fair } # First key contains many segments $query="primary key ("; for ($i= 1 ; $i <= $seg ; $i++) { $query.= "field$i,"; } substr($query,-1)=")"; push (@keys,$query); push (@keys,"index index2 (field_search)"); #Create other keys for ($i=3 ; $i <= $keys ; $i++) { push(@keys,"index index$i (field$i)"); } do_many($dbh,$server->create("bench1",\@fields,\@keys)); if ($opt_lock_tables) { $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } $fields=$#fields; if (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'}) { $query_size=$server->{'limits'}->{'query_size'}; $query="insert into bench1 values "; $res=$query; for ($i=0; $i < $<API key>; $i++) { $id= $i & 127; $rand=$random[$i]; $tmp="($id,$id,$rand," . ($i & 32766) . ",'ABCDEF$rand',0,$rand,$rand.0,"; for ($j=8; $j <= $fields ; $j++) { $tmp.= ($types[$j] == 0) ? "$rand," : "'$rand',"; } substr($tmp,-1)=")"; if (length($tmp)+length($res) < $query_size) { $res.= $tmp . ","; } else { $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; $res=$query . $tmp . ","; } } $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr; } else { for ($i=0; $i < $<API key>; $i++) { $id= $i & 127; $rand=$random[$i]; $query="insert into bench1 values ($id,$id,$rand," . ($i & 32767) . ",'ABCDEF$rand',0,$rand,$rand.0,"; for ($j=8; $j <= $fields ; $j++) { $query.= ($types[$j] == 0) ? "$rand," : "'$rand',"; } substr($query,-1)=")"; print "query1: $query\n" if ($opt_debug); $dbh->do($query) or die "Got error $DBI::errstr with query: $query\n"; } } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for insert_key ($<API key>): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } # update one key of the above print "Testing update of keys\n"; $loop_time=new Benchmark; if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } for ($i=0 ; $i< 256; $i++) { $dbh->do("update bench1 set field5=1 where field_search=$i") or die "Got error $DBI::errstr with query: update bench1 set field5=1 where field_search=$i\n"; } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for <API key> (256): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } if ($opt_fast && defined($server->{vacuum})) { if ($opt_lock_tables) { do_query($dbh,"UNLOCK TABLES"); } $server->vacuum(1,\$dbh,"bench1"); if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 WRITE") || die $DBI::errstr; } } if ($server-><API key>()) { $dbh->disconnect; # close connection $dbh = $server->connect(); } # Delete everything from table print "Deleting rows from the table\n"; $loop_time=new Benchmark; $count=0; for ($i=0 ; $i < 128 ; $i++) { $count++; $dbh->do("delete from bench1 where field_search = $i") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for <API key> ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES") || die $DBI::errstr; } print "Deleting everything from table\n"; $count=1; if ($opt_fast) { $query= ($limits->{'truncate_table'} ? "truncate table bench1" : "delete from bench1"); $dbh->do($query) or die $DBI::errstr; } else { $dbh->do("delete from bench1 where field1 > 0") or die $DBI::errstr; } $end_time=new Benchmark; print "Time for <API key> ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh); } # Test multi value inserts if the server supports it if ($limits->{'insert_multi_value'}) { $query_size=$limits->{'query_size'}; # Same limit for all databases $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}); do_many($dbh,$server->create("bench1", ["id int NOT NULL", "id2 int NOT NULL", "id3 int NOT NULL", "dummy1 char(30)"], ["primary key (id,id2)", "index index_id3 (id3)"])); $loop_time=new Benchmark; if ($opt_lock_tables) { $sth = $dbh->do("LOCK TABLES bench1 write") || die $DBI::errstr; } if ($opt_fast && $server->{transactions}) { $dbh->{AutoCommit} = 0; } print "Inserting $opt_loop_count rows with multiple values\n"; $query="insert into bench1 values "; $res=$query; for ($i=0 ; $i < $opt_loop_count ; $i++) { my $tmp= "($i,$i,$i,'EFGHIJKLM'),"; if (length($i)+length($res) < $query_size) { $res.= $tmp; } else { do_query($dbh,substr($res,0,length($res)-1)); $res=$query .$tmp; } } do_query($dbh,substr($res,0,length($res)-1)); if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES ") || die $DBI::errstr; } if ($opt_fast && $server->{transactions}) { $dbh->commit; $dbh->{AutoCommit} = 1; } $end_time=new Benchmark; print "Time for <API key> (" . ($opt_loop_count) . "): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; if ($opt_lock_tables) { $sth = $dbh->do("UNLOCK TABLES ") || die $DBI::errstr; } # A big table may take a while to drop $loop_time=new Benchmark; $sth = $dbh->do("drop table bench1" . $server->{'drop_attr'}) or die $DBI::errstr; $end_time=new Benchmark; print "Time for drop table(1): " . timestr(timediff($end_time, $loop_time),"all") . "\n\n"; } # End of benchmark $dbh->disconnect; # close connection end_benchmark($start_time); Some help functions # Do some sample selects on direct key # First select finds a row, the second one doesn't find. sub check_select_key { my ($sel_columns,$column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated); $estimated=0; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i <= $<API key>; $i++) { $count+=2; $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp") or die $DBI::errstr; $tmp+=$total_rows; defined($row_count=fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp")) or die $DBI::errstr; die "Found $row_count rows on impossible id: $tmp\n" if ($row_count); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$i, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # Same as above, but select on 2 columns sub check_select_key2 { my ($sel_columns,$column,$column2,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated); $estimated=0; $loop_time=new Benchmark; $count=0; for ($i=1 ; $i <= $<API key>; $i++) { $count+=2; $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($total_rows); fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp") or die $DBI::errstr; $tmp+=$total_rows; defined($row_count=fetch_all_rows($dbh,"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp")) or die $DBI::errstr; die "Found $row_count rows on impossible id: $tmp\n" if ($row_count); $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$i, $opt_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # Search using some very simple queries sub check_select_range { my ($column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$query,$rows,$estimated); $estimated=0; $loop_time=new Benchmark; $found=$count=0; for ($test=1 ; $test <= $range_loop_count; $test++) { $count+=$ for ($i=0 ; $i < $#Q ; $i+=2) { $query=$Q[$i]; $rows=$Q[$i+1]; $query =~ s/!id!/$column/g; if (($row_count=fetch_all_rows($dbh,$query)) != $rows) { if ($row_count == undef()) { die "Got error: $DBI::errstr when executing $query\n"; } die "'$query' returned wrong number of rows: $row_count instead of $rows\n"; } $found+=$row_count; } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$test, $range_loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count:$found): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # SELECT * from bench where col=x or col=x or col=x ... sub check_or_range { my ($column,$check)= @_; my ($loop_time,$end_time,$i,$tmp_var,$tmp,$columns,$estimated,$found, $or_part,$count,$loop_count); $columns=min($limits->{'max_columns'},50,($limits->{'query_size'}-50)/13); $columns=$columns- ($columns % 4); # Make Divisible by 4 $estimated=0; $loop_time=new Benchmark; $found=0; # The number of tests must be divisible by the following $tmp= $limits->{'func_extra_in_num'} ? 15 : 10; # We need to calculate the exact number of test to make 'Estimated' right $loop_count=$range_loop_count*10+$tmp-1; $loop_count=$loop_count- ($loop_count % $tmp); for ($count=0 ; $count < $loop_count ; ) { for ($rowcnt=0; $rowcnt <= $columns; $rowcnt+= $columns/4) { my $query="select * from bench1 where "; my $or_part= "$column = 1"; $count+=2; for ($i=1 ; $i < $rowcnt ; $i++) { $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count); $tmp=$tmpvar % ($opt_loop_count*4); $or_part.=" or $column=$tmp"; } print $query . $or_part . "\n" if ($opt_debug); ($rows=fetch_all_rows($dbh,$query . $or_part)) or die $DBI::errstr; $found+=$rows; if ($limits->{'func_extra_in_num'}) { my $in_part=$or_part; # Same query, but use 'func_extra_in_num' instead. $in_part=~ s/ = / IN \(/; $in_part=~ s/ or $column=/,/g; $in_part.= ")"; fetch_all_rows($dbh,$query . $in_part) or die $DBI::errstr; $count++; } # Do it a little harder by setting a extra range defined(($rows=fetch_all_rows($dbh,"$query($or_part) and $column < 10"))) or die $DBI::errstr; $found+=$rows; } $end_time=new Benchmark; last if ($estimated=predict_query_time($loop_time,$end_time,\$count,$count, $loop_count)); } if ($estimated) { print "Estimated time"; } else { print "Time"; } print " for $check ($count:$found): " . timestr(timediff($end_time, $loop_time),"all") . "\n"; } # General test of SELECT ... WHERE id in(value-list) sub test_where_in { my ($t1,$t2,$id,$from,$to)= @_; return if ($from >= $to); $query="SELECT $t1.* FROM $t1 WHERE $id IN ("; for ($i=1 ; $i <= $to ; $i++) { $query.="$i,"; } $query=substr($query,0,length($query)-1) . ")"; # Fill join table to have the same id's as 'query' for ($i= $from ; $i <= $to ; $i++) { $dbh->do("insert into $t2 values($i)") or die $DBI::errstr; } if ($opt_fast && defined($server->{vacuum})) { $server->vacuum(1,\$dbh,"bench1"); } time_fetch_all_rows("Testing SELECT ... WHERE id in ($to values)", "select_in", $query, $dbh, $range_loop_count); time_fetch_all_rows(undef, "select_join_in", "SELECT $t1.* FROM $t2 left outer join $t1 on ($t1.$id=$t2.$id)", $dbh, $range_loop_count); }
var <API key> = new Ext.data.Store({ fields:[ {name : 'Name'}, {name : 'ID'}, {name : 'Mail'}, {name : 'Roles'} ], reader : AccountReader }); var UserInformationItem = [ { fieldLabel : 'User ID', name : 'id', readOnly : true }, { fieldLabel : 'User Name', name : 'username', allowBlank : false, regex : /^[^"'\\><&]*$/, regexText : 'deny following char " < > \\ & \'' }, { id : '<API key>', fieldLabel : 'Password', name : 'passwd', inputType : 'password', listeners : { 'change': function() { if (this.getValue() == "") { Ext.getCmp('<API key>').getTopToolbar().get('<API key>').setDisabled(false); Ext.getCmp("<API key>").allowBlank = true; } else { Ext.getCmp('<API key>').getTopToolbar().get('<API key>').setDisabled(true); Ext.getCmp("<API key>").allowBlank = false; } } } }, { id : '<API key>', fieldLabel : 'Re-enter', initialPassField : 'passwd', name : 'reenter', inputType : 'password', initialPassField: '<API key>', vtype : 'pwdvalid', listeners : { 'change': function() { if (Ext.getCmp("<API key>").getValue() == "") { Ext.getCmp('<API key>').getTopToolbar().get('<API key>').setDisabled(true); this.allowBlank = true; } else { Ext.getCmp('<API key>').getTopToolbar().get('<API key>').setDisabled(false); this.allowBlank = false; } } } }, { fieldLabel : 'E-mail Address', name : 'email', vtype : 'email', allowBlank : false } ]; // the form is for UserInformation Page ezScrum.UserInformationForm = Ext.extend(ezScrum.layout.InfoForm, { id : '<API key>', url : 'getUserData.do', modifyurl : 'updateAccount.do' , store : <API key>, width:500, bodyStyle:'padding:50px', monitorValid : true, buttonAlign:'center', initComponent : function() { var config = { items : [UserInformationItem], buttons : [{ formBind : true, text : 'Submit', scope : this, handler : this.submit, disabled : true }] } Ext.apply(this, Ext.apply(this.initialConfig, config)); ezScrum.UserInformationForm.superclass.initComponent.apply(this, arguments); }, submit : function() { Ext.getCmp('<API key>').doModify(); }, loadDataModel: function() { <API key>(); Ext.Ajax.request({ scope : this, url : this.url, success: function(response) { <API key>.loadData(response.responseXML); var record = <API key>.getAt(0); this.setDataModel(record); <API key>(); }, failure: function(response) { <API key>(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); }, setDataModel: function(record) { this.getForm().reset(); this.getForm().setValues({ id : record.data['ID'], username: record.data['Name'], passwd : '', reenter : '', email : record.data['Mail'] }); }, doModify: function() { <API key>(); Ext.Ajax.request({ scope : this, url : this.modifyurl, params : this.getForm().getValues(), success : function(response) { <API key>.loadData(response.responseXML); var record = <API key>.getAt(0); if (record) { Ext.example.msg('Update Account', 'Update Account Success'); } else { Ext.example.msg('Update Account', 'Update Account Failure'); } <API key>(); }, failure:function(response){ <API key>(); Ext.example.msg('Server Error', 'Sorry, the connection is failure.'); } }); } }); Ext.reg('UserInformationForm', ezScrum.UserInformationForm);
/** Container for a single photo, may not always contain a real photo, but * just text element. * @see JPhotoAlbumLink.java */ package fi.iki.jka; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.<API key>; import com.drew.metadata.exif.ExifDirectory; public class JPhotoDirectory extends JPhoto { public JPhotoDirectory() { this(defaultOwner, null); } public JPhotoDirectory(JPhotoCollection owner) { this(owner, null); } public JPhotoDirectory(File original) { this(defaultOwner, original); } public JPhotoDirectory(JPhotoCollection owner, File original) { super(owner, original); } public BufferedImage getThumbImage() { InputStream ins = getClass().getClassLoader().getResourceAsStream("pics/directory.png"); Iterator readers = ImageIO.<API key>("png"); ImageReader imageReader = (ImageReader)readers.next(); BufferedImage thumb = null; try { imageReader.setInput(new <API key>(ins, null)); thumb = imageReader.read(0); ins.close(); } catch (Exception e) { System.out.println("getThumbImage:"+e); } imageReader.dispose(); return thumb; } public BufferedImage getCachedThumb() { return getThumbImage(); } public BufferedImage getThumbImageAsync() { return getThumbImage(); } public BufferedImage getFullImage() { return null; } public ExifDirectory getExifDirectory() { return null; } public String toString() { return "Directory='"+getImageName()+"'"; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Tue Aug 12 22:14:04 PDT 2014 --> <title>org.creativecommons.nutch (apache-nutch 1.9 API)</title> <meta name="date" content="2014-08-12"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../org/creativecommons/nutch/package-summary.html" target="classFrame">org.creativecommons.nutch</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="CCIndexingFilter.html" title="class in org.creativecommons.nutch" target="classFrame">CCIndexingFilter</a></li> <li><a href="CCParseFilter.html" title="class in org.creativecommons.nutch" target="classFrame">CCParseFilter</a></li> <li><a href="CCParseFilter.Walker.html" title="class in org.creativecommons.nutch" target="classFrame">CCParseFilter.Walker</a></li> </ul> </div> </body> </html>
/** * SECTION:gstvalue * @short_description: GValue implementations specific * to GStreamer * * GValue implementations specific to GStreamer. * * Note that operations on the same #GValue from multiple threads may lead to * undefined behaviour. * * Last reviewed on 2008-03-11 (0.10.18) */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "gst_private.h" #include "glib-compat-private.h" #include <gst/gst.h> #include <gobject/gvaluecollector.h> #include "gstutils.h" typedef struct _GstValueUnionInfo GstValueUnionInfo; struct _GstValueUnionInfo { GType type1; GType type2; GstValueUnionFunc func; }; typedef struct <API key> <API key>; struct <API key> { GType type1; GType type2; <API key> func; }; typedef struct <API key> <API key>; struct <API key> { GType minuend; GType subtrahend; <API key> func; }; #define <API key> \ (<API key> >> <API key>) #define FUNDAMENTAL_TYPE_ID(type) \ ((type) >> <API key>) #define VALUE_LIST_SIZE(v) (((GArray *) (v)->data[0].v_pointer)->len) #define <API key>(v, index) ((const GValue *) &g_array_index ((GArray *) (v)->data[0].v_pointer, GValue, (index))) static GArray *gst_value_table; static GHashTable *gst_value_hash; static GstValueTable *<API key>[<API key> + 1]; static GArray *<API key>; static GArray *<API key>; static GArray *<API key>; /* Forward declarations */ static gchar *<API key> (const GValue * value); static GstValueCompareFunc <API key> (const GValue * value1); static gint <API key> (const GValue * value1, const GValue * value2, GstValueCompareFunc compare); static gchar *gst_string_wrap (const gchar * s); static gchar *<API key> (gchar * s); static gchar *gst_string_unwrap (const gchar * s); static inline GstValueTable * <API key> (GType type) { if (G_LIKELY (<API key> (type))) return <API key>[FUNDAMENTAL_TYPE_ID (type)]; else return g_hash_table_lookup (gst_value_hash, (gpointer) type); } static void <API key> (GType type, const GstValueTable * table) { if (<API key> (type)) <API key>[FUNDAMENTAL_TYPE_ID (type)] = (gpointer) table; g_hash_table_insert (gst_value_hash, (gpointer) type, (gpointer) table); } /* two helper functions to serialize/stringify any type of list * regular lists are done with { }, arrays with < > */ static gchar * <API key> (const GValue * value, const gchar * begin, const gchar * end) { guint i; GArray *array = value->data[0].v_pointer; GString *s; GValue *v; gchar *s_val; guint alen = array->len; /* estimate minimum string length to minimise re-allocs in GString */ s = g_string_sized_new (2 + (6 * alen) + 2); g_string_append (s, begin); for (i = 0; i < alen; i++) { v = &g_array_index (array, GValue, i); s_val = gst_value_serialize (v); g_string_append (s, s_val); g_free (s_val); if (i < alen - 1) { g_string_append_len (s, ", ", 2); } } g_string_append (s, end); return g_string_free (s, FALSE); } static void <API key> (const GValue * src_value, GValue * dest_value, const gchar * begin, const gchar * end) { GValue *list_value; GArray *array; GString *s; guint i; gchar *list_s; guint alen; array = src_value->data[0].v_pointer; alen = array->len; /* estimate minimum string length to minimise re-allocs in GString */ s = g_string_sized_new (2 + (10 * alen) + 2); g_string_append (s, begin); for (i = 0; i < alen; i++) { list_value = &g_array_index (array, GValue, i); if (i != 0) { g_string_append_len (s, ", ", 2); } list_s = <API key> (list_value); g_string_append (s, list_s); g_free (list_s); } g_string_append (s, end); dest_value->data[0].v_pointer = g_string_free (s, FALSE); } /* * helper function to see if a type is fixed. Is used internally here and * there. Do not export, since it doesn't work for types where the content * decides the fixedness (e.g. GST_TYPE_ARRAY). */ static gboolean gst_type_is_fixed (GType type) { /* the basic int, string, double types */ if (type <= <API key> (<API key>)) { return TRUE; } /* our fundamental types that are certainly not fixed */ if (type == GST_TYPE_INT_RANGE || type == <API key> || type == <API key> || type == GST_TYPE_LIST || type == <API key>) { return FALSE; } /* other (boxed) types that are fixed */ if (type == GST_TYPE_BUFFER) { return TRUE; } /* heavy checks */ if (<API key> (type) || G_TYPE_FUNDAMENTAL (type) <= <API key> (<API key>)) { return TRUE; } return FALSE; } /* GValue functions usable for both regular lists and arrays */ static void <API key> (GValue * value) { value->data[0].v_pointer = g_array_new (FALSE, TRUE, sizeof (GValue)); } static GArray * <API key> (const GArray * src) { GArray *dest; guint i, len; len = src->len; dest = g_array_sized_new (FALSE, TRUE, sizeof (GValue), len); g_array_set_size (dest, len); for (i = 0; i < len; i++) { <API key> (&g_array_index (dest, GValue, i), &g_array_index (src, GValue, i)); } return dest; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = <API key> ((GArray *) src_value->data[0].v_pointer); } static void <API key> (GValue * value) { guint i, len; GArray *src = (GArray *) value->data[0].v_pointer; len = src->len; if ((value->data[1].v_uint & <API key>) == 0) { for (i = 0; i < len; i++) { g_value_unset (&g_array_index (src, GValue, i)); } g_array_free (src, TRUE); } } static gpointer <API key> (const GValue * value) { return value->data[0].v_pointer; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (collect_flags & <API key>) { value->data[0].v_pointer = collect_values[0].v_pointer; value->data[1].v_uint = <API key>; } else { value->data[0].v_pointer = <API key> ((GArray *) collect_values[0].v_pointer); } return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { GArray **dest = collect_values[0].v_pointer; if (!dest) return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!value->data[0].v_pointer) return g_strdup_printf ("invalid value given for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_flags & <API key>) { *dest = (GArray *) value->data[0].v_pointer; } else { *dest = <API key> ((GArray *) value->data[0].v_pointer); } return NULL; } /** * <API key>: * @value: a #GValue of type #GST_TYPE_LIST * @append_value: the value to append * * Appends @append_value to the GstValueList in @value. */ void <API key> (GValue * value, const GValue * append_value) { GValue val = { 0, }; g_return_if_fail (<API key> (value)); g_return_if_fail (G_IS_VALUE (append_value)); <API key> (&val, append_value); g_array_append_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #ifndef GSTREAMER_LITE /** * <API key>: * @value: a #GValue of type #GST_TYPE_LIST * @prepend_value: the value to prepend * * Prepends @prepend_value to the GstValueList in @value. */ void <API key> (GValue * value, const GValue * prepend_value) { GValue val = { 0, }; g_return_if_fail (<API key> (value)); g_return_if_fail (G_IS_VALUE (prepend_value)); <API key> (&val, prepend_value); <API key> ((GArray *) value->data[0].v_pointer, &val, 1); } #endif // GSTREAMER_LITE /** * <API key>: * @dest: (out caller-allocates): an uninitialized #GValue to take the result * @value1: a #GValue * @value2: a #GValue * * Concatenates copies of @value1 and @value2 into a list. Values that are not * of type #GST_TYPE_LIST are treated as if they were lists of length 1. * @dest will be initialized to the type #GST_TYPE_LIST. */ void <API key> (GValue * dest, const GValue * value1, const GValue * value2) { guint i, value1_length, value2_length; GArray *array; g_return_if_fail (dest != NULL); g_return_if_fail (G_VALUE_TYPE (dest) == 0); g_return_if_fail (G_IS_VALUE (value1)); g_return_if_fail (G_IS_VALUE (value2)); value1_length = (<API key> (value1) ? VALUE_LIST_SIZE (value1) : 1); value2_length = (<API key> (value2) ? VALUE_LIST_SIZE (value2) : 1); g_value_init (dest, GST_TYPE_LIST); array = (GArray *) dest->data[0].v_pointer; g_array_set_size (array, value1_length + value2_length); if (<API key> (value1)) { for (i = 0; i < value1_length; i++) { <API key> (&g_array_index (array, GValue, i), <API key> (value1, i)); } } else { <API key> (&g_array_index (array, GValue, 0), value1); } if (<API key> (value2)) { for (i = 0; i < value2_length; i++) { <API key> (&g_array_index (array, GValue, i + value1_length), <API key> (value2, i)); } } else { <API key> (&g_array_index (array, GValue, value1_length), value2); } } /** * <API key>: * @dest: (out caller-allocates): an uninitialized #GValue to take the result * @value1: a #GValue * @value2: a #GValue * * Merges copies of @value1 and @value2. Values that are not * of type #GST_TYPE_LIST are treated as if they were lists of length 1. * * The result will be put into @dest and will either be a list that will not * contain any duplicates, or a non-list type (if @value1 and @value2 * were equal). * * Since: 0.10.32 */ void <API key> (GValue * dest, const GValue * value1, const GValue * value2) { guint i, j, k, value1_length, value2_length, skipped; const GValue *src; gboolean skip; GArray *array; g_return_if_fail (dest != NULL); g_return_if_fail (G_VALUE_TYPE (dest) == 0); g_return_if_fail (G_IS_VALUE (value1)); g_return_if_fail (G_IS_VALUE (value2)); value1_length = (<API key> (value1) ? VALUE_LIST_SIZE (value1) : 1); value2_length = (<API key> (value2) ? VALUE_LIST_SIZE (value2) : 1); g_value_init (dest, GST_TYPE_LIST); array = (GArray *) dest->data[0].v_pointer; g_array_set_size (array, value1_length + value2_length); if (<API key> (value1)) { for (i = 0; i < value1_length; i++) { <API key> (&g_array_index (array, GValue, i), <API key> (value1, i)); } } else { <API key> (&g_array_index (array, GValue, 0), value1); } j = value1_length; skipped = 0; if (<API key> (value2)) { for (i = 0; i < value2_length; i++) { skip = FALSE; src = <API key> (value2, i); for (k = 0; k < value1_length; k++) { if (gst_value_compare (&g_array_index (array, GValue, k), src) == GST_VALUE_EQUAL) { skip = TRUE; skipped++; break; } } if (!skip) { <API key> (&g_array_index (array, GValue, j), src); j++; } } } else { skip = FALSE; for (k = 0; k < value1_length; k++) { if (gst_value_compare (&g_array_index (array, GValue, k), value2) == GST_VALUE_EQUAL) { skip = TRUE; skipped++; break; } } if (!skip) { <API key> (&g_array_index (array, GValue, j), value2); } } if (skipped) { guint new_size = value1_length + (value2_length - skipped); if (new_size > 1) { /* shrink list */ g_array_set_size (array, new_size); } else { GValue single_dest; /* size is 1, take single value in list and make it new dest */ single_dest = g_array_index (array, GValue, 0); /* clean up old value allocations: must set array size to 0, because * allocated values are not inited meaning g_value_unset() will not * work on them */ g_array_set_size (array, 0); g_value_unset (dest); /* the single value is our new result */ *dest = single_dest; } } } /** * <API key>: * @value: a #GValue of type #GST_TYPE_LIST * * Gets the number of values contained in @value. * * Returns: the number of values */ guint <API key> (const GValue * value) { <API key> (<API key> (value), 0); return ((GArray *) value->data[0].v_pointer)->len; } /** * <API key>: * @value: a #GValue of type #GST_TYPE_LIST * @index: index of value to get from the list * * Gets the value that is a member of the list contained in @value and * has the index @index. * * Returns: (transfer none): the value at the given index */ const GValue * <API key> (const GValue * value, guint index) { <API key> (<API key> (value), NULL); <API key> (index < VALUE_LIST_SIZE (value), NULL); return (const GValue *) &g_array_index ((GArray *) value->data[0].v_pointer, GValue, index); } /** * <API key>: * @value: a #GValue of type #GST_TYPE_ARRAY * @append_value: the value to append * * Appends @append_value to the GstValueArray in @value. */ void <API key> (GValue * value, const GValue * append_value) { GValue val = { 0, }; g_return_if_fail (<API key> (value)); g_return_if_fail (G_IS_VALUE (append_value)); <API key> (&val, append_value); g_array_append_vals ((GArray *) value->data[0].v_pointer, &val, 1); } #ifndef GSTREAMER_LITE /** * <API key>: * @value: a #GValue of type #GST_TYPE_ARRAY * @prepend_value: the value to prepend * * Prepends @prepend_value to the GstValueArray in @value. */ void <API key> (GValue * value, const GValue * prepend_value) { GValue val = { 0, }; g_return_if_fail (<API key> (value)); g_return_if_fail (G_IS_VALUE (prepend_value)); <API key> (&val, prepend_value); <API key> ((GArray *) value->data[0].v_pointer, &val, 1); } #endif // GSTREAMER_LITE /** * <API key>: * @value: a #GValue of type #GST_TYPE_ARRAY * * Gets the number of values contained in @value. * * Returns: the number of values */ guint <API key> (const GValue * value) { <API key> (<API key> (value), 0); return ((GArray *) value->data[0].v_pointer)->len; } /** * <API key>: * @value: a #GValue of type #GST_TYPE_ARRAY * @index: index of value to get from the array * * Gets the value that is a member of the array contained in @value and * has the index @index. * * Returns: (transfer none): the value at the given index */ const GValue * <API key> (const GValue * value, guint index) { <API key> (<API key> (value), NULL); <API key> (index < <API key> (value), NULL); return (const GValue *) &g_array_index ((GArray *) value->data[0].v_pointer, GValue, index); } static void <API key> (const GValue * src_value, GValue * dest_value) { <API key> (src_value, dest_value, "{ ", " }"); } static void <API key> (const GValue * src_value, GValue * dest_value) { <API key> (src_value, dest_value, "< ", " >"); } /* Do an unordered compare of the contents of a list */ static gint <API key> (const GValue * value1, const GValue * value2) { guint i, j; GArray *array1 = value1->data[0].v_pointer; GArray *array2 = value2->data[0].v_pointer; GValue *v1; GValue *v2; gint len, to_remove; guint8 *removed; GstValueCompareFunc compare; /* get length and do initial length check. */ len = array1->len; if (len != array2->len) return GST_VALUE_UNORDERED; /* place to mark removed value indices of array2 */ removed = g_newa (guint8, len); memset (removed, 0, len); to_remove = len; /* loop over array1, all items should be in array2. When we find an * item in array2, remove it from array2 by marking it as removed */ for (i = 0; i < len; i++) { v1 = &g_array_index (array1, GValue, i); if ((compare = <API key> (v1))) { for (j = 0; j < len; j++) { /* item is removed, we can skip it */ if (removed[j]) continue; v2 = &g_array_index (array2, GValue, j); if (<API key> (v1, v2, compare) == GST_VALUE_EQUAL) { /* mark item as removed now that we found it in array2 and * decrement the number of remaining items in array2. */ removed[j] = 1; to_remove break; } } /* item in array1 and not in array2, UNORDERED */ if (j == len) return GST_VALUE_UNORDERED; } else return GST_VALUE_UNORDERED; } /* if not all items were removed, array2 contained something not in array1 */ if (to_remove != 0) return GST_VALUE_UNORDERED; /* arrays are equal */ return GST_VALUE_EQUAL; } /* Perform an ordered comparison of the contents of an array */ static gint <API key> (const GValue * value1, const GValue * value2) { guint i; GArray *array1 = value1->data[0].v_pointer; GArray *array2 = value2->data[0].v_pointer; guint len = array1->len; GValue *v1; GValue *v2; if (len != array2->len) return GST_VALUE_UNORDERED; for (i = 0; i < len; i++) { v1 = &g_array_index (array1, GValue, i); v2 = &g_array_index (array2, GValue, i); if (gst_value_compare (v1, v2) != GST_VALUE_EQUAL) return GST_VALUE_UNORDERED; } return GST_VALUE_EQUAL; } static gchar * <API key> (const GValue * value) { return <API key> (value, "{ ", " }"); } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("<API key>: unimplemented"); return FALSE; } static gchar * <API key> (const GValue * value) { return <API key> (value, "< ", " >"); } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("<API key>: unimplemented"); return FALSE; } static void <API key> (GValue * value) { value->data[0].v_int = 0; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { value->data[0].v_int = collect_values[0].v_int; return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint32 *fourcc_p = collect_values[0].v_pointer; if (!fourcc_p) return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *fourcc_p = value->data[0].v_int; return NULL; } /** * <API key>: * @value: a GValue initialized to #GST_TYPE_FOURCC * @fourcc: the #guint32 fourcc to set * * Sets @value to @fourcc. */ void <API key> (GValue * value, guint32 fourcc) { g_return_if_fail (<API key> (value)); value->data[0].v_int = fourcc; } /** * <API key>: * @value: a GValue initialized to #GST_TYPE_FOURCC * * Gets the #guint32 fourcc contained in @value. * * Returns: the #guint32 fourcc contained in @value. */ guint32 <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[0].v_int; } static void <API key> (const GValue * src_value, GValue * dest_value) { guint32 fourcc = src_value->data[0].v_int; gchar fourcc_char[4]; fourcc_char[0] = (fourcc >> 0) & 0xff; fourcc_char[1] = (fourcc >> 8) & 0xff; fourcc_char[2] = (fourcc >> 16) & 0xff; fourcc_char[3] = (fourcc >> 24) & 0xff; if ((g_ascii_isalnum (fourcc_char[0]) || fourcc_char[0] == ' ') && (g_ascii_isalnum (fourcc_char[1]) || fourcc_char[1] == ' ') && (g_ascii_isalnum (fourcc_char[2]) || fourcc_char[2] == ' ') && (g_ascii_isalnum (fourcc_char[3]) || fourcc_char[3] == ' ')) { dest_value->data[0].v_pointer = g_strdup_printf ("%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); } else { dest_value->data[0].v_pointer = g_strdup_printf ("0x%08x", fourcc); } } static gint <API key> (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int == value1->data[0].v_int) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { guint32 fourcc = value->data[0].v_int; gchar fourcc_char[4]; fourcc_char[0] = (fourcc >> 0) & 0xff; fourcc_char[1] = (fourcc >> 8) & 0xff; fourcc_char[2] = (fourcc >> 16) & 0xff; fourcc_char[3] = (fourcc >> 24) & 0xff; if ((g_ascii_isalnum (fourcc_char[0]) || fourcc_char[0] == ' ') && (g_ascii_isalnum (fourcc_char[1]) || fourcc_char[1] == ' ') && (g_ascii_isalnum (fourcc_char[2]) || fourcc_char[2] == ' ') && (g_ascii_isalnum (fourcc_char[3]) || fourcc_char[3] == ' ')) { return g_strdup_printf ("%" GST_FOURCC_FORMAT, GST_FOURCC_ARGS (fourcc)); } else { return g_strdup_printf ("0x%08x", fourcc); } } static gboolean <API key> (GValue * dest, const gchar * s) { gboolean ret = FALSE; guint32 fourcc = 0; gchar *end; gint l = strlen (s); if (l == 4) { fourcc = GST_MAKE_FOURCC (s[0], s[1], s[2], s[3]); ret = TRUE; } else if (l == 3) { fourcc = GST_MAKE_FOURCC (s[0], s[1], s[2], ' '); ret = TRUE; } else if (l == 2) { fourcc = GST_MAKE_FOURCC (s[0], s[1], ' ', ' '); ret = TRUE; } else if (l == 1) { fourcc = GST_MAKE_FOURCC (s[0], ' ', ' ', ' '); ret = TRUE; } else if (g_ascii_isdigit (*s)) { fourcc = strtoul (s, &end, 0); if (*end == 0) { ret = TRUE; } } <API key> (dest, fourcc); return ret; } static void <API key> (GValue * value) { value->data[0].v_int = 0; value->data[1].v_int = 0; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; dest_value->data[1].v_int = src_value->data[1].v_int; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int >= collect_values[1].v_int) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_int = collect_values[0].v_int; value->data[1].v_int = collect_values[1].v_int; return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint32 *int_range_start = collect_values[0].v_pointer; guint32 *int_range_end = collect_values[1].v_pointer; if (!int_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!int_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *int_range_start = value->data[0].v_int; *int_range_end = value->data[1].v_int; return NULL; } /** * <API key>: * @value: a GValue initialized to GST_TYPE_INT_RANGE * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. */ void <API key> (GValue * value, gint start, gint end) { g_return_if_fail (<API key> (value)); g_return_if_fail (start < end); value->data[0].v_int = start; value->data[1].v_int = end; } /** * <API key>: * @value: a GValue initialized to GST_TYPE_INT_RANGE * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ gint <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[0].v_int; } /** * <API key>: * @value: a GValue initialized to GST_TYPE_INT_RANGE * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range */ gint <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[1].v_int; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = g_strdup_printf ("[%d,%d]", (int) src_value->data[0].v_int, (int) src_value->data[1].v_int); } static gint <API key> (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int == value1->data[0].v_int && value2->data[1].v_int == value1->data[1].v_int) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { return g_strdup_printf ("[ %d, %d ]", value->data[0].v_int, value->data[1].v_int); } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } static void <API key> (GValue * value) { value->data[0].v_int64 = 0; value->data[1].v_int64 = 0; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int64 = src_value->data[0].v_int64; dest_value->data[1].v_int64 = src_value->data[1].v_int64; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int64 >= collect_values[1].v_int64) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_int64 = collect_values[0].v_int64; value->data[1].v_int64 = collect_values[1].v_int64; return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { guint64 *int_range_start = collect_values[0].v_pointer; guint64 *int_range_end = collect_values[1].v_pointer; if (!int_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!int_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *int_range_start = value->data[0].v_int64; *int_range_end = value->data[1].v_int64; return NULL; } /** * <API key>: * @value: a GValue initialized to <API key> * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. * * Since: 0.10.31 */ void <API key> (GValue * value, gint64 start, gint64 end) { g_return_if_fail (<API key> (value)); g_return_if_fail (start < end); value->data[0].v_int64 = start; value->data[1].v_int64 = end; } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range * * Since: 0.10.31 */ gint64 <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[0].v_int64; } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range * * Since: 0.10.31 */ gint64 <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[1].v_int64; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = g_strdup_printf ("(gint64)[%" G_GINT64_FORMAT ",%" G_GINT64_FORMAT "]", src_value->data[0].v_int64, src_value->data[1].v_int64); } static gint <API key> (const GValue * value1, const GValue * value2) { if (value2->data[0].v_int64 == value1->data[0].v_int64 && value2->data[1].v_int64 == value1->data[1].v_int64) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { return g_strdup_printf ("[ %" G_GINT64_FORMAT ", %" G_GINT64_FORMAT " ]", value->data[0].v_int64, value->data[1].v_int64); } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } static void <API key> (GValue * value) { value->data[0].v_double = 0; value->data[1].v_double = 0; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_double = src_value->data[0].v_double; dest_value->data[1].v_double = src_value->data[1].v_double; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_double >= collect_values[1].v_double) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); value->data[0].v_double = collect_values[0].v_double; value->data[1].v_double = collect_values[1].v_double; return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gdouble *double_range_start = collect_values[0].v_pointer; gdouble *double_range_end = collect_values[1].v_pointer; if (!double_range_start) return g_strdup_printf ("start value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!double_range_end) return g_strdup_printf ("end value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *double_range_start = value->data[0].v_double; *double_range_end = value->data[1].v_double; return NULL; } /** * <API key>: * @value: a GValue initialized to <API key> * @start: the start of the range * @end: the end of the range * * Sets @value to the range specified by @start and @end. */ void <API key> (GValue * value, gdouble start, gdouble end) { g_return_if_fail (<API key> (value)); g_return_if_fail (start < end); value->data[0].v_double = start; value->data[1].v_double = end; } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ gdouble <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[0].v_double; } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the maximum of the range specified by @value. * * Returns: the maxumum of the range */ gdouble <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[1].v_double; } static void <API key> (const GValue * src_value, GValue * dest_value) { gchar s1[<API key>], s2[<API key>]; dest_value->data[0].v_pointer = g_strdup_printf ("[%s,%s]", g_ascii_dtostr (s1, <API key>, src_value->data[0].v_double), g_ascii_dtostr (s2, <API key>, src_value->data[1].v_double)); } static gint <API key> (const GValue * value1, const GValue * value2) { if (value2->data[0].v_double == value1->data[0].v_double && value2->data[0].v_double == value1->data[0].v_double) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { gchar d1[<API key>]; gchar d2[<API key>]; g_ascii_dtostr (d1, <API key>, value->data[0].v_double); g_ascii_dtostr (d2, <API key>, value->data[1].v_double); return g_strdup_printf ("[ %s, %s ]", d1, d2); } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } static void <API key> (GValue * value) { GValue *vals; GType ftype; ftype = GST_TYPE_FRACTION; value->data[0].v_pointer = vals = g_slice_alloc0 (2 * sizeof (GValue)); g_value_init (&vals[0], ftype); g_value_init (&vals[1], ftype); } static void <API key> (GValue * value) { GValue *vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { g_value_unset (&vals[0]); g_value_unset (&vals[1]); g_slice_free1 (2 * sizeof (GValue), vals); value->data[0].v_pointer = NULL; } } static void <API key> (const GValue * src_value, GValue * dest_value) { GValue *vals = (GValue *) dest_value->data[0].v_pointer; GValue *src_vals = (GValue *) src_value->data[0].v_pointer; if (vals == NULL) { <API key> (dest_value); vals = dest_value->data[0].v_pointer; } if (src_vals != NULL) { g_value_copy (&src_vals[0], &vals[0]); g_value_copy (&src_vals[1], &vals[1]); } } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { GValue *vals = (GValue *) value->data[0].v_pointer; if (n_collect_values != 4) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int == 0) return g_strdup_printf ("passed '0' as first denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[3].v_int == 0) return g_strdup_printf ("passed '0' as second denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (<API key> (collect_values[0].v_int, collect_values[1].v_int, collect_values[2].v_int, collect_values[3].v_int) >= 0) return g_strdup_printf ("range start is not smaller than end for `%s'", G_VALUE_TYPE_NAME (value)); if (vals == NULL) { <API key> (value); vals = value->data[0].v_pointer; } <API key> (&vals[0], collect_values[0].v_int, collect_values[1].v_int); <API key> (&vals[1], collect_values[2].v_int, collect_values[3].v_int); return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gint i; gint *dest_values[4]; GValue *vals = (GValue *) value->data[0].v_pointer; if (G_UNLIKELY (n_collect_values != 4)) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); for (i = 0; i < 4; i++) { if (G_UNLIKELY (collect_values[i].v_pointer == NULL)) { return g_strdup_printf ("value location for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); } dest_values[i] = collect_values[i].v_pointer; } if (G_UNLIKELY (vals == NULL)) { return g_strdup_printf ("Uninitialised `%s' passed", G_VALUE_TYPE_NAME (value)); } dest_values[0][0] = <API key> (&vals[0]); dest_values[1][0] = <API key> (&vals[0]); dest_values[2][0] = <API key> (&vals[1]); dest_values[3][0] = <API key> (&vals[1]); return NULL; } /** * <API key>: * @value: a GValue initialized to <API key> * @start: the start of the range (a GST_TYPE_FRACTION GValue) * @end: the end of the range (a GST_TYPE_FRACTION GValue) * * Sets @value to the range specified by @start and @end. */ void <API key> (GValue * value, const GValue * start, const GValue * end) { GValue *vals; g_return_if_fail (<API key> (value)); g_return_if_fail (<API key> (start)); g_return_if_fail (<API key> (end)); g_return_if_fail (<API key> (start->data[0].v_int, start->data[1].v_int, end->data[0].v_int, end->data[1].v_int) < 0); vals = (GValue *) value->data[0].v_pointer; if (vals == NULL) { <API key> (value); vals = value->data[0].v_pointer; } g_value_copy (start, &vals[0]); g_value_copy (end, &vals[1]); } /** * <API key>: * @value: a GValue initialized to <API key> * @numerator_start: the numerator start of the range * @denominator_start: the denominator start of the range * @numerator_end: the numerator end of the range * @denominator_end: the denominator end of the range * * Sets @value to the range specified by @numerator_start/@denominator_start * and @numerator_end/@denominator_end. */ void <API key> (GValue * value, gint numerator_start, gint denominator_start, gint numerator_end, gint denominator_end) { GValue start = { 0 }; GValue end = { 0 }; g_return_if_fail (value != NULL); g_return_if_fail (denominator_start != 0); g_return_if_fail (denominator_end != 0); g_return_if_fail (<API key> (numerator_start, denominator_start, numerator_end, denominator_end) < 0); g_value_init (&start, GST_TYPE_FRACTION); g_value_init (&end, GST_TYPE_FRACTION); <API key> (&start, numerator_start, denominator_start); <API key> (&end, numerator_end, denominator_end); <API key> (value, &start, &end); g_value_unset (&start); g_value_unset (&end); } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the minimum of the range specified by @value. * * Returns: the minimum of the range */ const GValue * <API key> (const GValue * value) { GValue *vals; <API key> (<API key> (value), NULL); vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { return &vals[0]; } return NULL; } /** * <API key>: * @value: a GValue initialized to <API key> * * Gets the maximum of the range specified by @value. * * Returns: the maximum of the range */ const GValue * <API key> (const GValue * value) { GValue *vals; <API key> (<API key> (value), NULL); vals = (GValue *) value->data[0].v_pointer; if (vals != NULL) { return &vals[1]; } return NULL; } static gchar * <API key> (const GValue * value) { GValue *vals = (GValue *) value->data[0].v_pointer; gchar *retval; if (vals == NULL) { retval = g_strdup ("[ 0/1, 0/1 ]"); } else { gchar *start, *end; start = <API key> (&vals[0]); end = <API key> (&vals[1]); retval = g_strdup_printf ("[ %s, %s ]", start, end); g_free (start); g_free (end); } return retval; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = <API key> (src_value); } static gint <API key> (const GValue * value1, const GValue * value2) { GValue *vals1, *vals2; GstValueCompareFunc compare; if (value2->data[0].v_pointer == value1->data[0].v_pointer) return GST_VALUE_EQUAL; /* Only possible if both are NULL */ if (value2->data[0].v_pointer == NULL || value1->data[0].v_pointer == NULL) return GST_VALUE_UNORDERED; vals1 = (GValue *) value1->data[0].v_pointer; vals2 = (GValue *) value2->data[0].v_pointer; if ((compare = <API key> (&vals1[0]))) { if (<API key> (&vals1[0], &vals2[0], compare) == GST_VALUE_EQUAL && <API key> (&vals1[1], &vals2[1], compare) == GST_VALUE_EQUAL) return GST_VALUE_EQUAL; } return GST_VALUE_UNORDERED; } static gboolean <API key> (GValue * dest, const gchar * s) { g_warning ("unimplemented"); return FALSE; } /** * gst_value_set_caps: * @value: a GValue initialized to GST_TYPE_CAPS * @caps: (transfer none): the caps to set the value to * * Sets the contents of @value to @caps. A reference to the * provided @caps will be taken by the @value. */ void gst_value_set_caps (GValue * value, const GstCaps * caps) { g_return_if_fail (G_IS_VALUE (value)); g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_CAPS); g_return_if_fail (caps == NULL || GST_IS_CAPS (caps)); g_value_set_boxed (value, caps); } /** * gst_value_get_caps: * @value: a GValue initialized to GST_TYPE_CAPS * * Gets the contents of @value. The reference count of the returned * #GstCaps will not be modified, therefore the caller must take one * before getting rid of the @value. * * Returns: (transfer none): the contents of @value */ const GstCaps * gst_value_get_caps (const GValue * value) { <API key> (G_IS_VALUE (value), NULL); <API key> (G_VALUE_TYPE (value) == GST_TYPE_CAPS, NULL); return (GstCaps *) g_value_get_boxed (value); } static gchar * <API key> (const GValue * value) { GstCaps *caps = g_value_get_boxed (value); return gst_caps_to_string (caps); } static gboolean <API key> (GValue * dest, const gchar * s) { GstCaps *caps; caps = <API key> (s); if (caps) { g_value_take_boxed (dest, caps); return TRUE; } return FALSE; } /** * <API key>: * @value: a GValue initialized to GST_TYPE_STRUCTURE * @structure: the structure to set the value to * * Sets the contents of @value to @structure. The actual * * Since: 0.10.15 */ void <API key> (GValue * value, const GstStructure * structure) { g_return_if_fail (G_IS_VALUE (value)); g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_STRUCTURE); g_return_if_fail (structure == NULL || GST_IS_STRUCTURE (structure)); g_value_set_boxed (value, structure); } /** * <API key>: * @value: a GValue initialized to GST_TYPE_STRUCTURE * * Gets the contents of @value. * * Returns: (transfer none): the contents of @value * * Since: 0.10.15 */ const GstStructure * <API key> (const GValue * value) { <API key> (G_IS_VALUE (value), NULL); <API key> (G_VALUE_TYPE (value) == GST_TYPE_STRUCTURE, NULL); return (GstStructure *) g_value_get_boxed (value); } static gchar * <API key> (const GValue * value) { GstStructure *structure = g_value_get_boxed (value); return <API key> (<API key> (structure)); } static gboolean <API key> (GValue * dest, const gchar * s) { GstStructure *structure; if (*s != '"') { structure = <API key> (s, NULL); } else { gchar *str = gst_string_unwrap (s); if (G_UNLIKELY (!str)) return FALSE; structure = <API key> (str, NULL); g_free (str); } if (G_LIKELY (structure)) { g_value_take_boxed (dest, structure); return TRUE; } return FALSE; } static gint <API key> (const GValue * value1, const GValue * value2) { GstBuffer *buf1 = GST_BUFFER (<API key> (value1)); GstBuffer *buf2 = GST_BUFFER (<API key> (value2)); if (GST_BUFFER_SIZE (buf1) != GST_BUFFER_SIZE (buf2)) return GST_VALUE_UNORDERED; if (GST_BUFFER_SIZE (buf1) == 0) return GST_VALUE_EQUAL; g_assert (GST_BUFFER_DATA (buf1)); g_assert (GST_BUFFER_DATA (buf2)); if (memcmp (GST_BUFFER_DATA (buf1), GST_BUFFER_DATA (buf2), GST_BUFFER_SIZE (buf1)) == 0) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { guint8 *data; gint i; gint size; gchar *string; GstBuffer *buffer; buffer = <API key> (value); if (buffer == NULL) return NULL; data = GST_BUFFER_DATA (buffer); size = GST_BUFFER_SIZE (buffer); string = g_malloc (size * 2 + 1); for (i = 0; i < size; i++) { sprintf (string + i * 2, "%02x", data[i]); } string[size * 2] = 0; return string; } static gboolean <API key> (GValue * dest, const gchar * s) { GstBuffer *buffer; gint len; gchar ts[3]; guint8 *data; gint i; len = strlen (s); if (len & 1) goto wrong_length; buffer = <API key> (len / 2); data = GST_BUFFER_DATA (buffer); for (i = 0; i < len / 2; i++) { if (!isxdigit ((int) s[i * 2]) || !isxdigit ((int) s[i * 2 + 1])) goto wrong_char; ts[0] = s[i * 2 + 0]; ts[1] = s[i * 2 + 1]; ts[2] = 0; data[i] = (guint8) strtoul (ts, NULL, 16); } <API key> (dest, buffer); return TRUE; /* ERRORS */ wrong_length: { return FALSE; } wrong_char: { gst_buffer_unref (buffer); return FALSE; } } static gint <API key> (const GValue * value1, const GValue * value2) { if ((value1->data[0].v_int != 0) == (value2->data[0].v_int != 0)) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { if (value->data[0].v_int) { return g_strdup ("true"); } return g_strdup ("false"); } static gboolean <API key> (GValue * dest, const gchar * s) { gboolean ret = FALSE; if (g_ascii_strcasecmp (s, "true") == 0 || g_ascii_strcasecmp (s, "yes") == 0 || g_ascii_strcasecmp (s, "t") == 0 || strcmp (s, "1") == 0) { g_value_set_boolean (dest, TRUE); ret = TRUE; } else if (g_ascii_strcasecmp (s, "false") == 0 || g_ascii_strcasecmp (s, "no") == 0 || g_ascii_strcasecmp (s, "f") == 0 || strcmp (s, "0") == 0) { g_value_set_boolean (dest, FALSE); ret = TRUE; } return ret; } #define <API key>(_type,_macro) \ static gint \ gst_value_compare_ ## _type \ (const GValue * value1, const GValue * value2) \ { \ g ## _type val1 = g_value_get_ ## _type (value1); \ g ## _type val2 = g_value_get_ ## _type (value2); \ if (val1 > val2) \ return <API key>; \ if (val1 < val2) \ return GST_VALUE_LESS_THAN; \ return GST_VALUE_EQUAL; \ } \ \ static gchar * \ <API key> ## _type (const GValue * value) \ { \ GValue val = { 0, }; \ g_value_init (&val, G_TYPE_STRING); \ if (!g_value_transform (value, &val)) \ <API key> (); \ /* NO_COPY_MADNESS!!! */ \ return (char *) g_value_get_string (&val); \ } /* deserialize the given s into to as a gint64. * check if the result is actually storeable in the given size number of * bytes. */ static gboolean <API key> (gint64 * to, const gchar * s, gint64 min, gint64 max, gint size) { gboolean ret = FALSE; gchar *end; gint64 mask = -1; errno = 0; *to = g_ascii_strtoull (s, &end, 0); /* a range error is a definitive no-no */ if (errno == ERANGE) { return FALSE; } if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "little_endian") == 0) { *to = G_LITTLE_ENDIAN; ret = TRUE; } else if (g_ascii_strcasecmp (s, "big_endian") == 0) { *to = G_BIG_ENDIAN; ret = TRUE; } else if (g_ascii_strcasecmp (s, "byte_order") == 0) { *to = G_BYTE_ORDER; ret = TRUE; } else if (g_ascii_strcasecmp (s, "min") == 0) { *to = min; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { *to = max; ret = TRUE; } } if (ret) { /* by definition, a gint64 fits into a gint64; so ignore those */ if (size != sizeof (mask)) { if (*to >= 0) { /* for positive numbers, we create a mask of 1's outside of the range * and 0's inside the range. An and will thus keep only 1 bits * outside of the range */ mask <<= (size * 8); if ((mask & *to) != 0) { ret = FALSE; } } else { /* for negative numbers, we do a 2's complement version */ mask <<= ((size * 8) - 1); if ((mask & *to) != mask) { ret = FALSE; } } } } return ret; } #define <API key>(_type,_macro) \ <API key>(_type,_macro) \ \ static gboolean \ <API key> ## _type (GValue * dest, const gchar *s) \ { \ gint64 x; \ \ if (<API key> (&x, s, G_MIN ## _macro, \ G_MAX ## _macro, sizeof (g ## _type))) { \ g_value_set_ ## _type (dest, /*(g ## _type)*/ x); \ return TRUE; \ } else { \ return FALSE; \ } \ } #define <API key>(_type,_macro) \ <API key>(_type,_macro) \ \ static gboolean \ <API key> ## _type (GValue * dest, const gchar *s) \ { \ gint64 x; \ gchar *end; \ gboolean ret = FALSE; \ \ errno = 0; \ x = g_ascii_strtoull (s, &end, 0); \ /* a range error is a definitive no-no */ \ if (errno == ERANGE) { \ return FALSE; \ } \ /* the cast ensures the range check later on makes sense */ \ x = (g ## _type) x; \ if (*end == 0) { \ ret = TRUE; \ } else { \ if (g_ascii_strcasecmp (s, "little_endian") == 0) { \ x = G_LITTLE_ENDIAN; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "big_endian") == 0) { \ x = G_BIG_ENDIAN; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "byte_order") == 0) { \ x = G_BYTE_ORDER; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "min") == 0) { \ x = 0; \ ret = TRUE; \ } else if (g_ascii_strcasecmp (s, "max") == 0) { \ x = G_MAX ## _macro; \ ret = TRUE; \ } \ } \ if (ret) { \ if (x > G_MAX ## _macro) { \ ret = FALSE; \ } else { \ g_value_set_ ## _type (dest, x); \ } \ } \ return ret; \ } #define <API key>(_gtype, _type) \ G_STMT_START { \ static const GstValueTable gst_value = { \ _gtype, \ gst_value_compare_ ## _type, \ <API key> ## _type, \ <API key> ## _type, \ }; \ \ gst_value_register (&gst_value); \ } G_STMT_END <API key> (int, INT); <API key> (int64, INT64); <API key> (long, LONG); <API key> (uint, UINT); <API key> (uint64, UINT64); <API key> (ulong, ULONG); /* FIXME 0.11: remove this again, plugins shouldn't have uchar properties */ #ifndef G_MAXUCHAR #define G_MAXUCHAR 255 #endif <API key> (uchar, UCHAR); static gint <API key> (const GValue * value1, const GValue * value2) { if (value1->data[0].v_double > value2->data[0].v_double) return <API key>; if (value1->data[0].v_double < value2->data[0].v_double) return GST_VALUE_LESS_THAN; if (value1->data[0].v_double == value2->data[0].v_double) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { gchar d[<API key>]; g_ascii_dtostr (d, <API key>, value->data[0].v_double); return g_strdup (d); } static gboolean <API key> (GValue * dest, const gchar * s) { gdouble x; gboolean ret = FALSE; gchar *end; x = g_ascii_strtod (s, &end); if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "min") == 0) { x = -G_MAXDOUBLE; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { x = G_MAXDOUBLE; ret = TRUE; } } if (ret) { g_value_set_double (dest, x); } return ret; } static gint <API key> (const GValue * value1, const GValue * value2) { if (value1->data[0].v_float > value2->data[0].v_float) return <API key>; if (value1->data[0].v_float < value2->data[0].v_float) return GST_VALUE_LESS_THAN; if (value1->data[0].v_float == value2->data[0].v_float) return GST_VALUE_EQUAL; return GST_VALUE_UNORDERED; } static gchar * <API key> (const GValue * value) { gchar d[<API key>]; g_ascii_dtostr (d, <API key>, value->data[0].v_float); return g_strdup (d); } static gboolean <API key> (GValue * dest, const gchar * s) { gdouble x; gboolean ret = FALSE; gchar *end; x = g_ascii_strtod (s, &end); if (*end == 0) { ret = TRUE; } else { if (g_ascii_strcasecmp (s, "min") == 0) { x = -G_MAXFLOAT; ret = TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { x = G_MAXFLOAT; ret = TRUE; } } if (x > G_MAXFLOAT || x < -G_MAXFLOAT) ret = FALSE; if (ret) { g_value_set_float (dest, (float) x); } return ret; } static gint <API key> (const GValue * value1, const GValue * value2) { if (G_UNLIKELY (!value1->data[0].v_pointer || !value2->data[0].v_pointer)) { /* if only one is NULL, no match - otherwise both NULL == EQUAL */ if (value1->data[0].v_pointer != value2->data[0].v_pointer) return GST_VALUE_UNORDERED; } else { gint x = strcmp (value1->data[0].v_pointer, value2->data[0].v_pointer); if (x < 0) return GST_VALUE_LESS_THAN; if (x > 0) return <API key>; } return GST_VALUE_EQUAL; } static gint <API key> (const gchar * s) { gint len; gboolean wrap = FALSE; if (G_UNLIKELY (s == NULL)) return -1; /* Special case: the actual string NULL needs wrapping */ if (G_UNLIKELY (strcmp (s, "NULL") == 0)) return 4; len = 0; while (*s) { if (GST_ASCII_IS_STRING (*s)) { len++; } else if (*s < 0x20 || *s >= 0x7f) { wrap = TRUE; len += 4; } else { wrap = TRUE; len += 2; } s++; } /* Wrap the string if we found something that needs * wrapping, or the empty string (len == 0) */ return (wrap || len == 0) ? len : -1; } static gchar * <API key> (const gchar * s, gint len) { gchar *d, *e; e = d = g_malloc (len + 3); *e++ = '\"'; while (*s) { if (GST_ASCII_IS_STRING (*s)) { *e++ = *s++; } else if (*s < 0x20 || *s >= 0x7f) { *e++ = '\\'; *e++ = '0' + ((*(guchar *) s) >> 6); *e++ = '0' + (((*s) >> 3) & 0x7); *e++ = '0' + ((*s++) & 0x7); } else { *e++ = '\\'; *e++ = *s++; } } *e++ = '\"'; *e = 0; g_assert (e - d <= len + 3); return d; } /* Do string wrapping/escaping */ static gchar * gst_string_wrap (const gchar * s) { gint len = <API key> (s); if (G_LIKELY (len < 0)) return g_strdup (s); return <API key> (s, len); } /* Same as above, but take ownership of the string */ static gchar * <API key> (gchar * s) { gchar *out; gint len = <API key> (s); if (G_LIKELY (len < 0)) return s; out = <API key> (s, len); g_free (s); return out; } /* * This function takes a string delimited with double quotes (") * and unescapes any \xxx octal numbers. * * If sequences of \y are found where y is not in the range of * 0->3, y is copied unescaped. * * If \xyy is found where x is an octal number but y is not, an * error is encountered and NULL is returned. * * the input string must be \0 terminated. */ static gchar * gst_string_unwrap (const gchar * s) { gchar *ret; gchar *read, *write; /* NULL string returns NULL */ if (s == NULL) return NULL; /* strings not starting with " are invalid */ if (*s != '"') return NULL; /* make copy of original string to hold the result. This * string will always be smaller than the original */ ret = g_strdup (s); read = ret; write = ret; /* need to move to the next position as we parsed the " */ read++; while (*read) { if (GST_ASCII_IS_STRING (*read)) { /* normal chars are just copied */ *write++ = *read++; } else if (*read == '"') { /* quote marks end of string */ break; } else if (*read == '\\') { /* got an escape char, move to next position to read a tripplet * of octal numbers */ read++; /* is the next char a possible first octal number? */ if (*read >= '0' && *read <= '3') { /* parse other 2 numbers, if one of them is not in the range of * an octal number, we error. We also catch the case where a zero * byte is found here. */ if (read[1] < '0' || read[1] > '7' || read[2] < '0' || read[2] > '7') goto beach; /* now convert the octal number to a byte again. */ *write++ = ((read[0] - '0') << 6) + ((read[1] - '0') << 3) + (read[2] - '0'); read += 3; } else { /* if we run into a \0 here, we definately won't get a quote later */ if (*read == 0) goto beach; /* else copy \X sequence */ *write++ = *read++; } } else { /* weird character, error */ goto beach; } } /* if the string is not ending in " and zero terminated, we error */ if (*read != '"' || read[1] != '\0') goto beach; /* null terminate result string and return */ *write = '\0'; return ret; beach: g_free (ret); return NULL; } static gchar * <API key> (const GValue * value) { return gst_string_wrap (value->data[0].v_pointer); } static gboolean <API key> (GValue * dest, const gchar * s) { if (G_UNLIKELY (strcmp (s, "NULL") == 0)) { g_value_set_string (dest, NULL); return TRUE; } else if (G_LIKELY (*s != '"')) { if (!g_utf8_validate (s, -1, NULL)) return FALSE; g_value_set_string (dest, s); return TRUE; } else { gchar *str = gst_string_unwrap (s); if (G_UNLIKELY (!str)) return FALSE; g_value_take_string (dest, str); } return TRUE; } static gint <API key> (const GValue * value1, const GValue * value2) { GEnumValue *en1, *en2; GEnumClass *klass1 = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value1)); GEnumClass *klass2 = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value2)); <API key> (klass1, GST_VALUE_UNORDERED); <API key> (klass2, GST_VALUE_UNORDERED); en1 = g_enum_get_value (klass1, g_value_get_enum (value1)); en2 = g_enum_get_value (klass2, g_value_get_enum (value2)); g_type_class_unref (klass1); g_type_class_unref (klass2); <API key> (en1, GST_VALUE_UNORDERED); <API key> (en2, GST_VALUE_UNORDERED); if (en1->value < en2->value) return GST_VALUE_LESS_THAN; if (en1->value > en2->value) return <API key>; return GST_VALUE_EQUAL; } static gchar * <API key> (const GValue * value) { GEnumValue *en; GEnumClass *klass = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (value)); <API key> (klass, NULL); en = g_enum_get_value (klass, g_value_get_enum (value)); g_type_class_unref (klass); /* might be one of the custom formats registered later */ if (G_UNLIKELY (en == NULL && G_VALUE_TYPE (value) == GST_TYPE_FORMAT)) { const GstFormatDefinition *format_def; format_def = <API key> (g_value_get_enum (value)); <API key> (format_def != NULL, NULL); return g_strdup (format_def->description); } <API key> (en, NULL); return g_strdup (en->value_name); } static gint <API key> (const GstFormatDefinition * format_def, const gchar * s) { if (g_ascii_strcasecmp (s, format_def->nick) == 0) return 0; return g_ascii_strcasecmp (s, format_def->description); } static gboolean <API key> (GValue * dest, const gchar * s) { GEnumValue *en; gchar *endptr = NULL; GEnumClass *klass = (GEnumClass *) g_type_class_ref (G_VALUE_TYPE (dest)); <API key> (klass, FALSE); if (!(en = <API key> (klass, s))) { if (!(en = <API key> (klass, s))) { gint i = strtol (s, &endptr, 0); if (endptr && *endptr == '\0') { en = g_enum_get_value (klass, i); } } } g_type_class_unref (klass); /* might be one of the custom formats registered later */ if (G_UNLIKELY (en == NULL && G_VALUE_TYPE (dest) == GST_TYPE_FORMAT)) { const GstFormatDefinition *format_def; GstIterator *iter; iter = <API key> (); format_def = <API key> (iter, (GCompareFunc) <API key>, (gpointer) s); <API key> (format_def != NULL, FALSE); g_value_set_enum (dest, (gint) format_def->value); gst_iterator_free (iter); return TRUE; } <API key> (en, FALSE); g_value_set_enum (dest, en->value); return TRUE; } /* we just compare the value here */ static gint <API key> (const GValue * value1, const GValue * value2) { guint fl1, fl2; GFlagsClass *klass1 = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value1)); GFlagsClass *klass2 = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value2)); <API key> (klass1, GST_VALUE_UNORDERED); <API key> (klass2, GST_VALUE_UNORDERED); fl1 = g_value_get_flags (value1); fl2 = g_value_get_flags (value2); g_type_class_unref (klass1); g_type_class_unref (klass2); if (fl1 < fl2) return GST_VALUE_LESS_THAN; if (fl1 > fl2) return <API key>; return GST_VALUE_EQUAL; } /* the different flags are serialized separated with a + */ static gchar * <API key> (const GValue * value) { guint flags; GFlagsValue *fl; GFlagsClass *klass = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (value)); gchar *result, *tmp; gboolean first = TRUE; <API key> (klass, NULL); flags = g_value_get_flags (value); /* if no flags are set, try to serialize to the _NONE string */ if (!flags) { fl = <API key> (klass, flags); return g_strdup (fl->value_name); } /* some flags are set, so serialize one by one */ result = g_strdup (""); while (flags) { fl = <API key> (klass, flags); if (fl != NULL) { tmp = g_strconcat (result, (first ? "" : "+"), fl->value_name, NULL); g_free (result); result = tmp; first = FALSE; /* clear flag */ flags &= ~fl->value; } } g_type_class_unref (klass); return result; } static gboolean <API key> (GValue * dest, const gchar * s) { GFlagsValue *fl; gchar *endptr = NULL; GFlagsClass *klass = (GFlagsClass *) g_type_class_ref (G_VALUE_TYPE (dest)); gchar **split; guint flags; gint i; <API key> (klass, FALSE); /* split into parts delimited with + */ split = g_strsplit (s, "+", 0); flags = 0; i = 0; /* loop over each part */ while (split[i]) { if (!(fl = <API key> (klass, split[i]))) { if (!(fl = <API key> (klass, split[i]))) { gint val = strtol (split[i], &endptr, 0); /* just or numeric value */ if (endptr && *endptr == '\0') { flags |= val; } } } if (fl) { flags |= fl->value; } i++; } g_strfreev (split); g_type_class_unref (klass); g_value_set_flags (dest, flags); return TRUE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int <= src1->data[0].v_int && src2->data[1].v_int >= src1->data[0].v_int) { <API key> (dest, src2); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { gint min; gint max; min = MAX (src1->data[0].v_int, src2->data[0].v_int); max = MIN (src1->data[1].v_int, src2->data[1].v_int); if (min <= max) { g_value_init (dest, GST_TYPE_INT_RANGE); <API key> (dest, MIN (src1->data[0].v_int, src2->data[0].v_int), MAX (src1->data[1].v_int, src2->data[1].v_int)); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int <= src1->data[0].v_int && src2->data[1].v_int >= src1->data[0].v_int) { <API key> (dest, src1); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { gint min; gint max; min = MAX (src1->data[0].v_int, src2->data[0].v_int); max = MIN (src1->data[1].v_int, src2->data[1].v_int); if (min < max) { g_value_init (dest, GST_TYPE_INT_RANGE); <API key> (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_INT); g_value_set_int (dest, min); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_int64 <= src1->data[0].v_int64 && src2->data[1].v_int64 >= src1->data[0].v_int64) { <API key> (dest, src1); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { gint64 min; gint64 max; min = MAX (src1->data[0].v_int64, src2->data[0].v_int64); max = MIN (src1->data[1].v_int64, src2->data[1].v_int64); if (min < max) { g_value_init (dest, <API key>); <API key> (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_INT64); g_value_set_int64 (dest, min); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { if (src2->data[0].v_double <= src1->data[0].v_double && src2->data[1].v_double >= src1->data[0].v_double) { <API key> (dest, src1); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { gdouble min; gdouble max; min = MAX (src1->data[0].v_double, src2->data[0].v_double); max = MIN (src1->data[1].v_double, src2->data[1].v_double); if (min < max) { g_value_init (dest, <API key>); <API key> (dest, min, max); return TRUE; } if (min == max) { g_value_init (dest, G_TYPE_DOUBLE); g_value_set_int (dest, (int) min); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * value1, const GValue * value2) { guint i, size; GValue intersection = { 0, }; gboolean ret = FALSE; size = VALUE_LIST_SIZE (value1); for (i = 0; i < size; i++) { const GValue *cur = <API key> (value1, i); if (gst_value_intersect (&intersection, cur, value2)) { /* append value */ if (!ret) { <API key> (dest, &intersection); ret = TRUE; } else if (<API key> (dest)) { <API key> (dest, &intersection); } else { GValue temp = { 0, }; <API key> (&temp, dest); g_value_unset (dest); <API key> (dest, &temp, &intersection); g_value_unset (&temp); } g_value_unset (&intersection); } } return ret; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { guint size; guint n; GValue val = { 0 }; /* only works on similar-sized arrays */ size = <API key> (src1); if (size != <API key> (src2)) return FALSE; g_value_init (dest, GST_TYPE_ARRAY); for (n = 0; n < size; n++) { if (!gst_value_intersect (&val, <API key> (src1, n), <API key> (src2, n))) { g_value_unset (dest); return FALSE; } <API key> (dest, &val); g_value_unset (&val); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { gint res1, res2; GValue *vals; GstValueCompareFunc compare; vals = src2->data[0].v_pointer; if (vals == NULL) return FALSE; if ((compare = <API key> (src1))) { res1 = <API key> (&vals[0], src1, compare); res2 = <API key> (&vals[1], src1, compare); if ((res1 == GST_VALUE_EQUAL || res1 == GST_VALUE_LESS_THAN) && (res2 == GST_VALUE_EQUAL || res2 == <API key>)) { <API key> (dest, src1); return TRUE; } } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * src1, const GValue * src2) { GValue *min; GValue *max; gint res; GValue *vals1, *vals2; GstValueCompareFunc compare; vals1 = src1->data[0].v_pointer; vals2 = src2->data[0].v_pointer; <API key> (vals1 != NULL && vals2 != NULL, FALSE); if ((compare = <API key> (&vals1[0]))) { /* min = MAX (src1.start, src2.start) */ res = <API key> (&vals1[0], &vals2[0], compare); <API key> (res != GST_VALUE_UNORDERED, FALSE); if (res == GST_VALUE_LESS_THAN) min = &vals2[0]; /* Take the max of the 2 */ else min = &vals1[0]; /* max = MIN (src1.end, src2.end) */ res = <API key> (&vals1[1], &vals2[1], compare); <API key> (res != GST_VALUE_UNORDERED, FALSE); if (res == <API key>) max = &vals2[1]; /* Take the min of the 2 */ else max = &vals1[1]; res = <API key> (min, max, compare); <API key> (res != GST_VALUE_UNORDERED, FALSE); if (res == GST_VALUE_LESS_THAN) { g_value_init (dest, <API key>); vals1 = dest->data[0].v_pointer; g_value_copy (min, &vals1[0]); g_value_copy (max, &vals1[1]); return TRUE; } if (res == GST_VALUE_EQUAL) { <API key> (dest, min); return TRUE; } } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min = <API key> (subtrahend); gint max = <API key> (subtrahend); gint val = g_value_get_int (minuend); /* subtracting a range from an int only works if the int is not in the * range */ if (val < min || val > max) { /* and the result is the int */ <API key> (dest, minuend); return TRUE; } return FALSE; } /* creates a new int range based on input values. */ static gboolean <API key> (GValue * dest, gint min1, gint max1, gint min2, gint max2) { GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 <= max1 && min2 <= max2) { pv1 = &v1; pv2 = &v2; } else if (min1 <= max1) { pv1 = dest; pv2 = NULL; } else if (min2 <= max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, GST_TYPE_INT_RANGE); <API key> (pv1, min1, max1); } else if (min1 == max1) { g_value_init (pv1, G_TYPE_INT); g_value_set_int (pv1, min1); } if (min2 < max2) { g_value_init (pv2, GST_TYPE_INT_RANGE); <API key> (pv2, min2, max2); } else if (min2 == max2) { g_value_init (pv2, G_TYPE_INT); g_value_set_int (pv2, min2); } if (min1 <= max1 && min2 <= max2) { <API key> (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min = <API key> (minuend); gint max = <API key> (minuend); gint val = g_value_get_int (subtrahend); <API key> (min < max, FALSE); /* value is outside of the range, return range unchanged */ if (val < min || val > max) { <API key> (dest, minuend); return TRUE; } else { /* max must be MAXINT too as val <= max */ if (val == G_MAXINT) { max val } /* min must be MININT too as val >= max */ if (val == G_MININT) { min++; val++; } <API key> (dest, min, val - 1, val + 1, max); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint min1 = <API key> (minuend); gint max1 = <API key> (minuend); gint min2 = <API key> (subtrahend); gint max2 = <API key> (subtrahend); if (max2 == G_MAXINT && min2 == G_MININT) { return FALSE; } else if (max2 == G_MAXINT) { return <API key> (dest, min1, MIN (min2 - 1, max1), 1, 0); } else if (min2 == G_MININT) { return <API key> (dest, MAX (max2 + 1, min1), max1, 1, 0); } else { return <API key> (dest, min1, MIN (min2 - 1, max1), MAX (max2 + 1, min1), max1); } } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min = <API key> (subtrahend); gint64 max = <API key> (subtrahend); gint64 val = g_value_get_int64 (minuend); /* subtracting a range from an int64 only works if the int64 is not in the * range */ if (val < min || val > max) { /* and the result is the int64 */ <API key> (dest, minuend); return TRUE; } return FALSE; } /* creates a new int64 range based on input values. */ static gboolean <API key> (GValue * dest, gint64 min1, gint64 max1, gint64 min2, gint64 max2) { GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 <= max1 && min2 <= max2) { pv1 = &v1; pv2 = &v2; } else if (min1 <= max1) { pv1 = dest; pv2 = NULL; } else if (min2 <= max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, <API key>); <API key> (pv1, min1, max1); } else if (min1 == max1) { g_value_init (pv1, G_TYPE_INT64); g_value_set_int64 (pv1, min1); } if (min2 < max2) { g_value_init (pv2, <API key>); <API key> (pv2, min2, max2); } else if (min2 == max2) { g_value_init (pv2, G_TYPE_INT64); g_value_set_int64 (pv2, min2); } if (min1 <= max1 && min2 <= max2) { <API key> (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min = <API key> (minuend); gint64 max = <API key> (minuend); gint64 val = g_value_get_int64 (subtrahend); <API key> (min < max, FALSE); /* value is outside of the range, return range unchanged */ if (val < min || val > max) { <API key> (dest, minuend); return TRUE; } else { /* max must be MAXINT64 too as val <= max */ if (val == G_MAXINT64) { max val } /* min must be MININT64 too as val >= max */ if (val == G_MININT64) { min++; val++; } <API key> (dest, min, val - 1, val + 1, max); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint64 min1 = <API key> (minuend); gint64 max1 = <API key> (minuend); gint64 min2 = <API key> (subtrahend); gint64 max2 = <API key> (subtrahend); if (max2 == G_MAXINT64 && min2 == G_MININT64) { return FALSE; } else if (max2 == G_MAXINT64) { return <API key> (dest, min1, MIN (min2 - 1, max1), 1, 0); } else if (min2 == G_MININT64) { return <API key> (dest, MAX (max2 + 1, min1), max1, 1, 0); } else { return <API key> (dest, min1, MIN (min2 - 1, max1), MAX (max2 + 1, min1), max1); } } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gdouble min = <API key> (subtrahend); gdouble max = <API key> (subtrahend); gdouble val = g_value_get_double (minuend); if (val < min || val > max) { <API key> (dest, minuend); return TRUE; } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we cannot create a hole in * a double range. We return the original range */ <API key> (dest, minuend); return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we have to approximate */ /* done like with ints */ gdouble min1 = <API key> (minuend); gdouble max2 = <API key> (minuend); gdouble max1 = MIN (<API key> (subtrahend), max2); gdouble min2 = MAX (<API key> (subtrahend), min1); GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ if (min1 < max1 && min2 < max2) { pv1 = &v1; pv2 = &v2; } else if (min1 < max1) { pv1 = dest; pv2 = NULL; } else if (min2 < max2) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (min1 < max1) { g_value_init (pv1, <API key>); <API key> (pv1, min1, max1); } if (min2 < max2) { g_value_init (pv2, <API key>); <API key> (pv2, min2, max2); } if (min1 < max1 && min2 < max2) { <API key> (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { guint i, size; GValue subtraction = { 0, }; gboolean ret = FALSE; GType ltype; ltype = <API key> (); size = VALUE_LIST_SIZE (minuend); for (i = 0; i < size; i++) { const GValue *cur = <API key> (minuend, i); if (gst_value_subtract (&subtraction, cur, subtrahend)) { if (!ret) { <API key> (dest, &subtraction); ret = TRUE; } else if (G_VALUE_HOLDS (dest, ltype) && !G_VALUE_HOLDS (&subtraction, ltype)) { <API key> (dest, &subtraction); } else { GValue temp = { 0, }; <API key> (&temp, dest); g_value_unset (dest); <API key> (dest, &temp, &subtraction); g_value_unset (&temp); } g_value_unset (&subtraction); } } return ret; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { guint i, size; GValue data[2] = { {0,}, {0,} }; GValue *subtraction = &data[0], *result = &data[1]; <API key> (result, minuend); size = VALUE_LIST_SIZE (subtrahend); for (i = 0; i < size; i++) { const GValue *cur = <API key> (subtrahend, i); if (gst_value_subtract (subtraction, result, cur)) { GValue *temp = result; result = subtraction; subtraction = temp; g_value_unset (subtraction); } else { g_value_unset (result); return FALSE; } } <API key> (dest, result); g_value_unset (result); return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { const GValue *min = <API key> (subtrahend); const GValue *max = <API key> (subtrahend); GstValueCompareFunc compare; if ((compare = <API key> (minuend))) { /* subtracting a range from an fraction only works if the fraction * is not in the range */ if (<API key> (minuend, min, compare) == GST_VALUE_LESS_THAN || <API key> (minuend, max, compare) == <API key>) { /* and the result is the value */ <API key> (dest, minuend); return TRUE; } } return FALSE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we cannot create a hole in * a range. We return the original range */ <API key> (dest, minuend); return TRUE; } static gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { /* since we don't have open ranges, we have to approximate */ /* done like with ints and doubles. Creates a list of 2 fraction ranges */ const GValue *min1 = <API key> (minuend); const GValue *max2 = <API key> (minuend); const GValue *max1 = <API key> (subtrahend); const GValue *min2 = <API key> (subtrahend); gint cmp1, cmp2; GValue v1 = { 0, }; GValue v2 = { 0, }; GValue *pv1, *pv2; /* yeah, hungarian! */ GstValueCompareFunc compare; <API key> (min1 != NULL && max1 != NULL, FALSE); <API key> (min2 != NULL && max2 != NULL, FALSE); compare = <API key> (min1); <API key> (compare, FALSE); cmp1 = <API key> (max2, max1, compare); <API key> (cmp1 != GST_VALUE_UNORDERED, FALSE); if (cmp1 == GST_VALUE_LESS_THAN) max1 = max2; cmp1 = <API key> (min1, min2, compare); <API key> (cmp1 != GST_VALUE_UNORDERED, FALSE); if (cmp1 == <API key>) min2 = min1; cmp1 = <API key> (min1, max1, compare); cmp2 = <API key> (min2, max2, compare); if (cmp1 == GST_VALUE_LESS_THAN && cmp2 == GST_VALUE_LESS_THAN) { pv1 = &v1; pv2 = &v2; } else if (cmp1 == GST_VALUE_LESS_THAN) { pv1 = dest; pv2 = NULL; } else if (cmp2 == GST_VALUE_LESS_THAN) { pv1 = NULL; pv2 = dest; } else { return FALSE; } if (cmp1 == GST_VALUE_LESS_THAN) { g_value_init (pv1, <API key>); <API key> (pv1, min1, max1); } if (cmp2 == GST_VALUE_LESS_THAN) { g_value_init (pv2, <API key>); <API key> (pv2, min2, max2); } if (cmp1 == GST_VALUE_LESS_THAN && cmp2 == GST_VALUE_LESS_THAN) { <API key> (dest, pv1, pv2); g_value_unset (pv1); g_value_unset (pv2); } return TRUE; } /* * <API key>: * @value1: a value to get the compare function for * * Determines the compare function to be used with values of the same type as * @value1. The function can be given to <API key>(). * * Returns: A #GstValueCompareFunc value */ static GstValueCompareFunc <API key> (const GValue * value1) { GstValueTable *table, *best = NULL; guint i; GType type1; type1 = G_VALUE_TYPE (value1); /* this is a fast check */ best = <API key> (type1); /* slower checks */ if (G_UNLIKELY (!best || !best->compare)) { guint len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->compare && g_type_is_a (type1, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->compare; return NULL; } /** * <API key>: * @value1: a value to compare * @value2: another value to compare * * Determines if @value1 and @value2 can be compared. * * Returns: TRUE if the values can be compared */ gboolean <API key> (const GValue * value1, const GValue * value2) { <API key> (G_IS_VALUE (value1), FALSE); <API key> (G_IS_VALUE (value2), FALSE); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return FALSE; return <API key> (value1) != NULL; } /** * gst_value_compare: * @value1: a value to compare * @value2: another value to compare * * Compares @value1 and @value2. If @value1 and @value2 cannot be * compared, the function returns GST_VALUE_UNORDERED. Otherwise, * if @value1 is greater than @value2, <API key> is returned. * If @value1 is less than @value2, GST_VALUE_LESS_THAN is returned. * If the values are equal, GST_VALUE_EQUAL is returned. * * Returns: comparison result */ gint gst_value_compare (const GValue * value1, const GValue * value2) { GstValueCompareFunc compare; <API key> (G_IS_VALUE (value1), GST_VALUE_LESS_THAN); <API key> (G_IS_VALUE (value2), <API key>); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return GST_VALUE_UNORDERED; compare = <API key> (value1); if (compare) { return compare (value1, value2); } g_critical ("unable to compare values of type %s\n", g_type_name (G_VALUE_TYPE (value1))); return GST_VALUE_UNORDERED; } /* * <API key>: * @value1: a value to compare * @value2: another value to compare * @compare: compare function * * Compares @value1 and @value2 using the @compare function. Works like * gst_value_compare() but allows to save time determining the compare function * a multiple times. * * Returns: comparison result */ static gint <API key> (const GValue * value1, const GValue * value2, GstValueCompareFunc compare) { g_assert (compare); if (G_VALUE_TYPE (value1) != G_VALUE_TYPE (value2)) return GST_VALUE_UNORDERED; return compare (value1, value2); } /* union */ /** * gst_value_can_union: * @value1: a value to union * @value2: another value to union * * Determines if @value1 and @value2 can be non-trivially unioned. * Any two values can be trivially unioned by adding both of them * to a GstValueList. However, certain types have the possibility * to be unioned in a simpler way. For example, an integer range * and an integer can be unioned if the integer is a subset of the * integer range. If there is the possibility that two values can * be unioned, this function returns TRUE. * * Returns: TRUE if there is a function allowing the two values to * be unioned. */ gboolean gst_value_can_union (const GValue * value1, const GValue * value2) { GstValueUnionInfo *union_info; guint i, len; <API key> (G_IS_VALUE (value1), FALSE); <API key> (G_IS_VALUE (value2), FALSE); len = <API key>->len; for (i = 0; i < len; i++) { union_info = &g_array_index (<API key>, GstValueUnionInfo, i); if (union_info->type1 == G_VALUE_TYPE (value1) && union_info->type2 == G_VALUE_TYPE (value2)) return TRUE; if (union_info->type1 == G_VALUE_TYPE (value2) && union_info->type2 == G_VALUE_TYPE (value1)) return TRUE; } return FALSE; } /** * gst_value_union: * @dest: (out caller-allocates): the destination value * @value1: a value to union * @value2: another value to union * * Creates a GValue corresponding to the union of @value1 and @value2. * * Returns: always returns %TRUE */ /* FIXME: change return type to 'void'? */ gboolean gst_value_union (GValue * dest, const GValue * value1, const GValue * value2) { GstValueUnionInfo *union_info; guint i, len; <API key> (dest != NULL, FALSE); <API key> (G_IS_VALUE (value1), FALSE); <API key> (G_IS_VALUE (value2), FALSE); len = <API key>->len; for (i = 0; i < len; i++) { union_info = &g_array_index (<API key>, GstValueUnionInfo, i); if (union_info->type1 == G_VALUE_TYPE (value1) && union_info->type2 == G_VALUE_TYPE (value2)) { if (union_info->func (dest, value1, value2)) { return TRUE; } } if (union_info->type1 == G_VALUE_TYPE (value2) && union_info->type2 == G_VALUE_TYPE (value1)) { if (union_info->func (dest, value2, value1)) { return TRUE; } } } <API key> (dest, value1, value2); return TRUE; } /** * <API key>: * @type1: a type to union * @type2: another type to union * @func: a function that implments creating a union between the two types * * Registers a union function that can create a union between #GValue items * of the type @type1 and @type2. * * Union functions should be registered at startup before any pipelines are * started, as <API key>() is not thread-safe and cannot * be used at the same time as gst_value_union() or gst_value_can_union(). */ void <API key> (GType type1, GType type2, GstValueUnionFunc func) { GstValueUnionInfo union_info; union_info.type1 = type1; union_info.type2 = type2; union_info.func = func; g_array_append_val (<API key>, union_info); } /* intersection */ /** * <API key>: * @value1: a value to intersect * @value2: another value to intersect * * Determines if intersecting two values will produce a valid result. * Two values will produce a valid intersection if they have the same * type, or if there is a method (registered by * <API key>()) to calculate the intersection. * * Returns: TRUE if the values can intersect */ gboolean <API key> (const GValue * value1, const GValue * value2) { <API key> *intersect_info; guint i, len; GType ltype, type1, type2; <API key> (G_IS_VALUE (value1), FALSE); <API key> (G_IS_VALUE (value2), FALSE); ltype = <API key> (); /* special cases */ if (G_VALUE_HOLDS (value1, ltype) || G_VALUE_HOLDS (value2, ltype)) return TRUE; type1 = G_VALUE_TYPE (value1); type2 = G_VALUE_TYPE (value2); /* practically all GstValue types have a compare function (_can_compare=TRUE) * GstStructure and GstCaps have npot, but are intersectable */ if (type1 == type2) return TRUE; /* check registered intersect functions */ len = <API key>->len; for (i = 0; i < len; i++) { intersect_info = &g_array_index (<API key>, <API key>, i); if ((intersect_info->type1 == type1 && intersect_info->type2 == type2) || (intersect_info->type1 == type2 && intersect_info->type2 == type1)) return TRUE; } return <API key> (value1, value2); } /** * gst_value_intersect: * @dest: (out caller-allocates): a uninitialized #GValue that will hold the calculated * intersection value * @value1: a value to intersect * @value2: another value to intersect * * Calculates the intersection of two values. If the values have * a non-empty intersection, the value representing the intersection * is placed in @dest. If the intersection is non-empty, @dest is * not modified. * * Returns: TRUE if the intersection is non-empty */ gboolean gst_value_intersect (GValue * dest, const GValue * value1, const GValue * value2) { <API key> *intersect_info; guint i, len; GType ltype, type1, type2; <API key> (dest != NULL, FALSE); <API key> (G_IS_VALUE (value1), FALSE); <API key> (G_IS_VALUE (value2), FALSE); ltype = <API key> (); /* special cases first */ if (G_VALUE_HOLDS (value1, ltype)) return <API key> (dest, value1, value2); if (G_VALUE_HOLDS (value2, ltype)) return <API key> (dest, value2, value1); if (gst_value_compare (value1, value2) == GST_VALUE_EQUAL) { <API key> (dest, value1); return TRUE; } type1 = G_VALUE_TYPE (value1); type2 = G_VALUE_TYPE (value2); len = <API key>->len; for (i = 0; i < len; i++) { intersect_info = &g_array_index (<API key>, <API key>, i); if (intersect_info->type1 == type1 && intersect_info->type2 == type2) { return intersect_info->func (dest, value1, value2); } if (intersect_info->type1 == type2 && intersect_info->type2 == type1) { return intersect_info->func (dest, value2, value1); } } return FALSE; } /** * <API key>: * @type1: the first type to intersect * @type2: the second type to intersect * @func: the intersection function * * Registers a function that is called to calculate the intersection * of the values having the types @type1 and @type2. * * Intersect functions should be registered at startup before any pipelines are * started, as <API key>() is not thread-safe and * cannot be used at the same time as gst_value_intersect() or * <API key>(). */ void <API key> (GType type1, GType type2, <API key> func) { <API key> intersect_info; intersect_info.type1 = type1; intersect_info.type2 = type2; intersect_info.func = func; g_array_append_val (<API key>, intersect_info); } /* subtraction */ /** * gst_value_subtract: * @dest: (out caller-allocates): the destination value for the result if the * subtraction is not empty * @minuend: the value to subtract from * @subtrahend: the value to subtract * * Subtracts @subtrahend from @minuend and stores the result in @dest. * Note that this means subtraction as in sets, not as in mathematics. * * Returns: %TRUE if the subtraction is not empty */ gboolean gst_value_subtract (GValue * dest, const GValue * minuend, const GValue * subtrahend) { <API key> *info; guint i, len; GType ltype, mtype, stype; <API key> (dest != NULL, FALSE); <API key> (G_IS_VALUE (minuend), FALSE); <API key> (G_IS_VALUE (subtrahend), FALSE); ltype = <API key> (); /* special cases first */ if (G_VALUE_HOLDS (minuend, ltype)) return <API key> (dest, minuend, subtrahend); if (G_VALUE_HOLDS (subtrahend, ltype)) return <API key> (dest, minuend, subtrahend); mtype = G_VALUE_TYPE (minuend); stype = G_VALUE_TYPE (subtrahend); len = <API key>->len; for (i = 0; i < len; i++) { info = &g_array_index (<API key>, <API key>, i); if (info->minuend == mtype && info->subtrahend == stype) { return info->func (dest, minuend, subtrahend); } } if (gst_value_compare (minuend, subtrahend) != GST_VALUE_EQUAL) { <API key> (dest, minuend); return TRUE; } return FALSE; } #if 0 gboolean gst_value_subtract (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gboolean ret = gst_value_subtract2 (dest, minuend, subtrahend); g_printerr ("\"%s\" - \"%s\" = \"%s\"\n", gst_value_serialize (minuend), gst_value_serialize (subtrahend), ret ? gst_value_serialize (dest) : " return ret; } #endif /** * <API key>: * @minuend: the value to subtract from * @subtrahend: the value to subtract * * Checks if it's possible to subtract @subtrahend from @minuend. * * Returns: TRUE if a subtraction is possible */ gboolean <API key> (const GValue * minuend, const GValue * subtrahend) { <API key> *info; guint i, len; GType ltype, mtype, stype; <API key> (G_IS_VALUE (minuend), FALSE); <API key> (G_IS_VALUE (subtrahend), FALSE); ltype = <API key> (); /* special cases */ if (G_VALUE_HOLDS (minuend, ltype) || G_VALUE_HOLDS (subtrahend, ltype)) return TRUE; mtype = G_VALUE_TYPE (minuend); stype = G_VALUE_TYPE (subtrahend); len = <API key>->len; for (i = 0; i < len; i++) { info = &g_array_index (<API key>, <API key>, i); if (info->minuend == mtype && info->subtrahend == stype) return TRUE; } return <API key> (minuend, subtrahend); } /** * <API key>: * @minuend_type: type of the minuend * @subtrahend_type: type of the subtrahend * @func: function to use * * Registers @func as a function capable of subtracting the values of * @subtrahend_type from values of @minuend_type. * * Subtract functions should be registered at startup before any pipelines are * started, as <API key>() is not thread-safe and * cannot be used at the same time as gst_value_subtract(). */ void <API key> (GType minuend_type, GType subtrahend_type, <API key> func) { <API key> info; /* one type must be unfixed, other subtractions can be done as comparisons */ g_return_if_fail (!gst_type_is_fixed (minuend_type) || !gst_type_is_fixed (subtrahend_type)); info.minuend = minuend_type; info.subtrahend = subtrahend_type; info.func = func; g_array_append_val (<API key>, info); } /** * gst_value_register: * @table: structure containing functions to register * * Registers functions to perform calculations on #GValue items of a given * type. Each type can only be added once. */ void gst_value_register (const GstValueTable * table) { GstValueTable *found; g_return_if_fail (table != NULL); g_array_append_val (gst_value_table, *table); found = <API key> (table->type); if (found) g_warning ("adding type %s multiple times", g_type_name (table->type)); /* FIXME: we're not really doing the const justice, we assume the table is * static */ <API key> (table->type, table); } /** * <API key>: * @dest: (out caller-allocates): the target value * @src: the source value * * Initialises the target value to be of the same type as source and then copies * the contents from source to target. */ void <API key> (GValue * dest, const GValue * src) { g_return_if_fail (G_IS_VALUE (src)); g_return_if_fail (dest != NULL); g_value_init (dest, G_VALUE_TYPE (src)); g_value_copy (src, dest); } /** * gst_value_serialize: * @value: a #GValue to serialize * * tries to transform the given @value into a string representation that allows * getting back this string later on using <API key>(). * * Free-function: g_free * * Returns: (transfer full): the serialization for @value or NULL if none exists */ gchar * gst_value_serialize (const GValue * value) { guint i, len; GValue s_val = { 0 }; GstValueTable *table, *best; gchar *s; GType type; <API key> (G_IS_VALUE (value), NULL); type = G_VALUE_TYPE (value); best = <API key> (type); if (G_UNLIKELY (!best || !best->serialize)) { len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->serialize && g_type_is_a (type, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->serialize (value); g_value_init (&s_val, G_TYPE_STRING); if (g_value_transform (value, &s_val)) { s = gst_string_wrap (g_value_get_string (&s_val)); } else { s = NULL; } g_value_unset (&s_val); return s; } /** * <API key>: * @dest: (out caller-allocates): #GValue to fill with contents of * deserialization * @src: string to deserialize * * Tries to deserialize a string into the type specified by the given GValue. * If the operation succeeds, TRUE is returned, FALSE otherwise. * * Returns: TRUE on success */ gboolean <API key> (GValue * dest, const gchar * src) { GstValueTable *table, *best; guint i, len; GType type; <API key> (src != NULL, FALSE); <API key> (G_IS_VALUE (dest), FALSE); type = G_VALUE_TYPE (dest); best = <API key> (type); if (G_UNLIKELY (!best || !best->deserialize)) { len = gst_value_table->len; best = NULL; for (i = 0; i < len; i++) { table = &g_array_index (gst_value_table, GstValueTable, i); if (table->deserialize && g_type_is_a (type, table->type)) { if (!best || g_type_is_a (table->type, best->type)) best = table; } } } if (G_LIKELY (best)) return best->deserialize (dest, src); return FALSE; } /** * gst_value_is_fixed: * @value: the #GValue to check * * Tests if the given GValue, if available in a GstStructure (or any other * container) contains a "fixed" (which means: one value) or an "unfixed" * (which means: multiple possible values, such as data lists or data * ranges) value. * * Returns: true if the value is "fixed". */ gboolean gst_value_is_fixed (const GValue * value) { GType type; <API key> (G_IS_VALUE (value), FALSE); type = G_VALUE_TYPE (value); /* the most common types are just basic plain glib types */ if (type <= <API key> (<API key>)) { return TRUE; } if (type == GST_TYPE_ARRAY) { gint size, n; const GValue *kid; /* check recursively */ size = <API key> (value); for (n = 0; n < size; n++) { kid = <API key> (value, n); if (!gst_value_is_fixed (kid)) return FALSE; } return TRUE; } return gst_type_is_fixed (type); } /* helper functions */ static void <API key> (GValue * value) { value->data[0].v_int = 0; value->data[1].v_int = 1; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_int = src_value->data[0].v_int; dest_value->data[1].v_int = src_value->data[1].v_int; } static gchar * <API key> (GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { if (n_collect_values != 2) return g_strdup_printf ("not enough value locations for `%s' passed", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int == 0) return g_strdup_printf ("passed '0' as denominator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[0].v_int < -G_MAXINT) return g_strdup_printf ("passed value smaller than -G_MAXINT as numerator for `%s'", G_VALUE_TYPE_NAME (value)); if (collect_values[1].v_int < -G_MAXINT) return g_strdup_printf ("passed value smaller than -G_MAXINT as denominator for `%s'", G_VALUE_TYPE_NAME (value)); <API key> (value, collect_values[0].v_int, collect_values[1].v_int); return NULL; } static gchar * <API key> (const GValue * value, guint n_collect_values, GTypeCValue * collect_values, guint collect_flags) { gint *numerator = collect_values[0].v_pointer; gint *denominator = collect_values[1].v_pointer; if (!numerator) return g_strdup_printf ("numerator for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); if (!denominator) return g_strdup_printf ("denominator for `%s' passed as NULL", G_VALUE_TYPE_NAME (value)); *numerator = value->data[0].v_int; *denominator = value->data[1].v_int; return NULL; } /** * <API key>: * @value: a GValue initialized to #GST_TYPE_FRACTION * @numerator: the numerator of the fraction * @denominator: the denominator of the fraction * * Sets @value to the fraction specified by @numerator over @denominator. * The fraction gets reduced to the smallest numerator and denominator, * and if necessary the sign is moved to the numerator. */ void <API key> (GValue * value, gint numerator, gint denominator) { gint gcd = 0; g_return_if_fail (<API key> (value)); g_return_if_fail (denominator != 0); g_return_if_fail (denominator >= -G_MAXINT); g_return_if_fail (numerator >= -G_MAXINT); /* normalize sign */ if (denominator < 0) { numerator = -numerator; denominator = -denominator; } /* check for reduction */ gcd = <API key> (numerator, denominator); if (gcd) { numerator /= gcd; denominator /= gcd; } g_assert (denominator > 0); value->data[0].v_int = numerator; value->data[1].v_int = denominator; } /** * <API key>: * @value: a GValue initialized to #GST_TYPE_FRACTION * * Gets the numerator of the fraction specified by @value. * * Returns: the numerator of the fraction. */ gint <API key> (const GValue * value) { <API key> (<API key> (value), 0); return value->data[0].v_int; } /** * <API key>: * @value: a GValue initialized to #GST_TYPE_FRACTION * * Gets the denominator of the fraction specified by @value. * * Returns: the denominator of the fraction. */ gint <API key> (const GValue * value) { <API key> (<API key> (value), 1); return value->data[1].v_int; } /** * <API key>: * @product: a GValue initialized to #GST_TYPE_FRACTION * @factor1: a GValue initialized to #GST_TYPE_FRACTION * @factor2: a GValue initialized to #GST_TYPE_FRACTION * * Multiplies the two #GValue items containing a #GST_TYPE_FRACTION and sets * @product to the product of the two fractions. * * Returns: FALSE in case of an error (like integer overflow), TRUE otherwise. */ gboolean <API key> (GValue * product, const GValue * factor1, const GValue * factor2) { gint n1, n2, d1, d2; gint res_n, res_d; <API key> (product != NULL, FALSE); <API key> (<API key> (factor1), FALSE); <API key> (<API key> (factor2), FALSE); n1 = factor1->data[0].v_int; n2 = factor2->data[0].v_int; d1 = factor1->data[1].v_int; d2 = factor2->data[1].v_int; if (!<API key> (n1, d1, n2, d2, &res_n, &res_d)) return FALSE; <API key> (product, res_n, res_d); return TRUE; } /** * <API key>: * @dest: a GValue initialized to #GST_TYPE_FRACTION * @minuend: a GValue initialized to #GST_TYPE_FRACTION * @subtrahend: a GValue initialized to #GST_TYPE_FRACTION * * Subtracts the @subtrahend from the @minuend and sets @dest to the result. * * Returns: FALSE in case of an error (like integer overflow), TRUE otherwise. */ gboolean <API key> (GValue * dest, const GValue * minuend, const GValue * subtrahend) { gint n1, n2, d1, d2; gint res_n, res_d; <API key> (dest != NULL, FALSE); <API key> (<API key> (minuend), FALSE); <API key> (<API key> (subtrahend), FALSE); n1 = minuend->data[0].v_int; n2 = subtrahend->data[0].v_int; d1 = minuend->data[1].v_int; d2 = subtrahend->data[1].v_int; if (!<API key> (n1, d1, -n2, d2, &res_n, &res_d)) return FALSE; <API key> (dest, res_n, res_d); return TRUE; } static gchar * <API key> (const GValue * value) { gint32 numerator = value->data[0].v_int; gint32 denominator = value->data[1].v_int; gboolean positive = TRUE; /* get the sign and make components absolute */ if (numerator < 0) { numerator = -numerator; positive = !positive; } if (denominator < 0) { denominator = -denominator; positive = !positive; } return g_strdup_printf ("%s%d/%d", positive ? "" : "-", numerator, denominator); } static gboolean <API key> (GValue * dest, const gchar * s) { gint num, den; gint num_chars; if (G_UNLIKELY (s == NULL)) return FALSE; if (G_UNLIKELY (dest == NULL || !<API key> (dest))) return FALSE; if (sscanf (s, "%d/%d%n", &num, &den, &num_chars) >= 2) { if (s[num_chars] != 0) return FALSE; if (den == 0) return FALSE; <API key> (dest, num, den); return TRUE; } else if (g_ascii_strcasecmp (s, "1/max") == 0) { <API key> (dest, 1, G_MAXINT); return TRUE; } else if (sscanf (s, "%d%n", &num, &num_chars) >= 1) { if (s[num_chars] != 0) return FALSE; <API key> (dest, num, 1); return TRUE; } else if (g_ascii_strcasecmp (s, "min") == 0) { <API key> (dest, -G_MAXINT, 1); return TRUE; } else if (g_ascii_strcasecmp (s, "max") == 0) { <API key> (dest, G_MAXINT, 1); return TRUE; } return FALSE; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = <API key> (src_value); } static void <API key> (const GValue * src_value, GValue * dest_value) { if (!<API key> (dest_value, src_value->data[0].v_pointer)) /* If the deserialize fails, ensure we leave the fraction in a * valid, if incorrect, state */ <API key> (dest_value, 0, 1); } static void <API key> (const GValue * src_value, GValue * dest_value) { gdouble src = g_value_get_double (src_value); gint n, d; <API key> (src, &n, &d); <API key> (dest_value, n, d); } static void <API key> (const GValue * src_value, GValue * dest_value) { gfloat src = g_value_get_float (src_value); gint n, d; <API key> (src, &n, &d); <API key> (dest_value, n, d); } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_double = ((double) src_value->data[0].v_int) / ((double) src_value->data[1].v_int); } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_float = ((float) src_value->data[0].v_int) / ((float) src_value->data[1].v_int); } static gint <API key> (const GValue * value1, const GValue * value2) { gint n1, n2; gint d1, d2; gint ret; n1 = value1->data[0].v_int; n2 = value2->data[0].v_int; d1 = value1->data[1].v_int; d2 = value2->data[1].v_int; /* fractions are reduced when set, so we can quickly see if they're equal */ if (n1 == n2 && d1 == d2) return GST_VALUE_EQUAL; if (d1 == 0 && d2 == 0) return GST_VALUE_UNORDERED; else if (d1 == 0) return <API key>; else if (d2 == 0) return GST_VALUE_LESS_THAN; ret = <API key> (n1, d1, n2, d2); if (ret == -1) return GST_VALUE_LESS_THAN; else if (ret == 1) return <API key>; /* Equality can't happen here because we check for that * first already */ <API key> (GST_VALUE_UNORDERED); } void gst_value_set_date (GValue * value, const GDate * date) { g_return_if_fail (G_VALUE_TYPE (value) == GST_TYPE_DATE); g_return_if_fail (g_date_valid (date)); g_value_set_boxed (value, date); } const GDate * gst_value_get_date (const GValue * value) { <API key> (G_VALUE_TYPE (value) == GST_TYPE_DATE, NULL); return (const GDate *) g_value_get_boxed (value); } static gpointer gst_date_copy (gpointer boxed) { const GDate *date = (const GDate *) boxed; if (!g_date_valid (date)) { GST_WARNING ("invalid GDate"); return NULL; } return g_date_new_julian (g_date_get_julian (date)); } static gint <API key> (const GValue * value1, const GValue * value2) { const GDate *date1 = (const GDate *) g_value_get_boxed (value1); const GDate *date2 = (const GDate *) g_value_get_boxed (value2); guint32 j1, j2; if (date1 == date2) return GST_VALUE_EQUAL; if ((date1 == NULL || !g_date_valid (date1)) && (date2 != NULL && g_date_valid (date2))) { return GST_VALUE_LESS_THAN; } if ((date2 == NULL || !g_date_valid (date2)) && (date1 != NULL && g_date_valid (date1))) { return <API key>; } if (date1 == NULL || date2 == NULL || !g_date_valid (date1) || !g_date_valid (date2)) { return GST_VALUE_UNORDERED; } j1 = g_date_get_julian (date1); j2 = g_date_get_julian (date2); if (j1 == j2) return GST_VALUE_EQUAL; else if (j1 < j2) return GST_VALUE_LESS_THAN; else return <API key>; } static gchar * <API key> (const GValue * val) { const GDate *date = (const GDate *) g_value_get_boxed (val); if (date == NULL || !g_date_valid (date)) return g_strdup ("9999-99-99"); return g_strdup_printf ("%04u-%02u-%02u", g_date_get_year (date), g_date_get_month (date), g_date_get_day (date)); } static gboolean <API key> (GValue * dest, const gchar * s) { guint year, month, day; if (!s || sscanf (s, "%04u-%02u-%02u", &year, &month, &day) != 3) return FALSE; if (!g_date_valid_dmy (day, month, year)) return FALSE; g_value_take_boxed (dest, g_date_new_dmy (day, month, year)); return TRUE; } static gint <API key> (const GValue * value1, const GValue * value2) { const GstDateTime *date1 = (const GstDateTime *) g_value_get_boxed (value1); const GstDateTime *date2 = (const GstDateTime *) g_value_get_boxed (value2); gint ret; if (date1 == date2) return GST_VALUE_EQUAL; if ((date1 == NULL) && (date2 != NULL)) { return GST_VALUE_LESS_THAN; } if ((date2 == NULL) && (date1 != NULL)) { return GST_VALUE_LESS_THAN; } ret = <API key> (date1, date2); if (ret == 0) return GST_VALUE_EQUAL; else if (ret < 0) return GST_VALUE_LESS_THAN; else return <API key>; } static gchar * <API key> (const GValue * val) { GstDateTime *date = (GstDateTime *) g_value_get_boxed (val); gfloat offset; gint tzhour, tzminute; if (date == NULL) return g_strdup ("null"); offset = <API key> (date); tzhour = (gint) ABS (offset); tzminute = (gint) ((ABS (offset) - tzhour) * 60); return g_strdup_printf ("\"%04d-%02d-%02dT%02d:%02d:%02d.%06d" "%c%02d%02d\"", <API key> (date), <API key> (date), <API key> (date), <API key> (date), <API key> (date), <API key> (date), <API key> (date), offset >= 0 ? '+' : '-', tzhour, tzminute); } static gboolean <API key> (GValue * dest, const gchar * s) { gint year, month, day, hour, minute, second, usecond; gchar signal; gint offset = 0; gfloat tzoffset = 0; gint ret; if (!s || strcmp (s, "null") == 0) { return FALSE; } ret = sscanf (s, "%04d-%02d-%02dT%02d:%02d:%02d.%06d%c%04d", &year, &month, &day, &hour, &minute, &second, &usecond, &signal, &offset); if (ret >= 9) { tzoffset = (offset / 100) + ((offset % 100) / 60.0); if (signal == '-') tzoffset = -tzoffset; } else return FALSE; g_value_take_boxed (dest, gst_date_time_new (tzoffset, year, month, day, hour, minute, second + (usecond / 1000000.0))); return TRUE; } static void <API key> (const GValue * src_value, GValue * dest_value) { dest_value->data[0].v_pointer = <API key> (src_value); } static void <API key> (const GValue * src_value, GValue * dest_value) { <API key> (dest_value, src_value->data[0].v_pointer); } static void <API key> (const GValue * src_value, GValue * dest_value) { GstObject *obj; gchar *str; obj = g_value_get_object (src_value); if (obj) { str = g_strdup_printf ("(%s) %s", G_OBJECT_TYPE_NAME (obj), GST_OBJECT_NAME (obj)); } else { str = g_strdup ("NULL"); } dest_value->data[0].v_pointer = str; } static GTypeInfo _info = { 0, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, }; static <API key> _finfo = { 0 }; #define FUNC_VALUE_GET_TYPE(type, name) \ GType gst_ ## type ## _get_type (void) \ { \ static volatile GType gst_ ## type ## _type = 0; \ \ if (g_once_init_enter (&gst_ ## type ## _type)) { \ GType _type; \ _info.value_table = & _gst_ ## type ## _value_table; \ _type = <API key> ( \ <API key> (), \ name, &_info, &_finfo, 0); \ g_once_init_leave(&gst_ ## type ## _type, _type); \ } \ \ return gst_ ## type ## _type; \ } static const GTypeValueTable <API key> = { <API key>, NULL, <API key>, NULL, (char *) "i", <API key>, (char *) "p", <API key> }; FUNC_VALUE_GET_TYPE (fourcc, "GstFourcc"); static const GTypeValueTable <API key> = { <API key>, NULL, <API key>, NULL, (char *) "ii", <API key>, (char *) "pp", <API key> }; FUNC_VALUE_GET_TYPE (int_range, "GstIntRange"); static const GTypeValueTable <API key> = { <API key>, NULL, <API key>, NULL, (char *) "qq", <API key>, (char *) "pp", <API key> }; FUNC_VALUE_GET_TYPE (int64_range, "GstInt64Range"); static const GTypeValueTable <API key> = { <API key>, NULL, <API key>, NULL, (char *) "dd", <API key>, (char *) "pp", <API key> }; FUNC_VALUE_GET_TYPE (double_range, "GstDoubleRange"); static const GTypeValueTable <API key> = { <API key>, <API key>, <API key>, NULL, (char *) "iiii", <API key>, (char *) "pppp", <API key> }; FUNC_VALUE_GET_TYPE (fraction_range, "GstFractionRange"); static const GTypeValueTable <API key> = { <API key>, <API key>, <API key>, <API key>, (char *) "p", <API key>, (char *) "p", <API key> }; FUNC_VALUE_GET_TYPE (value_list, "GstValueList"); static const GTypeValueTable <API key> = { <API key>, <API key>, <API key>, <API key>, (char *) "p", <API key>, (char *) "p", <API key> }; FUNC_VALUE_GET_TYPE (value_array, "GstValueArray"); static const GTypeValueTable <API key> = { <API key>, NULL, <API key>, NULL, (char *) "ii", <API key>, (char *) "pp", <API key> }; FUNC_VALUE_GET_TYPE (fraction, "GstFraction"); GType gst_date_get_type (void) { static GType gst_date_type = 0; if (G_UNLIKELY (gst_date_type == 0)) { /* FIXME 0.11: we require GLib 2.8 already * Not using G_TYPE_DATE here on purpose, even if we could * if GLIB_CHECK_VERSION(2,8,0) was true: we don't want the * serialised strings to have different type strings depending * on what version is used, so FIXME when we require GLib-2.8 */ gst_date_type = <API key> ("GstDate", (GBoxedCopyFunc) gst_date_copy, (GBoxedFreeFunc) g_date_free); } return gst_date_type; } GType <API key> (void) { static GType gst_date_time_type = 0; if (G_UNLIKELY (gst_date_time_type == 0)) { gst_date_time_type = <API key> ("GstDateTime", (GBoxedCopyFunc) gst_date_time_ref, (GBoxedFreeFunc) gst_date_time_unref); } return gst_date_time_type; } void <API key> (void) { gst_value_table = g_array_new (FALSE, FALSE, sizeof (GstValueTable)); gst_value_hash = g_hash_table_new (NULL, NULL); <API key> = g_array_new (FALSE, FALSE, sizeof (GstValueUnionInfo)); <API key> = g_array_new (FALSE, FALSE, sizeof (<API key>)); <API key> = g_array_new (FALSE, FALSE, sizeof (<API key>)); { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = gst_fourcc_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { #if 0 static const GTypeValueTable value_table = { <API key>, NULL, <API key>, NULL, "i", NULL, /*<API key>, */ "p", NULL /*<API key> */ }; #endif static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = GST_TYPE_BUFFER; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, NULL, <API key>, <API key>, }; gst_value.type = GST_TYPE_CAPS; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, NULL, <API key>, <API key>, }; gst_value.type = GST_TYPE_STRUCTURE; gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = gst_date_get_type (); gst_value_register (&gst_value); } { static GstValueTable gst_value = { 0, <API key>, <API key>, <API key>, }; gst_value.type = <API key> (); gst_value_register (&gst_value); } <API key> (G_TYPE_DOUBLE, double); <API key> (G_TYPE_FLOAT, float); <API key> (G_TYPE_STRING, string); <API key> (G_TYPE_BOOLEAN, boolean); <API key> (G_TYPE_ENUM, enum); <API key> (G_TYPE_FLAGS, flags); <API key> (G_TYPE_INT, int); <API key> (G_TYPE_INT64, int64); <API key> (G_TYPE_LONG, long); <API key> (G_TYPE_UINT, uint); <API key> (G_TYPE_UINT64, uint64); <API key> (G_TYPE_ULONG, ulong); <API key> (G_TYPE_UCHAR, uchar); <API key> (GST_TYPE_FOURCC, G_TYPE_STRING, <API key>); <API key> (GST_TYPE_INT_RANGE, G_TYPE_STRING, <API key>); <API key> (<API key>, G_TYPE_STRING, <API key>); <API key> (<API key>, G_TYPE_STRING, <API key>); <API key> (<API key>, G_TYPE_STRING, <API key>); <API key> (GST_TYPE_LIST, G_TYPE_STRING, <API key>); <API key> (GST_TYPE_ARRAY, G_TYPE_STRING, <API key>); <API key> (GST_TYPE_FRACTION, G_TYPE_STRING, <API key>); <API key> (G_TYPE_STRING, GST_TYPE_FRACTION, <API key>); <API key> (GST_TYPE_FRACTION, G_TYPE_DOUBLE, <API key>); <API key> (GST_TYPE_FRACTION, G_TYPE_FLOAT, <API key>); <API key> (G_TYPE_DOUBLE, GST_TYPE_FRACTION, <API key>); <API key> (G_TYPE_FLOAT, GST_TYPE_FRACTION, <API key>); <API key> (GST_TYPE_DATE, G_TYPE_STRING, <API key>); <API key> (G_TYPE_STRING, GST_TYPE_DATE, <API key>); <API key> (GST_TYPE_OBJECT, G_TYPE_STRING, <API key>); <API key> (G_TYPE_INT, GST_TYPE_INT_RANGE, <API key>); <API key> (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, <API key>); <API key> (G_TYPE_INT64, <API key>, <API key>); <API key> (<API key>, <API key>, <API key>); <API key> (G_TYPE_DOUBLE, <API key>, <API key>); <API key> (<API key>, <API key>, <API key>); <API key> (GST_TYPE_ARRAY, GST_TYPE_ARRAY, <API key>); <API key> (GST_TYPE_FRACTION, <API key>, <API key>); <API key> (<API key>, <API key>, <API key>); <API key> (G_TYPE_INT, GST_TYPE_INT_RANGE, <API key>); <API key> (GST_TYPE_INT_RANGE, G_TYPE_INT, <API key>); <API key> (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, <API key>); <API key> (G_TYPE_INT64, <API key>, <API key>); <API key> (<API key>, G_TYPE_INT64, <API key>); <API key> (<API key>, <API key>, <API key>); <API key> (G_TYPE_DOUBLE, <API key>, <API key>); <API key> (<API key>, G_TYPE_DOUBLE, <API key>); <API key> (<API key>, <API key>, <API key>); <API key> (GST_TYPE_FRACTION, <API key>, <API key>); <API key> (<API key>, GST_TYPE_FRACTION, <API key>); <API key> (<API key>, <API key>, <API key>); /* see bug #317246, #64994, #65041 */ { volatile GType date_type = G_TYPE_DATE; g_type_name (date_type); } <API key> (G_TYPE_INT, GST_TYPE_INT_RANGE, <API key>); <API key> (GST_TYPE_INT_RANGE, GST_TYPE_INT_RANGE, <API key>); #if 0 /* Implement these if needed */ <API key> (GST_TYPE_FRACTION, <API key>, <API key>); <API key> (<API key>, <API key>, <API key>); #endif }
#ifndef <API key> #define <API key> #include "koproperty/Factory.h" #include <QDateEdit> namespace KoProperty { class KOPROPERTY_EXPORT DateEdit : public QDateEdit { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue USER true) public: DateEdit(const Property* prop, QWidget* parent); virtual ~DateEdit(); QVariant value() const; signals: void commitData(QWidget* editor); public slots: void setValue(const QVariant& value); protected: virtual void paintEvent(QPaintEvent* event); protected slots: void onDateChanged(); }; class KOPROPERTY_EXPORT DateDelegate : public <API key>, public <API key> { public: DateDelegate(); virtual QString <API key>(const Property* prop) const; virtual QWidget* createEditor(int type, QWidget* parent, const <API key>& option, const QModelIndex& index) const; }; } #endif
#pragma once #include <map> #include <string> #include <vector> #include "Common/CommonTypes.h" #include "DiscIO/Volume.h" namespace File { struct FSTEntry; } namespace DiscIO { class CVolumeDirectory : public IVolume { public: CVolumeDirectory(const std::string& _rDirectory, bool _bIsWii, const std::string& _rApploader = "", const std::string& _rDOL = ""); ~CVolumeDirectory(); static bool IsValidDirectory(const std::string& _rDirectory); bool Read(u64 _Offset, u64 _Length, u8* _pBuffer) const override; bool RAWRead(u64 _Offset, u64 _Length, u8* _pBuffer) const override; std::string GetUniqueID() const override; void SetUniqueID(std::string _ID); std::string GetMakerID() const override; std::vector<std::string> GetNames() const override; void SetName(std::string); u32 GetFSTSize() const override; std::string GetApploaderDate() const override; ECountry GetCountry() const override; u64 GetSize() const override; u64 GetRawSize() const override; void BuildFST(); private: static std::string <API key>(const std::string& _rDirectory); void SetDiskTypeWii(); void SetDiskTypeGC(); bool SetApploader(const std::string& _rApploader); void SetDOL(const std::string& _rDOL); // writing to read buffer void WriteToBuffer(u64 _SrcStartAddress, u64 _SrcLength, u8* _Src, u64& _Address, u64& _Length, u8*& _pBuffer) const; void PadToAddress(u64 _StartAddress, u64& _Address, u64& _Length, u8*& _pBuffer) const; void Write32(u32 data, u32 offset, u8* buffer); // FST creation void WriteEntryData(u32& entryOffset, u8 type, u32 nameOffset, u64 dataOffset, u32 length); void WriteEntryName(u32& nameOffset, const std::string& name); void WriteEntry(const File::FSTEntry& entry, u32& fstOffset, u32& nameOffset, u64& dataOffset, u32 parentEntryNum); // returns number of entries found in _Directory u32 AddDirectoryEntries(const std::string& _Directory, File::FSTEntry& parentEntry); std::string m_rootDirectory; std::map<u64, std::string> m_virtualDisk; u32 m_totalNameSize; // gc has no shift, wii has 2 bit shift u32 m_addressShift; // first address on disk containing file data u64 m_dataStartAddress; u64 m_fstNameOffset; u64 m_fstSize; u8* m_FSTData; u8* m_diskHeader; #pragma pack(push, 1) struct SDiskHeaderInfo { u32 debug_mntr_size; u32 simulated_mem_size; u32 arg_offset; u32 debug_flag; u32 track_location; u32 track_size; u32 countrycode; u32 unknown; u32 unknown2; // All the data is byteswapped SDiskHeaderInfo() { debug_mntr_size = 0; simulated_mem_size = 0; arg_offset = 0; debug_flag = 0; track_location = 0; track_size = 0; countrycode = 0; unknown = 0; unknown2 = 0; } }; #pragma pack(pop) SDiskHeaderInfo* m_diskHeaderInfo; u64 m_apploaderSize; u8* m_apploader; u64 m_DOLSize; u8* m_DOL; static const u8 ENTRY_SIZE = 0x0c; static const u8 FILE_ENTRY = 0; static const u8 DIRECTORY_ENTRY = 1; static const u64 DISKHEADER_ADDRESS = 0; static const u64 <API key> = 0x440; static const u64 APPLOADER_ADDRESS = 0x2440; static const u32 MAX_NAME_LENGTH = 0x3df; u64 FST_ADDRESS; u64 DOL_ADDRESS; }; } // namespace
<html> <head> <title>WATOBO - Interceptor</title> </head> <body> <h1>Thank you for using WATOBO - The Webapplication Toolbox</h1> Info:<br> Version: WATOBO_VERSION<br /> Home dir: WATOBO_HOME<br /> <br /><br /> <a href="watobo.pem">Download Certificate</a> </body> </html>
#ifndef __GSL_POLY_H__ #define __GSL_POLY_H__ #include <stdlib.h> #include <gsl/gsl_complex.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* Evaluate polynomial * * c[0] + c[1] x + c[2] x^2 + ... + c[len-1] x^(len-1) * * exceptions: none */ double gsl_poly_eval(const double c[], const int len, const double x); #ifdef HAVE_INLINE extern inline double gsl_poly_eval(const double c[], const int len, const double x) { int i; double ans = c[len-1]; for(i=len-1; i>0; i--) ans = c[i-1] + x * ans; return ans; } #endif /* HAVE_INLINE */ /* Solve for real or complex roots of the standard quadratic equation, * returning the number of real roots. * * Roots are returned ordered. */ int <API key> (double a, double b, double c, double * x0, double * x1); int <API key> (double a, double b, double c, gsl_complex * z0, gsl_complex * z1); /* Solve for real roots of the cubic equation * x^3 + a x^2 + b x + c = 0, returning the * number of real roots. * * Roots are returned ordered. */ int <API key> (double a, double b, double c, double * x0, double * x1, double * x2); int <API key> (double a, double b, double c, gsl_complex * z0, gsl_complex * z1, gsl_complex * z2); /* Solve for the complex roots of a general real polynomial */ typedef struct { size_t nc ; double * matrix ; } <API key> ; <API key> * <API key> (size_t n); void <API key> (<API key> * w); int <API key> (const double * a, size_t n, <API key> * w, <API key> z); __END_DECLS #endif /* __GSL_POLY_H__ */
#include <sys/mman.h> #ifndef PROT_EXEC #error PROT_EXEC not defined #endif
(function ($) { providers_small.mailru = { name: 'mail.ru', url: "javascript: $('#mail_ru_auth_login a').click();" }; openid.getBoxHTML__mailru = openid.getBoxHTML; openid.getBoxHTML = function (box_id, provider, box_size, index) { if (box_id == 'mailru') { var no_sprite = this.no_sprite; this.no_sprite = true; var result = this.getBoxHTML__mailru(box_id, provider, box_size, index); this.no_sprite = no_sprite; return result; } return this.getBoxHTML__mailru(box_id, provider, box_size, index); } Drupal.behaviors.<API key> = { attach: function (context) { $('#mail_ru_auth_login').hide(); }} })(jQuery);
/* $OpenBSD: libcrypto.h,v 1.17 2005/04/05 20:46:20 cloder Exp $ */ /* $EOM: libcrypto.h,v 1.16 2000/09/28 12:53:27 niklas Exp $ */ /* * This code was written under funding by Ericsson Radio Systems. */ #ifndef _LIBCRYPTO_H_ #define _LIBCRYPTO_H_ #include <stdio.h> /* XXX I want #include <ssl/cryptall.h> but we appear to not install meth.h */ #include <openssl/ssl.h> #include <openssl/bio.h> #include <openssl/md5.h> #include <openssl/pem.h> #include <openssl/x509_vfy.h> #include <openssl/x509.h> extern void libcrypto_init(void); #endif /* _LIBCRYPTO_H_ */
#include <stdlib.h> #include <string.h> #include "tcpstream.h" #include <iostream> #include <iomanip> #include <assert.h> #include <errno.h> #include <math.h> #include <limits.h> #include <sys/time.h> #include <time.h> /* Debugging for STATE change, and Startup SYNs */ #include "util/rsdebug.h" #include "util/rsstring.h" #include "util/rsrandom.h" static struct RsLog::logInfo rstcpstreamzoneInfo = {RsLog::Default, "rstcpstream"}; #define rstcpstreamzone &rstcpstreamzoneInfo /* * #define DEBUG_TCP_STREAM 1 * #define <API key> 1 * #define <API key> 1 */ //#define <API key> 1 //#define <API key> 1 /* *#define <API key> 1 */ /* * #define TCP_NO_PARTIAL_READ 1 */ #ifdef DEBUG_TCP_STREAM int checkData(uint8 *data, int size, int idx); int setupBinaryCheck(std::string fname); #endif static const uint32 kMaxQueueSize = 300; // Was 100, which means max packet size of 100k (smaller than max packet size). static const uint32 kMaxPktRetransmit = 10; static const uint32 <API key> = 100; // 100 => 200secs = over 3 minutes startup static const int TCP_STD_TTL = 64; static const int <API key> = 4; static const double RTT_ALPHA = 0.875; int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size); // platform independent fractional timestamp. static double getCurrentTS(); TcpStream::TcpStream(UdpSubReceiver *lyr) : tcpMtx("TcpStream"), inSize(0), outSizeRead(0), outSizeNet(0), state(TCP_CLOSED), inStreamActive(false), outStreamActive(false), outSeqno(0), outAcked(0), outWinSize(0), inAckno(0), inWinSize(0), maxWinSize(TCP_MAX_WIN), keepAliveTimeout(TCP_ALIVE_TIMEOUT), retransTimerOn(false), retransTimeout(TCP_RETRANS_TIMEOUT), retransTimerTs(0), keepAliveTimer(0), lastIncomingPkt(0), lastSentAck(0), lastSentWinSize(0), initOurSeqno(0), initPeerSeqno(0), lastWriteTF(0),lastReadTF(0), wcount(0), rcount(0), errorState(0), /* retranmission variables - init to large */ rtt_est(TCP_RETRANS_TIMEOUT), rtt_dev(0), congestThreshold(TCP_MAX_WIN), congestWinSize(MAX_SEG), congestUpdate(0), ttl(0), mTTL_period(0), mTTL_start(0), mTTL_end(0), peerKnown(false), udp(lyr) { sockaddr_clear(&peeraddr); return; } /* Stream Control! */ int TcpStream::connect(const struct sockaddr_in &raddr, uint32_t conn_period) { tcpMtx.lock(); setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); return -1; } /* setup Seqnos */ outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ inWinSize = maxWinSize; congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; /* Init Connection */ /* send syn packet */ TcpPacket *pkt = new TcpPacket(); pkt -> setSyn(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::connect() Send Init Pkt" << std::endl; #endif setTTL(1); mTTL_start = getCurrentTS(); mTTL_period = conn_period; mTTL_end = mTTL_start + mTTL_period; toSend(pkt); /* change state */ state = TCP_SYN_SENT; errorState = EAGAIN; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_SENT" << std::endl; #endif { rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_SYN_SENT (Connect)"); } tcpMtx.unlock(); return -1; } int TcpStream::listenfor(const struct sockaddr_in &raddr) { tcpMtx.lock(); setRemoteAddress(raddr); /* check state */ if (state != TCP_CLOSED) { if (state == TCP_ESTABLISHED) { tcpMtx.unlock(); return 0; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; } else { // major issues! errorState = EFAULT; } tcpMtx.unlock(); return -1; } errorState = EAGAIN; tcpMtx.unlock(); return -1; } /* Stream Control! */ int TcpStream::close() { tcpMtx.lock(); cleanup(); tcpMtx.unlock(); return 0; } int TcpStream::closeWrite() { tcpMtx.lock(); /* check state */ /* will always close socket.... */ /* if in TCP_ESTABLISHED.... * -> to state: TCP_FIN_WAIT_1 * and shutdown outward stream. */ /* if in CLOSE_WAIT.... * -> to state: TCP_LAST_ACK * and shutdown outward stream. * do this one first!. */ outStreamActive = false; if (state == TCP_CLOSE_WAIT) { /* don't think we need to be * graceful at this point... * connection already closed by other end. * XXX might fix later with scheme * * flag stream closed, and when outqueue * emptied then fin will be sent. */ /* do nothing */ } if (state == TCP_ESTABLISHED) { /* fire off the damned thing. */ /* by changing state */ /* again this is handled by internals * the flag however indicates that * no more data can be send, * and once the queue empties * the FIN will be sent. */ } if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() Flag Set" << std::endl; #endif tcpMtx.unlock(); return 0; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::close() pending" << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); return -1; } bool TcpStream::isConnected() { tcpMtx.lock(); bool isConn = (state == TCP_ESTABLISHED); tcpMtx.unlock(); return isConn; } int TcpStream::status(std::ostream &out) { tcpMtx.lock(); int s = status_locked(out); tcpMtx.unlock(); return s; } int TcpStream::status_locked(std::ostream &out) { int tmpstate = state; // can leave the timestamp here as time()... rough but okay. out << "TcpStream::status @ (" << time(NULL) << ")" << std::endl; out << "TcpStream::state = " << (int) state << std::endl; out << std::endl; out << "writeBuffer: " << inSize << " + MAX_SEG * " << inQueue.size(); out << " bytes Queued for transmission" << std::endl; out << "readBuffer: " << outSizeRead << " + MAX_SEG * "; out << outQueue.size() << " + " << outSizeNet; out << " incoming bytes waiting" << std::endl; out << std::endl; out << "inPkts: " << inPkt.size() << " packets waiting for processing"; out << std::endl; out << "outPkts: " << outPkt.size() << " packets waiting for acks"; out << std::endl; out << "us -> peer: nextSeqno: " << outSeqno << " lastAcked: " << outAcked; out << " winsize: " << outWinSize; out << std::endl; out << "peer -> us: Expected SeqNo: " << inAckno; out << " winsize: " << inWinSize; out << std::endl; out << std::endl; return tmpstate; } int TcpStream::write_allowed() { tcpMtx.lock(); int ret = 1; if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { errorState = EBADF; ret = -1; } if (ret < 1) { tcpMtx.unlock(); return ret; } int maxwrite = (kMaxQueueSize - inQueue.size()) * MAX_SEG; tcpMtx.unlock(); return maxwrite; } int TcpStream::read_pending() { tcpMtx.lock(); /* error should be detected next time */ int maxread = int_read_pending(); if (state == TCP_CLOSED) { errorState = EBADF; maxread = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; maxread = -1; } tcpMtx.unlock(); return maxread; } /* INTERNAL */ int TcpStream::int_read_pending() { return outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; } /* stream Interface */ int TcpStream::write(char *dta, int size) /* write -> pkt -> net */ { tcpMtx.lock(); int ret = 1; /* initial error checking */ #ifdef <API key> static uint32 TMPtotalwrite = 0; #endif if (state == TCP_CLOSED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP Not Established" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (inQueue.size() > kMaxQueueSize) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error EAGAIN" << std::endl; #endif errorState = EAGAIN; ret = -1; } else if (!outStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() Error TCP_CLOSED" << std::endl; #endif errorState = EBADF; ret = -1; } if (ret < 1) /* check for initial error */ { tcpMtx.unlock(); return ret; } #ifdef <API key> std::cerr << "TcpStream::write() = Will Succeed " << size << std::endl; std::cerr << "TcpStream::write() Write Start: " << TMPtotalwrite << std::endl; std::cerr << printPktOffset(TMPtotalwrite, dta, size) << std::endl; TMPtotalwrite += size; #endif if (size + inSize < MAX_SEG) { #ifdef <API key> std::cerr << "TcpStream::write() Add Itty Bit" << std::endl; std::cerr << "TcpStream::write() inData: " << (void *) inData; std::cerr << " inSize: " << inSize << " dta: " << (void *) dta; std::cerr << " size: " << size << " dest: " << (void *) &(inData[inSize]); std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif memcpy((void *) &(inData[inSize]), dta, size); inSize += size; //std::cerr << "Small Packet - write to net:" << std::endl; //std::cerr << printPkt(dta, size) << std::endl; tcpMtx.unlock(); return size; } /* otherwise must construct a dataBuffer. */ #ifdef <API key> std::cerr << "TcpStream::write() filling 1 dataBuffer" << std::endl; std::cerr << "TcpStream::write() from inData(" << inSize << ")" << std::endl; std::cerr << "TcpStream::write() + dta(" << MAX_SEG - inSize; std::cerr << "/" << size << ")" << std::endl; #endif /* first create 1. */ dataBuffer *db = new dataBuffer; memcpy((void *) db->data, (void *) inData, inSize); int remSize = size; memcpy((void *) &(db->data[inSize]), dta, MAX_SEG - inSize); inQueue.push_back(db); remSize -= (MAX_SEG - inSize); #ifdef <API key> std::cerr << "TcpStream::write() remaining " << remSize << " bytes to load" << std::endl; #endif while(remSize >= MAX_SEG) { #ifdef <API key> std::cerr << "TcpStream::write() filling whole dataBuffer" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "]" << std::endl; #endif db = new dataBuffer; memcpy((void *) db->data, (void *) &(dta[size-remSize]), MAX_SEG); inQueue.push_back(db); remSize -= MAX_SEG; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::write() = " << size << std::endl; #endif if (remSize > 0) { #ifdef <API key> std::cerr << "TcpStream::write() putting last bit in inData" << std::endl; std::cerr << "TcpStream::write() from dta[" << size-remSize << "] size: "; std::cerr << remSize << std::endl; #endif memcpy((void *) inData, (void *) &(dta[size-remSize]), remSize); inSize = remSize; } else { #ifdef <API key> std::cerr << "TcpStream::write() Data fitted exactly in dataBuffer!" << std::endl; #endif inSize = 0; } tcpMtx.unlock(); return size; } int TcpStream::read(char *dta, int size) /* net -> pkt -> read */ { tcpMtx.lock(); #ifdef <API key> static uint32 TMPtotalread = 0; #endif /* max available data is * outDataRead + outQueue + outDataNet */ int maxread = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; int ret = 1; /* used only for initial errors */ if (state == TCP_CLOSED) { errorState = EBADF; ret = -1; } else if (state < TCP_ESTABLISHED) { errorState = EAGAIN; ret = -1; } else if ((!inStreamActive) && (maxread == 0)) { // finished stream. ret = 0; } else if (maxread == 0) { /* must wait for more data */ errorState = EAGAIN; ret = -1; } if (ret < 1) /* if ret has been changed */ { tcpMtx.unlock(); return ret; } if (maxread < size) { #ifdef TCP_NO_PARTIAL_READ if (inStreamActive) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::read() No Partial Read! "; std::cerr << "Can only supply " << maxread << " of "; std::cerr << size; std::cerr << std::endl; #endif errorState = EAGAIN; tcpMtx.unlock(); return -1; } #endif /* TCP_NO_PARTIAL_READ */ size = maxread; } /* if less than outDataRead size */ if (((unsigned) (size) < outSizeRead) && (outSizeRead)) { #ifdef <API key> std::cerr << "TcpStream::read() Add Itty Bit" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size << " remaining: " << outSizeRead - size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, size); memmove((void *) outDataRead, (void *) &(outDataRead[size]), outSizeRead - (size)); outSizeRead -= size; #ifdef <API key> std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef <API key> checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); return size; } /* move the whole of outDataRead. */ if (outSizeRead) { #ifdef <API key> std::cerr << "TcpStream::read() Move All outSizeRead" << std::endl; std::cerr << "TcpStream::read() outSizeRead: " << outSizeRead; std::cerr << " size: " << size; std::cerr << std::endl; #endif memcpy(dta,(void *) outDataRead, outSizeRead); } int remSize = size - outSizeRead; outSizeRead = 0; #ifdef <API key> std::cerr << "TcpStream::read() remaining size: " << remSize << std::endl; #endif while((outQueue.size() > 0) && (remSize > 0)) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); /* remove */ #ifdef <API key> std::cerr << "TcpStream::read() Taking Data from outQueue" << std::endl; #endif /* load into outDataRead */ if (remSize < MAX_SEG) { #ifdef <API key> std::cerr << "TcpStream::read() Partially using Segment" << std::endl; std::cerr << "TcpStream::read() moving: " << remSize << " to dta @: " << size-remSize; std::cerr << std::endl; std::cerr << "TcpStream::read() rest to outDataRead: " << MAX_SEG - remSize; std::cerr << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, remSize); memcpy((void *) outDataRead, (void *) &(db->data[remSize]), MAX_SEG - remSize); outSizeRead = MAX_SEG - remSize; delete db; #ifdef <API key> std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef <API key> checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); return size; } #ifdef <API key> std::cerr << "TcpStream::read() Move Whole Segment to dta @ " << size-remSize << std::endl; #endif /* else copy whole segment */ memcpy((void *) &(dta[(size)-remSize]), (void *) db->data, MAX_SEG); remSize -= MAX_SEG; delete db; } /* assumes that outSizeNet >= remSize due to initial * constraint */ if ((remSize > 0)) { #ifdef <API key> std::cerr << "TcpStream::read() Using up : " << remSize; std::cerr << " last Bytes, leaving: " << outSizeNet - remSize << std::endl; #endif memcpy((void *) &(dta[(size)-remSize]),(void *) outDataNet, remSize); outSizeNet -= remSize; if (outSizeNet > 0) { /* move to the outDataRead */ memcpy((void *) outDataRead,(void *) &(outDataNet[remSize]), outSizeNet); outSizeRead = outSizeNet; outSizeNet = 0; #ifdef <API key> std::cerr << "TcpStream::read() moving last of outSizeNet to outSizeRead: " << outSizeRead; std::cerr << std::endl; #endif } #ifdef <API key> std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef <API key> checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); return size; } #ifdef <API key> std::cerr << "TcpStream::read() = Succeeded " << size << std::endl; std::cerr << "TcpStream::read() Read Start: " << TMPtotalread << std::endl; std::cerr << printPktOffset(TMPtotalread, dta, size) << std::endl; #endif #ifdef <API key> checkData((uint8 *) dta, size, TMPtotalread); TMPtotalread += size; #endif /* can allow more in! - update inWinSize */ UpdateInWinSize(); tcpMtx.unlock(); return size; } /* Callback from lower Layers */ void TcpStream::recvPkt(void *data, int size) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt()"; std::cerr << std::endl; #endif tcpMtx.lock(); uint8 *input = (uint8 *) data; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recvPkt() Past Lock!"; std::cerr << std::endl; #endif #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recvPkt() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv() Not Connected"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() ReadPkt(" << size << ")" << std::endl; //std::cerr << printPkt(input, size); //std::cerr << std::endl; #endif TcpPacket *pkt = new TcpPacket(); if (0 < pkt -> readPacket(input, size)) { lastIncomingPkt = getCurrentTS(); handleIncoming(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::recv() Bad Packet Deleting!"; std::cerr << std::endl; #endif delete pkt; } tcpMtx.unlock(); return; } int TcpStream::tick() { tcpMtx.lock(); //std::cerr << "TcpStream::tick()" << std::endl; recv_check(); /* recv is async */ send(); tcpMtx.unlock(); return 1; } bool TcpStream::getRemoteAddress(struct sockaddr_in &raddr) { tcpMtx.lock(); if (peerKnown) { raddr = peeraddr; } tcpMtx.unlock(); return peerKnown; } uint8 TcpStream::TcpState() { tcpMtx.lock(); uint8 err = state; tcpMtx.unlock(); return err; } int TcpStream::TcpErrorState() { tcpMtx.lock(); int err = errorState; tcpMtx.unlock(); return err; } static int ilevel = 100; bool TcpStream::widle() { tcpMtx.lock(); /* init */ if (!lastWriteTF) { lastWriteTF = int_wbytes(); tcpMtx.unlock(); return false; } if ((lastWriteTF == int_wbytes()) && (inSize == 0) && inQueue.empty()) { wcount++; if (wcount > ilevel) { tcpMtx.unlock(); return true; } tcpMtx.unlock(); return false; } wcount = 0; lastWriteTF = int_wbytes(); tcpMtx.unlock(); return false; } bool TcpStream::ridle() { tcpMtx.lock(); /* init */ if (!lastReadTF) { lastReadTF = int_rbytes(); tcpMtx.unlock(); return false; } if ((lastReadTF == int_rbytes()) && (outSizeRead + outQueue.size() + outSizeNet== 0)) { rcount++; if (rcount > ilevel) { tcpMtx.unlock(); return true; } tcpMtx.unlock(); return false; } rcount = 0; lastReadTF = int_rbytes(); tcpMtx.unlock(); return false; } uint32 TcpStream::wbytes() { tcpMtx.lock(); uint32 wb = int_wbytes(); tcpMtx.unlock(); return wb; } uint32 TcpStream::rbytes() { tcpMtx.lock(); uint32 rb = int_rbytes(); tcpMtx.unlock(); return rb; } int TcpStream::recv_check() { double cts = getCurrentTS(); // fractional seconds. #ifdef DEBUG_TCP_STREAM if (state > TCP_SYN_RCVD) { int availRead = outSizeRead + outQueue.size() * MAX_SEG + outSizeNet; std::cerr << "TcpStream::recv_check() CC: "; std::cerr << " iWS: " << inWinSize; std::cerr << " aRead: " << availRead; std::cerr << " iAck: " << inAckno; std::cerr << std::endl; } else { std::cerr << "TcpStream::recv_check() Not Connected"; std::cerr << std::endl; } #endif // make sure we've rcvd something! if ((state > TCP_SYN_RCVD) && (cts - lastIncomingPkt > kNoPktTimeout)) { /* shut it all down */ /* this period should be equivalent * to the firewall timeouts ??? * * for max efficiency */ #ifdef <API key> std::cerr << "TcpStream::recv_check() state = CLOSED (NoPktTimeout)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (kNoPktTimeout)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); } return 1; } int TcpStream::cleanup() { // This shuts it all down! no matter what. rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::cleanup() state = TCP_CLOSED"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif //peerKnown = false; //??? NOT SURE -> for a rapid reconnetion this might be key?? /* reset TTL */ setTTL(TCP_STD_TTL); // clear arrays. inSize = 0; while(inQueue.size() > 0) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); delete db; } while(outPkt.size() > 0) { TcpPacket *pkt = outPkt.front(); outPkt.pop_front(); delete pkt; } // clear arrays. outSizeRead = 0; outSizeNet = 0; while(outQueue.size() > 0) { dataBuffer *db = outQueue.front(); outQueue.pop_front(); delete db; } while(inPkt.size() > 0) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; } return 1; } int TcpStream::handleIncoming(TcpPacket *pkt) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::handleIncoming()" << std::endl; #endif switch(state) { case TCP_CLOSED: case TCP_LISTEN: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ return incoming_Closed(pkt); break; case TCP_SYN_SENT: /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ return incoming_SynSent(pkt); break; case TCP_SYN_RCVD: /* if receive ACK * To State: TCP_ESTABLISHED */ return incoming_SynRcvd(pkt); break; case TCP_ESTABLISHED: /* if receive FIN * -> respond ACK * To State: TCP_CLOSE_WAIT * else Discard. */ return <API key>(pkt); break; case TCP_FIN_WAIT_1: /* state entered by close() call. * if receive FIN * -> respond ACK * To State: TCP_CLOSING * * if receive ACK * -> no response * To State: TCP_FIN_WAIT_2 * * if receive FIN+ACK * -> respond ACK * To State: TCP_TIMED_WAIT * */ return <API key>(pkt); //return incoming_FinWait1(pkt); break; case TCP_FIN_WAIT_2: /* if receive FIN * -> respond ACK * To State: TCP_TIMED_WAIT */ return <API key>(pkt); //return incoming_FinWait2(pkt); break; case TCP_CLOSING: /* if receive ACK * To State: TCP_TIMED_WAIT */ /* all handled in Established */ return <API key>(pkt); //return incoming_Closing(pkt); break; case TCP_CLOSE_WAIT: /* * wait for our close to be called. */ /* all handled in Established */ return <API key>(pkt); //return incoming_CloseWait(pkt); break; case TCP_LAST_ACK: /* entered by the local close() after sending FIN. * if receive ACK * To State: TCP_CLOSED */ /* all handled in Established */ return <API key>(pkt); /* return incoming_LastAck(pkt); */ break; /* this is actually the only * final state where packets not expected! */ case TCP_TIMED_WAIT: /* State: TCP_TIMED_WAIT * * discard all -> both connections FINed * timeout of this state. * */ #ifdef <API key> std::cerr << "TcpStream::handleIncoming() state = CLOSED (TimedWait)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; // return incoming_TimedWait(pkt); { rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd TCP_TIMED_WAIT?)"); } break; } delete pkt; return 1; } int TcpStream::incoming_Closed(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed()" << std::endl; #endif if ((pkt -> hasSyn()) && (!pkt -> hasAck())) { /* Init Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; inWinSize = maxWinSize; /* we can get from SynSent as well, * but only send one SYN packet */ /* start packet */ TcpPacket *rsp = new TcpPacket(); if (state == TCP_CLOSED) { outSeqno = genSequenceNo(); initOurSeqno = outSeqno; outAcked = outSeqno; /* min - 1 expected */ /* setup Congestion Charging */ congestThreshold = TCP_MAX_WIN; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; rsp -> setSyn(); } rsp -> setAck(inAckno); /* seq + winsize set in toSend() */ /* as we have received something ... we can up the TTL */ setTTL(TCP_STD_TTL); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_Closed() Sending reply" << std::endl; std::cerr << "SeqNo: " << rsp->seqno << " Ack: " << rsp->ackno; std::cerr << std::endl; #endif toSend(rsp); /* change state */ state = TCP_SYN_RCVD; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_SYN_RCVD" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_SYN_RECVD (recvd SYN & !ACK)"); } delete pkt; return 1; } int TcpStream::incoming_SynSent(TcpPacket *pkt) { /* if receive SYN * -> respond SYN/ACK * To State: SYN_RCVD * * if receive SYN+ACK * -> respond ACK * To State: TCP_ESTABLISHED * * else Discard. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent()" << std::endl; #endif if ((pkt -> hasSyn()) && (pkt -> hasAck())) { /* check stuff */ if (pkt -> getAck() != outSeqno) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynSent() Bad Ack - Deleting " << std::endl; #endif /* bad ignore */ delete pkt; return -1; } /* Complete Connection */ /* save seqno */ initPeerSeqno = pkt -> seqno; inAckno = initPeerSeqno + 1; outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* before ACK, reset the TTL * As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* ack the Syn Packet */ sendAck(); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (recvd SUN & ACK)"); delete pkt; } else /* same as if closed! (simultaneous open) */ { return incoming_Closed(pkt); } return 1; } int TcpStream::incoming_SynRcvd(TcpPacket *pkt) { /* if receive ACK * To State: TCP_ESTABLISHED */ if (pkt -> hasRst()) { /* trouble */ state = TCP_CLOSED; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_CLOSED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (recvd RST)"); delete pkt; return 1; } bool ackWithData = false; if (pkt -> hasAck()) { if (pkt -> hasSyn()) { /* has resent syn -> check it matches */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Pkt with ACK + SYN" << std::endl; #endif } /* check stuff */ if (pkt -> getAck() != outSeqno) { /* bad ignore */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt with bad ACK" << std::endl; #endif delete pkt; return -1; } /* Complete Connection */ /* save seqno */ if (pkt -> datasize > 0) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::incoming_SynRcvd() ACK with Data!" << std::endl; std::cerr << "TcpStream::incoming_SynRcvd() Shoudn't recv ... unless initACK lost!" << std::endl; #endif // managed to trigger this under windows... // perhaps the initial Ack was lost, // believe we should just pass this packet // directly to the <API key>... once // the following has been done. // and it should all work! //exit(1); ackWithData = true; } inAckno = pkt -> seqno; /* + pkt -> datasize; */ outWinSize = pkt -> winsize; outAcked = pkt -> getAck(); /* As they have sent something, and we have received * through the firewall, set to STD. */ setTTL(TCP_STD_TTL); /* change state */ state = TCP_ESTABLISHED; outStreamActive = true; inStreamActive = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream STATE -> TCP_ESTABLISHED" << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_ESTABLISHED (have SYN, recvd ACK)"); } if (ackWithData) { /* connection Established -> handle normally */ #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Handling Data with Ack Pkt!"; std::cerr << std::endl; #endif <API key>(pkt); } else { #ifdef DEBUG_TCP_STREAM std::cerr << "incoming_SynRcvd -> Ignoring Pkt!" << std::endl; #endif /* else nothing */ delete pkt; } return 1; } int TcpStream::<API key>(TcpPacket *pkt) { /* first handle the Ack ... * this must be done before the queue, * to keep the values as up-to-date as possible. * * must sanity check ..... * make sure that the sequence number is within the correct range. */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() "; std::cerr << " Pkt->seqno: " << std::hex << pkt->seqno; std::cerr << " Pkt->datasize: " << std::hex << pkt->datasize; std::cerr << std::dec << std::endl; #endif if ((!isOldSequence(pkt->seqno, inAckno)) && // seq >= inAckno isOldSequence(pkt->seqno, inAckno + maxWinSize)) // seq < inAckno + maxWinSize. { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() valid Packet Seqno."; std::cerr << std::endl; #endif if (pkt->hasAck()) { #ifdef DEBUG_TCP_STREAM if (outAcked != pkt->ackno) { std::cerr << "TcpStream::<API key>() valid Packet Seqno & new Ackno."; std::cerr << std::endl; std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; } #endif outAcked = pkt->ackno; } outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { /* what we do! (This is actually okay - and happens occasionally) */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() ERROR out-of-range Packet Seqno."; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::endl; std::cerr << "\t inAckno: " << std::hex << inAckno; std::cerr << std::endl; std::cerr << "\t inAckno + maxWinSize: " << std::hex << inAckno + maxWinSize; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->SeqNo: " << std::hex << pkt->seqno; std::cerr << std::dec << std::endl; std::cerr << "\t !isOldSequence(pkt->seqno, inAckno): " << (!isOldSequence(pkt->seqno, inAckno)); std::cerr << std::endl; std::cerr << "\t isOldSequence(pkt->seqno, inAckno + maxWinSize): " << isOldSequence(pkt->seqno, inAckno + maxWinSize); std::cerr << std::endl; std::cerr << std::endl; std::cerr << "TcpStream::<API key>() Sending Ack to update Peer"; std::cerr << std::endl; #endif sendAck(); } /* add to queue */ inPkt.push_back(pkt); if (inPkt.size() > kMaxQueueSize) { TcpPacket *pkt = inPkt.front(); inPkt.pop_front(); delete pkt; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() inPkt reached max size...Discarding Oldest Pkt"; std::cerr << std::endl; #endif } /* use as many packets as possible */ return check_InPkts(); } int TcpStream::check_InPkts() { bool found = true; TcpPacket *pkt; std::list<TcpPacket *>::iterator it; while(found) { found = false; for(it = inPkt.begin(); (!found) && (it != inPkt.end());) { #ifdef DEBUG_TCP_STREAM std::cerr << "Checking expInAck: " << std::hex << inAckno; std::cerr << " vs: " << std::hex << (*it)->seqno << std::dec << std::endl; #endif pkt = *it; if ((*it)->seqno == inAckno) { //std::cerr << "\tFOUND MATCH!"; //std::cerr << std::endl; found = true; it = inPkt.erase(it); } /* see if we can discard it */ /* if smaller seqno, and not wrapping around */ else if (isOldSequence((*it)->seqno, inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "Discarding Old Packet expAck: " << std::hex << inAckno; std::cerr << " seqno: " << std::hex << (*it)->seqno; std::cerr << " pkt->size: " << std::hex << (*it)->datasize; std::cerr << " pkt->seqno+size: " << std::hex << (*it)->seqno + (*it)->datasize; std::cerr << std::dec << std::endl; #endif /* discard */ it = inPkt.erase(it); delete pkt; } else { ++it; } } if (found) { #ifdef <API key> if (pkt->datasize) { checkData(pkt->data, pkt->datasize, pkt-><API key>); } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() Updating inAckno from: " << std::hex << inAckno; #endif /* update ack number - let it rollover */ inAckno = pkt->seqno + pkt->datasize; #ifdef DEBUG_TCP_STREAM std::cerr << " to: " << std::hex << inAckno; std::cerr << std::dec << std::endl; #endif /* XXX This shouldn't be here, as it prevents * the Ack being used until the packet is. * This means that a dropped packet will stop traffic in both * directions.... * * Moved it to <API key> .... but extra * check here to be sure! */ if (pkt->hasAck()) { if (isOldSequence(outAcked, pkt->ackno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() ERROR Ack Not Already Used!"; std::cerr << std::endl; std::cerr << "\t Pkt->ackno: " << std::hex << pkt->ackno; std::cerr << std::endl; std::cerr << "\t outAcked: " << std::hex << outAcked; std::cerr << std::endl; std::cerr << "\t Pkt->winsize: " << std::hex << pkt->winsize; std::cerr << std::endl; std::cerr << "\t outWinSize: " << std::hex << outWinSize; std::cerr << std::endl; std::cerr << "\t isOldSequence(outAcked, pkt->ackno): " << isOldSequence(outAcked, pkt->ackno); std::cerr << std::endl; std::cerr << std::endl; #endif outAcked = pkt->ackno; outWinSize = pkt->winsize; #ifdef DEBUG_TCP_STREAM std::cerr << "\tUpdating OutAcked to: " << outAcked; std::cerr << std::endl; std::cerr << "\tUpdating OutWinSize to: " << outWinSize; std::cerr << std::endl; #endif } else { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::check_inPkts() GOOD Ack Already Used!"; std::cerr << std::endl; #endif } } /* push onto queue */ if (outSizeNet + pkt->datasize < MAX_SEG) { /* move onto outSizeNet */ if (pkt->datasize) { memcpy((void *) &(outDataNet[outSizeNet]), pkt->data, pkt->datasize); outSizeNet += pkt->datasize; } } else { /* if it'll overflow the buffer. */ dataBuffer *db = new dataBuffer(); /* move outDatNet -> buffer */ memcpy((void *) db->data, (void *) outDataNet, outSizeNet); /* fill rest of space */ int remSpace = MAX_SEG - outSizeNet; memcpy((void *) &(db->data[outSizeNet]), (void *) pkt->data, remSpace); /* push packet onto queue */ outQueue.push_back(db); /* any big chunks that will take up a full dataBuffer */ int remData = pkt->datasize - remSpace; while(remData >= MAX_SEG) { db = new dataBuffer(); memcpy((void *) db->data, (void *) &(pkt->data[remSpace]), MAX_SEG); remData -= MAX_SEG; outQueue.push_back(db); } /* remove any remaining to outDataNet */ outSizeNet = remData; if (outSizeNet > 0) { memcpy((void *) outDataNet, (void *) &(pkt->data[pkt->datasize - remData]), outSizeNet); } } /* can allow more in! - update inWinSize */ UpdateInWinSize(); /* if pkt is FIN */ /* these must be here -> at the end of the reliable stream */ /* if the fin is set, ack it specially close stream */ if (pkt->hasFin()) { /* send final ack */ sendAck(); /* closedown stream */ inStreamActive = false; if (state == TCP_ESTABLISHED) { state = TCP_CLOSE_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSE_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSE_WAIT (recvd FIN)"); } else if (state == TCP_FIN_WAIT_1) { state = TCP_CLOSING; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_CLOSING"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSING (FIN_WAIT_1, recvd FIN)"); } else if (state == TCP_FIN_WAIT_2) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (FIN_WAIT_2, recvd FIN)"); cleanup(); } } /* if ack for our FIN */ if ((pkt->hasAck()) && (!outStreamActive) && (pkt->ackno == outSeqno)) { if (state == TCP_FIN_WAIT_1) { state = TCP_FIN_WAIT_2; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_2"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_2 (FIN_WAIT_1, recvd ACK)"); } else if (state == TCP_LAST_ACK) { #ifdef <API key> std::cerr << "TcpStream::state = TCP_CLOSED (LastAck)"; std::cerr << std::endl; dumpstate_locked(std::cerr); #endif state = TCP_CLOSED; rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_CLOSED (LAST_ACK, recvd ACK)"); cleanup(); } else if (state == TCP_CLOSING) { state = TCP_TIMED_WAIT; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_TIMED_WAIT"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_TIMED_WAIT (TCP_CLOSING, recvd ACK)"); cleanup(); } } delete pkt; } /* end of found */ } /* while(found) */ return 1; } /* This Fn should be called after each read, or recvd data (thats added to the buffer) */ int TcpStream::UpdateInWinSize() { /* InWinSize = maxWinSze - QueuedData, * actually we can allow a lot more to queue up... * inWinSize = 65536, unless QueuedData > 65536. * inWinSize = 2 * maxWinSize - QueuedData; * */ uint32 queuedData = int_read_pending(); if (queuedData < maxWinSize) { inWinSize = maxWinSize; } else if (queuedData < 2 * maxWinSize) { inWinSize = 2 * maxWinSize - queuedData; } else { inWinSize = 0; } return inWinSize; } int TcpStream::sendAck() { /* simple -> toSend fills in ack/winsize * and the rest is history */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::sendAck()"; std::cerr << std::endl; #endif return toSend(new TcpPacket(), false); } void TcpStream::setRemoteAddress(const struct sockaddr_in &raddr) { peeraddr = raddr; peerKnown = true; } int TcpStream::toSend(TcpPacket *pkt, bool retrans) { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif delete pkt; return 0; } /* get accurate timestamp */ double cts = getCurrentTS(); pkt -> winsize = inWinSize; pkt -> seqno = outSeqno; /* increment seq no */ if (pkt->datasize) { #ifdef <API key> checkData(pkt->data, pkt->datasize, <API key>); #endif outSeqno += pkt->datasize; } if (pkt->hasSyn()) { /* should not have data! */ if (pkt->datasize) { #ifdef DEBUG_TCP_STREAM std::cerr << "SYN Packet shouldn't contain data!" << std::endl; #endif } outSeqno++; } else { /* cannot auto Ack SynPackets */ pkt -> setAck(inAckno); } pkt -> winsize = inWinSize; /* store old info */ lastSentAck = pkt -> ackno; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt -> writePacket(tmpOutPkt, outPktSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); if (retrans) { /* restart timers */ pkt -> ts = cts; pkt -> retrans = 0; <API key>(); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::toSend() Adding to outPkt --> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif outPkt.push_back(pkt); } else { delete pkt; } return 1; } /* single retransmit timer. * */ void TcpStream::<API key>() { if (retransTimerOn) { return; } retransTimerTs = getCurrentTS(); retransTimerOn = true; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() peer: " << peeraddr; std::cerr << " retransTimeout: " << retransTimeout; std::cerr << " retransTimerTs: " << std::setprecision(12) <<retransTimerTs; std::cerr << std::endl; #endif } void TcpStream::<API key>() { stopRetransmitTimer(); <API key>(); } void TcpStream::stopRetransmitTimer() { if (!retransTimerOn) { return; } #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::stopRetransmitTimer() peer: " << peeraddr; std::cerr << std::endl; #endif retransTimerOn = false; } void TcpStream::<API key>() { retransTimerOn = false; retransTimeout = 2.0 * (rtt_est + 4.0 * rtt_dev); // happens too often for RETRANS debugging. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::<API key>() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } void TcpStream::<API key>() { retransTimeout = 2 * retransTimeout; if (retransTimeout > <API key>) { retransTimeout = <API key>; } #ifdef <API key> std::cerr << "TcpStream::incRetransmitTimer() peer: " << peeraddr; std::cerr << " retransTimeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; #endif } int TcpStream::retrans() { int outPktSize = MAX_SEG + TCP_PSEUDO_HDR_SIZE; char tmpOutPkt[outPktSize]; if (!peerKnown) { /* Major Error! */ #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() peerUnknown ERROR!!!"; std::cerr << std::endl; #endif return 0; } if (!retransTimerOn) { return 0; } double cts = getCurrentTS(); if (cts - retransTimerTs < retransTimeout) { return 0; } if (outPkt.begin() == outPkt.end()) { <API key>(); return 0; } TcpPacket *pkt = outPkt.front(); if (!pkt) { /* error */ return 0; } /* retransmission -> adjust the congestWinSize and congestThreshold */ congestThreshold = congestWinSize / 2; congestWinSize = MAX_SEG; congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::retrans() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif /* update ackno and winsize */ if (!(pkt->hasSyn())) { pkt->setAck(inAckno); lastSentAck = pkt -> ackno; } pkt->winsize = inWinSize; lastSentWinSize = pkt -> winsize; keepAliveTimer = cts; pkt->writePacket(tmpOutPkt, outPktSize); #ifdef <API key> std::cerr << "TcpStream::retrans()"; std::cerr << " peer: " << peeraddr; std::cerr << " hasSyn: " << pkt->hasSyn(); std::cerr << " Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << " Ackno: "; std::cerr << pkt->ackno << " winsize: " << pkt->winsize; std::cerr << " retrans: " << (int) pkt->retrans; std::cerr << " timeout: " << std::setprecision(12) << retransTimeout; std::cerr << std::endl; //std::cerr << printPkt(tmpOutPkt, outPktSize) << std::endl; #endif /* if its a syn packet ** thats been * transmitting for a while, maybe * we should increase the ttl. */ if ((pkt->hasSyn()) && (getTTL() < TCP_STD_TTL)) { /* calculate a new TTL */ if (mTTL_end > cts) { setTTL(<API key>); } else { setTTL(getTTL() + 1); } std::string out; rs_sprintf(out, "TcpStream::retrans() Startup SYNs retrans count: %u New TTL: %d", pkt->retrans, getTTL()); rslog(RSL_WARNING, rstcpstreamzone, out); #ifdef DEBUG_TCP_STREAM std::cerr << out.str() << std::endl; #endif } /* catch excessive retransmits * - Allow Syn case more.... * - if not SYN or TTL has reached STD then timeout quickly. * OLD 2nd Logic (below) has been replaced with lower logic. * (((!pkt->hasSyn()) || (TCP_STD_TTL == getTTL())) * && (pkt->retrans > kMaxPktRetransmit))) * Problem was that the retransmit of Syn packet had STD_TTL, and was triggering Close (and SeqNo change). * It seemed to work anyway.... But might cause coonnection failures. Will reduce the MaxSyn Retransmit * so something more reasonable as well. * ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) */ if ((pkt->hasSyn() && (pkt->retrans > <API key>)) || ((!pkt->hasSyn()) && (pkt->retrans > kMaxPktRetransmit))) { /* too many attempts close stream */ #ifdef <API key> std::cerr << "TcpStream::retrans() Too many Retransmission Attempts ("; std::cerr << (int) pkt->retrans << ") for Peer: " << peeraddr << std::endl; std::cerr << "TcpStream::retrans() Closing Socket Connection"; std::cerr << std::endl; //dumpPacket(std::cerr, (unsigned char *) tmpOutPkt, outPktSize); dumpstate_locked(std::cerr); #endif rslog(RSL_WARNING,rstcpstreamzone,"TcpStream::state => TCP_CLOSED (Too Many Retransmits)"); outStreamActive = false; inStreamActive = false; state = TCP_CLOSED; cleanup(); return 0; } udp -> sendPkt(tmpOutPkt, outPktSize, peeraddr, ttl); /* restart timers */ pkt->ts = cts; pkt->retrans++; /* * finally - double the retransTimeout ... (Karn's Algorithm) * except if we are starting a connection... i.e. hasSyn() */ if (!pkt->hasSyn()) { <API key>(); <API key>(); } else { <API key>(); <API key>(); } return 1; } void TcpStream::acknowledge() { /* cleans up acknowledge packets */ /* packets are pushed back in order */ std::list<TcpPacket *>::iterator it; double cts = getCurrentTS(); bool updateRTT = true; bool clearedPkts = false; for(it = outPkt.begin(); (it != outPkt.end()) && (isOldSequence((*it)->seqno, outAcked)); it = outPkt.erase(it)) { TcpPacket *pkt = (*it); clearedPkts = true; if (!isOldSequence(outAcked, congestUpdate)) { if (congestWinSize < congestThreshold) { /* double it baby! */ congestWinSize *= 2; } else { /* linear increase */ congestWinSize += MAX_SEG; } if (congestWinSize > maxWinSize) { congestWinSize = maxWinSize; } congestUpdate = outAcked + congestWinSize; // point when we can up the winSize. #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Adjusting Congestion Parameters: "; std::cerr << std::endl; std::cerr << "\tcongestWinSize: " << congestWinSize; std::cerr << " congestThreshold: " << congestThreshold; std::cerr << " congestUpdate: " << congestUpdate; std::cerr << std::endl; #endif } /* update the RoundTripTime, * using Jacobson's values. * RTT = a RTT + (1-a) M * where * RTT is RoundTripTime estimate. * a = 7/8, * M = time for ack. * * D = a D + (1 - a) | RTT - M | * where * D is approx Deviation. * a,RTT & M are the same as above. * * Timeout = RTT + 4 * D. * * And Karn's Algorithm... * which says * (1) do not update RTT or D for retransmitted packets. * + the ones that follow .... (the ones whos ack was * delayed by the retranmission) * (2) double timeout, when packets fail. (done in retrans). */ if (pkt->retrans) { updateRTT = false; } if (updateRTT) /* can use for RTT calc */ { double ack_time = cts - pkt->ts; rtt_est = RTT_ALPHA * rtt_est + (1.0 - RTT_ALPHA) * ack_time; rtt_dev = RTT_ALPHA * rtt_dev + (1.0 - RTT_ALPHA) * fabs(rtt_est - ack_time); retransTimeout = rtt_est + 4.0 * rtt_dev; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Updating RTT: "; std::cerr << std::endl; std::cerr << "\tAckTime: " << ack_time; std::cerr << std::endl; std::cerr << "\tRRT_est: " << rtt_est; std::cerr << std::endl; std::cerr << "\tRTT_dev: " << rtt_dev; std::cerr << std::endl; std::cerr << "\tTimeout: " << retransTimeout; std::cerr << std::endl; #endif } #ifdef DEBUG_TCP_STREAM else { std::cerr << "TcpStream::acknowledge() Not Updating RTT for retransmitted Pkt Sequence"; std::cerr << std::endl; } #endif #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() Removing Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif delete pkt; } /* This is triggered if we have recieved acks for retransmitted packets.... * In this case we want to reset the timeout, and remove the doubling. * * If we don't do this, and there have been more dropped packets, * the the timeout gets continually doubled. which will virtually stop * all communication. * * This will effectively trigger the retransmission of the next dropped packet. */ /* * if have acked all data - resetRetransTimer() */ if (it == outPkt.end()) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Backlog cleared, <API key>"; std::cerr << std::endl; #endif <API key>(); } else if (clearedPkts) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::acknowledge() peer: " << peeraddr; std::cerr << " Cleared some packets -> <API key> + start"; std::cerr << std::endl; #endif <API key>(); <API key>(); } return; } int TcpStream::send() { /* handle network interface always */ /* clean up as much as possible */ acknowledge(); /* send any old packets */ retrans(); if (state < TCP_ESTABLISHED) { return -1; } /* get the inQueue, can send */ /* determine exactly how much we can send */ uint32 maxsend = congestWinSize; uint32 inTransit; if (outWinSize < congestWinSize) { maxsend = outWinSize; } if (outSeqno < outAcked) { inTransit = (TCP_MAX_SEQ - outAcked) + outSeqno; } else { inTransit = outSeqno - outAcked; } if (maxsend > inTransit) { maxsend -= inTransit; } else { maxsend = 0; } #ifdef DEBUG_TCP_STREAM int availSend = inQueue.size() * MAX_SEG + inSize; std::cerr << "TcpStream::send() CC: "; std::cerr << "oWS: " << outWinSize; std::cerr << " cWS: " << congestWinSize; std::cerr << " | inT: " << inTransit; std::cerr << " mSnd: " << maxsend; std::cerr << " aSnd: " << availSend; std::cerr << " | oSeq: " << outSeqno; std::cerr << " oAck: " << outAcked; std::cerr << " cUpd: " << congestUpdate; std::cerr << std::endl; #endif int sent = 0; while((inQueue.size() > 0) && (maxsend >= MAX_SEG)) { dataBuffer *db = inQueue.front(); inQueue.pop_front(); TcpPacket *pkt = new TcpPacket(db->data, MAX_SEG); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Segment ===> Seqno: "; std::cerr << pkt->seqno << " size: " << pkt->datasize; std::cerr << std::endl; #endif sent++; maxsend -= MAX_SEG; toSend(pkt); delete db; } /* if inqueue empty, and enough window space, send partial stuff */ if ((!sent) && (inQueue.empty()) && (maxsend >= inSize) && (inSize)) { TcpPacket *pkt = new TcpPacket(inData, inSize); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Remaining ===>"; std::cerr << std::endl; #endif inSize = 0; sent++; maxsend -= inSize; toSend(pkt); } /* if send nothing */ bool needsAck = false; if (!sent) { double cts = getCurrentTS(); /* if needs ack */ if (isOldSequence(lastSentAck,inAckno)) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Ackno)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs window * if added enough space for packet, or * (this case is equivalent to persistence timer) * haven't sent anything for a while, and the * window size has drastically increased. * */ if (((lastSentWinSize < MAX_SEG) && (inWinSize > MAX_SEG)) || ((cts - keepAliveTimer > retransTimeout * 4) && (inWinSize > lastSentWinSize + 4 * MAX_SEG))) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (Window)"; std::cerr << std::endl; #endif needsAck = true; } /* if needs keepalive */ if (cts - keepAliveTimer > keepAliveTimeout) { #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Ack Triggered (KAlive)"; std::cerr << std::endl; #endif needsAck = true; } /* if end of stream -> switch mode -> send fin (with ack) */ if ((!outStreamActive) && (inQueue.size() + inSize == 0) && ((state == TCP_ESTABLISHED) || (state == TCP_CLOSE_WAIT))) { /* finish the stream */ TcpPacket *pkt = new TcpPacket(); pkt -> setFin(); needsAck = false; toSend(pkt, false); #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::send() Fin Triggered"; std::cerr << std::endl; #endif if (state == TCP_ESTABLISHED) { state = TCP_FIN_WAIT_1; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_FIN_WAIT_1"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_FIN_WAIT_1 (End of Stream)"); } else if (state == TCP_CLOSE_WAIT) { state = TCP_LAST_ACK; #ifdef DEBUG_TCP_STREAM std::cerr << "TcpStream::state = TCP_LAST_ACK"; std::cerr << std::endl; #endif rslog(RSL_WARNING, rstcpstreamzone, "TcpStream::state => TCP_LAST_ACK (CLOSE_WAIT, End of Stream)"); } } if (needsAck) { sendAck(); } #ifdef <API key> else { std::cerr << "TcpStream::send() No Ack"; std::cerr << std::endl; } #endif } #ifdef <API key> else { std::cerr << "TcpStream::send() Stuff Sent"; std::cerr << std::endl; } #endif return 1; } uint32 TcpStream::genSequenceNo() { return RSRandom::random_u32(); //return 1000; // TCP_MAX_SEQ - 1000; //1000; //(rand() - 100000) + time(NULL) % 100000; //return (rand() - 100000) + time(NULL) % 100000; } bool TcpStream::isOldSequence(uint32 tst, uint32 curr) { return ((int)((tst)-(curr)) < 0); std::cerr << "TcpStream::isOldSequence(): Case "; /* if tst < curr */ if ((int)((tst)-(curr)) < 0) { if (curr - tst < TCP_MAX_SEQ/2) /* diff less than half span -> old */ { std::cerr << "1T" << std::endl; return true; } std::cerr << "2F" << std::endl; return false; } else if ((tst - curr) > TCP_MAX_SEQ/2) { std::cerr << "3T: tst-curr:" << (tst-curr) << std::endl; return true; } std::cerr << "4F: tst-curr:" << (tst-curr) << std::endl; return false; } #ifdef WINDOWS_SYS #include <time.h> #include <sys/timeb.h> #endif // Little fn to get current timestamp in an independent manner. static double getCurrentTS() { #ifndef WINDOWS_SYS struct timeval cts_tmp; gettimeofday(&cts_tmp, NULL); double cts = (cts_tmp.tv_sec) + ((double) cts_tmp.tv_usec) / 1000000.0; #else struct _timeb timebuf; _ftime( &timebuf); double cts = (timebuf.time) + ((double) timebuf.millitm) / 1000.0; #endif return cts; } uint32 TcpStream::int_wbytes() { return outSeqno - initOurSeqno - 1; } uint32 TcpStream::int_rbytes() { return inAckno - initPeerSeqno - 1; } #ifdef <API key> #include <stdio.h> static FILE *bc_fd = 0; int setupBinaryCheck(std::string fname) { bc_fd = RsDirUtil::rs_fopen(fname.c_str(), "r"); return 1; } /* uses seq number to track position -> ensure no rollover */ int checkData(uint8 *data, int size, int idx) { if (bc_fd <= 0) { return -1; } std::cerr << "checkData(" << idx << "+" << size << ")"; int tmpsize = size; uint8 tmpdata[tmpsize]; if (-1 == fseek(bc_fd, idx, SEEK_SET)) { std::cerr << "Fseek Issues!" << std::endl; exit(1); return -1; } if (1 != fread(tmpdata, tmpsize, 1, bc_fd)) { std::cerr << "Length Difference!" << std::endl; exit(1); return -1; } for(int i = 0; i < size; i++) { if (data[i] != tmpdata[i]) { std::cerr << "Byte Difference!" << std::endl; exit(1); return -1; } } std::cerr << "OK" << std::endl; return 1; } #endif int TcpStream::dumpstate_locked(std::ostream &out) { out << "TcpStream::dumpstate()"; out << "======================================================="; out << std::endl; out << "state: " << (int) state; out << " errorState: " << (int) errorState; out << std::endl; out << "(Streams) inStreamActive: " << inStreamActive; out << " outStreamActive: " << outStreamActive; out << std::endl; out << "(Timeouts) maxWinSize: " << maxWinSize; out << " keepAliveTimeout: " << keepAliveTimeout; out << " retransTimeout: " << retransTimeout; out << std::endl; out << "(Timers) keepAliveTimer: " << std::setprecision(12) << keepAliveTimer; out << " lastIncomingPkt: " << std::setprecision(12) << lastIncomingPkt; out << std::endl; out << "(Tracking) lastSendAck: " << lastSentAck; out << " lastSendWinSize: " << lastSentWinSize; out << std::endl; out << "(Init) initOutSeqno: " << initOurSeqno; out << " initPeerSeqno: " << initPeerSeqno; out << std::endl; out << "(r/w) lastWriteTF: " << lastWriteTF; out << " lastReadTF: " << lastReadTF; out << " wcount: " << wcount; out << " rcount: " << rcount; out << std::endl; out << "(rtt) rtt_est: " << rtt_est; out << " rtt_dev: " << rtt_dev; out << std::endl; out << "(congestion) congestThreshold: " << congestThreshold; out << " congestWinSize: " << congestWinSize; out << " congestUpdate: " << congestUpdate; out << std::endl; out << "(TTL) mTTL_period: " << mTTL_period; out << " mTTL_start: " << std::setprecision(12) << mTTL_start; out << " mTTL_end: " << std::setprecision(12) << mTTL_end; out << std::endl; out << "(Peer) peerKnown: " << peerKnown; out << " peerAddr: " << peeraddr; out << std::endl; out << " out << std::endl; status_locked(out); out << "======================================================="; out << std::endl; return 1; } int TcpStream::dumpstate(std::ostream &out) { tcpMtx.lock(); dumpstate_locked(out); tcpMtx.unlock(); return 1; } int dumpPacket(std::ostream &out, unsigned char *pkt, uint32_t size) { uint32_t i; out << "dumpPacket() Size: " << size; out << std::endl; out << " for(i = 0; i < size; i++) { if (i % 16 == 0) { out << std::endl; } out << std::hex << std::setfill('0') << std::setw(2) << (int) pkt[i] << ":"; } if ((i - 1) % 16 != 0) { out << std::endl; } out << " out << std::dec << std::endl; return 1; }
<?php defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' ); jimport('joomla.application.component.controllerform'); /** * Maintenance Controller * * @package CSVIVirtueMart */ class <API key> extends JControllerForm { public function Maintenance() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); $view->setModel( $this->getModel( 'availablefields', 'CsviModel' )); // View if (!JRequest::getBool('cron', false)) { if (JRequest::getInt('run_id') > 0) $view->setLayout('log'); } else $view->setLayout('cron'); // Now display the view $view->display(); } private function _outputHtml() { $this->setRedirect('index.php?option=com_csvi&task=maintenance.maintenance&run_id='.JRequest::getInt('import_id')); } private function _outputCron() { // Create the view object $view = $this->getView('maintenance', 'html'); // Standard model $view->setModel( $this->getModel( 'maintenance', 'CsviModel' ), true ); // Extra models $view->setModel( $this->getModel( 'log', 'CsviModel' )); // View $view->setLayout('cron'); // Now display the view $view->display(); } public function <API key>() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model-><API key>(); // Check if we are running a cron job if ($jinput->get('cron', false, 'bool')) { // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields-><API key>(); // Update the available fields $available_fields-><API key>(); // Finish $model->getFinishProcess(); // Redirect $this->_outputCron(); } else { // Create the view object $view = $this->getView('maintenance', 'json'); // Pre-configuration $available_fields = $this->getModel('availablefields', 'CsviModel'); $available_fields-><API key>(); // View $view->setLayout('availablefields'); // Now display the view $view->display(); } } public function <API key>() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('availablefields'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel('availablefields', 'CsviModel')); // Now display the view $view->display(); } public function <API key>() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model-><API key>(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function sortCategories() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getSortCategories(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function <API key>() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model-><API key>(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function exchangeRates() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getExchangeRates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function cleanTemp() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getCleanTemp(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function backupTemplates() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getBackupTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function restoreTemplates() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getRestoreTemplates(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function icecatIndex() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Check if we are running a cron job if (JRequest::getBool('cron', false)) { JRequest::setVar('loadtype', false); } // Perform the task $result = $model->getIcecatIndex(); // See if we need to do the staggered import of the index file switch ($result) { case 'full': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; case 'single': // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Now display the view $view->display(); break; case 'cancel': // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); break; } } public function icecatSingle() { // Create the view object $view = $this->getView('maintenance', 'json'); // View $view->setLayout('icecat'); // Load the model $view->setModel($this->getModel('maintenance', 'CsviModel'), true); $view->setModel($this->getModel( 'log', 'CsviModel' )); // Now display the view $view->display(); } public function optimizeTables() { // Prepare $jinput = JFactory::getApplication()->input; $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getOptimizeTables(); // Finish $model->getFinishProcess(); // Redirect if (!$jinput->get('cron', false, 'bool')) $this->_outputHtml(); else $this->_outputCron(); } public function backupVm() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getBackupVirtueMart(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function emptyDatabase() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->getEmptyDatabase(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function <API key>() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model-><API key>(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } public function cancelImport() { // Clean the session $session = JFactory::getSession(); $option = JRequest::getVar('option'); $session->set($option.'.icecat_index_file', serialize('0')); $session->set($option.'.icecat_rows', serialize('0')); $session->set($option.'.icecat_position', serialize('0')); $session->set($option.'.icecat_records', serialize('0')); $session->set($option.'.icecat_wait', serialize('0')); // Redirect back to the maintenance page $this->setRedirect('index.php?option='.JRequest::getCmd('option').'&view=maintenance'); } public function removeCsviTables() { // Prepare $model = $this->getModel('maintenance'); $model-><API key>(); // Perform the task $model->removeCsviTables(); // Finish $model->getFinishProcess(); // Redirect if (!JRequest::getBool('cron', false)) $this->_outputHtml(); else $this->_outputCron(); } } ?>
source ./templates/support.sh populate var_<API key> if grep -q "remember=" /etc/pam.d/system-auth; then sed -i --follow-symlink "s/\(remember *= *\).*/\1$var_<API key>/" /etc/pam.d/system-auth else sed -i --follow-symlink "/^password[[:space:]]\+sufficient[[:space:]]\+pam_unix.so/ s/$/ remember=$var_<API key>/" /etc/pam.d/system-auth fi
package net.pms.encoders; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.<API key>; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.DeviceConfiguration; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.<API key>; import net.pms.dlna.*; import net.pms.formats.Format; import net.pms.io.*; import net.pms.newgui.GuiUtil; import net.pms.util.CodecUtil; import net.pms.util.FormLayoutUtil; import net.pms.util.PlayerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TsMuxeRVideo extends Player { private static final Logger LOGGER = LoggerFactory.getLogger(TsMuxeRVideo.class); private static final String COL_SPEC = "left:pref, 0:grow"; private static final String ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, 0:grow"; public static final String ID = "tsmuxer"; @Deprecated public TsMuxeRVideo(PmsConfiguration configuration) { this(); } public TsMuxeRVideo() { } @Override public boolean excludeFormat(Format format) { String extension = format.getMatchedExtension(); return extension != null && !extension.equals("mp4") && !extension.equals("mkv") && !extension.equals("ts") && !extension.equals("tp") && !extension.equals("m2ts") && !extension.equals("m2t") && !extension.equals("mpg") && !extension.equals("evo") && !extension.equals("mpeg") && !extension.equals("vob") && !extension.equals("m2v") && !extension.equals("mts") && !extension.equals("mov"); } @Override public int purpose() { return <API key>; } @Override public String id() { return ID; } @Override public boolean isTimeSeekable() { return true; } @Override public String[] args() { return null; } @Override public String executable() { return configuration.getTsmuxerPath(); } @Override public ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { // Use device-specific pms conf PmsConfiguration prev = configuration; configuration = (DeviceConfiguration) params.mediaRenderer; final String filename = dlna.getSystemName(); setAudioAndSubs(filename, media, params); PipeIPCProcess ffVideoPipe; ProcessWrapperImpl ffVideo; PipeIPCProcess ffAudioPipe[] = null; ProcessWrapperImpl ffAudio[] = null; String fps = media.getValidFps(false); int width = media.getWidth(); int height = media.getHeight(); if (width < 320 || height < 240) { width = -1; height = -1; } String videoType = "V_MPEG4/ISO/AVC"; if (media.getCodecV() != null && media.getCodecV().startsWith("mpeg2")) { videoType = "V_MPEG-2"; } boolean aacTranscode = false; String[] ffmpegCommands; if (this instanceof TsMuxeRAudio && media.getFirstAudioTrack() != null) { ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "fakevideo", System.currentTimeMillis() + "videoout", false, true); String timeEndValue1 = "-t"; String timeEndValue2 = "" + params.timeend; if (params.timeend < 1) { timeEndValue1 = "-y"; timeEndValue2 = "-y"; } ffmpegCommands = new String[] { configuration.getFfmpegPath(), timeEndValue1, timeEndValue2, "-loop", "1", "-i", "DummyInput.jpg", "-f", "h264", "-c:v", "libx264", "-level", "31", "-tune", "zerolatency", "-pix_fmt", "yuv420p", "-an", "-y", ffVideoPipe.getInputPipe() }; videoType = "V_MPEG4/ISO/AVC"; OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); if ( filename.toLowerCase().endsWith(".flac") && media.getFirstAudioTrack().getBitsperSample() >= 24 && media.getFirstAudioTrack().getSampleRate() % 48000 == 0 ) { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "flacaudio", System.currentTimeMillis() + "audioout", false, true); String[] flacCmd = new String[] { configuration.getFlacPath(), "--output-name=" + ffAudioPipe[0].getInputPipe(), "-d", "-f", "-F", filename }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } else { ffAudioPipe = new PipeIPCProcess[1]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "mlpaudio", System.currentTimeMillis() + "audioout", false, true); String depth = "pcm_s16le"; String rate = "48000"; if (media.getFirstAudioTrack().getBitsperSample() >= 24) { depth = "pcm_s24le"; } if (media.getFirstAudioTrack().getSampleRate() > 48000) { rate = "" + media.getFirstAudioTrack().getSampleRate(); } String[] flacCmd = new String[] { configuration.getFfmpegPath(), "-i", filename, "-ar", rate, "-f", "wav", "-acodec", depth, "-y", ffAudioPipe[0].getInputPipe() }; ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffAudio = new ProcessWrapperImpl[1]; ffAudio[0] = new ProcessWrapperImpl(flacCmd, ffparams); } } else { params.waitbeforestart = 5000; params.manageFastStart(); ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-c", "copy", "-f", "rawvideo", "-y", ffVideoPipe.getInputPipe() }; InputFile newInput = new InputFile(); newInput.setFilename(filename); newInput.setPush(params.stdin); /** * Note: This logic is weird; on one hand we check if the renderer requires videos to be Level 4.1 or below, but then * the other function allows the video to exceed those limits. * In reality this won't cause problems since renderers typically don't support above 4.1 anyway - nor are many * videos encoded higher than that either - but it's worth acknowledging the logic discrepancy. */ if (!media.<API key>(newInput, params.mediaRenderer) && params.mediaRenderer.<API key>()) { LOGGER.info("The video will not play or will show a black screen"); } if (media.getH264AnnexB() != null && media.getH264AnnexB().length > 0) { StreamModifier sm = new StreamModifier(); sm.setHeader(media.getH264AnnexB()); sm.setH264AnnexB(true); ffVideoPipe.setModifier(sm); } OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffVideo = new ProcessWrapperImpl(ffmpegCommands, ffparams); int numAudioTracks = 1; if (media.getAudioTracksList() != null && media.getAudioTracksList().size() > 1 && configuration.isMuxAllAudioTracks()) { numAudioTracks = media.getAudioTracksList().size(); } boolean singleMediaAudio = media.getAudioTracksList().size() <= 1; if (params.aid != null) { boolean ac3Remux; boolean dtsRemux; boolean <API key>; boolean pcm; if (numAudioTracks <= 1) { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudioPipe[0] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); <API key> = configuration.<API key>() && params.aid.<API key>() && params.mediaRenderer.<API key>(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !<API key> && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.<API key>() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !<API key>; pcm = configuration.isAudioUsePCM() && media.<API key>() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.<API key>() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || <API key>) { channels = 2; } else if (pcm) { channels = params.aid.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.<API key>(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || <API key>)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.<API key>(<API key>); sm.setNbChannels(channels); sm.setSampleFrequency(params.aid.getSampleRate() < 48000 ? 48000 : params.aid.getSampleRate()); sm.setBitsPerSample(16); ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", "-c:a", sm.isDtsEmbed() || sm.<API key>() ? "copy" : "pcm", "-y", ffAudioPipe[0].getInputPipe() }; // Use PCM trick when media renderer does not support DTS in MPEG if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[0].setModifier(sm); } } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[0].getInputPipe() }; aacTranscode = true; } else { // AC-3 audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, params.aid)) + "k", "-y", ffAudioPipe[0].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio = new ProcessWrapperImpl[numAudioTracks]; ffAudio[0] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } else { ffAudioPipe = new PipeIPCProcess[numAudioTracks]; ffAudio = new ProcessWrapperImpl[numAudioTracks]; for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio audio = media.getAudioTracksList().get(i); ffAudioPipe[i] = new PipeIPCProcess(System.currentTimeMillis() + "ffmpeg" + i, System.currentTimeMillis() + "audioout" + i, false, true); <API key> = configuration.<API key>() && params.aid.<API key>() && params.mediaRenderer.<API key>(); ac3Remux = audio.isAC3() && configuration.isAudioRemuxAC3() && !<API key> && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.<API key>() && audio.isDTS() && params.mediaRenderer.isDTSPlayable() && !<API key>; pcm = configuration.isAudioUsePCM() && media.<API key>() && ( audio.isLossless() || (audio.isDTS() && audio.getAudioProperties().getNumberOfChannels() <= 6) || audio.isTrueHD() || ( !configuration.<API key>() && ( audio.isAC3() || audio.isMP3() || audio.isAAC() || audio.isVorbis() || // audio.isWMA() || audio.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); int channels; if (ac3Remux) { channels = audio.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux || <API key>) { channels = 2; } else if (pcm) { channels = audio.getAudioProperties().getNumberOfChannels(); } else { channels = configuration.<API key>(); // 5.1 max for AC-3 encoding } if (!ac3Remux && (dtsRemux || pcm || <API key>)) { // DTS remux or LPCM StreamModifier sm = new StreamModifier(); sm.setPcm(pcm); sm.setDtsEmbed(dtsRemux); sm.<API key>(<API key>); sm.setNbChannels(channels); sm.setSampleFrequency(audio.getSampleRate() < 48000 ? 48000 : audio.getSampleRate()); sm.setBitsPerSample(16); if (!params.mediaRenderer.isMuxDTSToMpeg()) { ffAudioPipe[i].setModifier(sm); } ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + sm.getNbChannels(), "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", sm.isDtsEmbed() || sm.<API key>() ? "copy" : "pcm", "-y", ffAudioPipe[i].getInputPipe() }; } else if (!ac3Remux && params.mediaRenderer.isTranscodeToAAC()) { // AAC audio ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "adts", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", "aac", "-strict", "experimental", "-ab", Math.min(configuration.getAudioBitrate(), 320) + "k", "-y", ffAudioPipe[i].getInputPipe() }; aacTranscode = true; } else { // AC-3 remux or encoding ffmpegCommands = new String[] { configuration.getFfmpegPath(), "-ss", params.timeseek > 0 ? "" + params.timeseek : "0", "-i", filename, "-ac", "" + channels, "-f", "ac3", singleMediaAudio ? "-y" : "-map", singleMediaAudio ? "-y" : ("0:a:" + (media.getAudioTracksList().indexOf(audio))), "-c:a", (ac3Remux) ? "copy" : "ac3", "-ab", String.valueOf(CodecUtil.getAC3Bitrate(configuration, audio)) + "k", "-y", ffAudioPipe[i].getInputPipe() }; } ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; ffAudio[i] = new ProcessWrapperImpl(ffmpegCommands, ffparams); } } } } File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); params.log = false; try (PrintWriter pw = new PrintWriter(f)) { pw.print("MUXOPT --no-pcr-on-video-pid"); pw.print(" --new-audio-pes"); pw.print(" --no-asyncio"); pw.print(" --vbr"); pw.println(" --vbv-len=500"); String sei = "insertSEI"; if ( params.mediaRenderer.isPS3() && media.isWebDl(filename, params) ) { sei = "forceSEI"; } String videoparams = "level=4.1, " + sei + ", contSPS, track=1"; if (this instanceof TsMuxeRAudio) { videoparams = "track=224"; } if (configuration.<API key>()) { fps = "25"; } pw.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + (fps != null ? ("fps=" + fps + ", ") : "") + (width != -1 ? ("video-width=" + width + ", ") : "") + (height != -1 ? ("video-height=" + height + ", ") : "") + videoparams); if (ffAudioPipe != null && ffAudioPipe.length == 1) { String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean <API key>; boolean pcm; <API key> = configuration.<API key>() && params.aid.<API key>() && params.mediaRenderer.<API key>(); ac3Remux = params.aid.isAC3() && configuration.isAudioRemuxAC3() && !<API key> && !params.mediaRenderer.isTranscodeToAAC(); dtsRemux = configuration.<API key>() && params.aid.isDTS() && params.mediaRenderer.isDTSPlayable() && !<API key>; pcm = configuration.isAudioUsePCM() && media.<API key>() && ( params.aid.isLossless() || (params.aid.isDTS() && params.aid.getAudioProperties().getNumberOfChannels() <= 6) || params.aid.isTrueHD() || ( !configuration.<API key>() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else if (aacTranscode) { type = "A_AAC"; } else { if (pcm || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (<API key> || this instanceof TsMuxeRAudio) { type = "A_LPCM"; } if (dtsRemux || this instanceof TsMuxeRAudio) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (params.aid != null && params.aid.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + params.aid.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[0].getOutputPipe() + "\", " + timeshift + "track=2"); } else if (ffAudioPipe != null) { for (int i = 0; i < media.getAudioTracksList().size(); i++) { DLNAMediaAudio lang = media.getAudioTracksList().get(i); String timeshift = ""; boolean ac3Remux; boolean dtsRemux; boolean <API key>; boolean pcm; <API key> = configuration.<API key>() && params.aid.<API key>() && params.mediaRenderer.<API key>(); ac3Remux = lang.isAC3() && configuration.isAudioRemuxAC3() && !<API key>; dtsRemux = configuration.<API key>() && lang.isDTS() && params.mediaRenderer.isDTSPlayable() && !<API key>; pcm = configuration.isAudioUsePCM() && media.<API key>() && ( lang.isLossless() || (lang.isDTS() && lang.getAudioProperties().getNumberOfChannels() <= 6) || lang.isTrueHD() || ( !configuration.<API key>() && ( params.aid.isAC3() || params.aid.isMP3() || params.aid.isAAC() || params.aid.isVorbis() || // params.aid.isWMA() || params.aid.isMpegAudio() ) ) ) && params.mediaRenderer.isLPCMPlayable(); String type = "A_AC3"; if (ac3Remux) { // AC-3 remux takes priority type = "A_AC3"; } else { if (pcm) { type = "A_LPCM"; } if (<API key>) { type = "A_LPCM"; } if (dtsRemux) { type = "A_LPCM"; if (params.mediaRenderer.isMuxDTSToMpeg()) { type = "A_DTS"; } } } if (lang.getAudioProperties().getAudioDelay() != 0 && params.timeseek == 0) { timeshift = "timeshift=" + lang.getAudioProperties().getAudioDelay() + "ms, "; } pw.println(type + ", \"" + ffAudioPipe[i].getOutputPipe() + "\", " + timeshift + "track=" + (2 + i)); } } } PipeProcess tsPipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); /** * Use the newer version of tsMuxeR on PS3 since other renderers * like Panasonic TVs don't always recognize the new output */ String executable = executable(); if (params.mediaRenderer.isPS3()) { executable = configuration.getTsmuxerNewPath(); } String[] cmdArray = new String[]{ executable, f.getAbsolutePath(), tsPipe.getInputPipe() }; cmdArray = <API key>( filename, dlna, media, params, cmdArray ); ProcessWrapperImpl p = new ProcessWrapperImpl(cmdArray, params); params.maxBufferSize = 100; params.input_pipes[0] = tsPipe; params.stdin = null; ProcessWrapper pipe_process = tsPipe.getPipeProcess(); p.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (<API key> e) { } tsPipe.deleteLater(); ProcessWrapper ff_pipe_process = ffVideoPipe.getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (<API key> e) { } ffVideoPipe.deleteLater(); p.attachProcess(ffVideo); ffVideo.runInNewThread(); try { Thread.sleep(50); } catch (<API key> e) { } if (ffAudioPipe != null && params.aid != null) { for (int i = 0; i < ffAudioPipe.length; i++) { ff_pipe_process = ffAudioPipe[i].getPipeProcess(); p.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (<API key> e) { } ffAudioPipe[i].deleteLater(); p.attachProcess(ffAudio[i]); ffAudio[i].runInNewThread(); } } try { Thread.sleep(100); } catch (<API key> e) { } p.runInNewThread(); configuration = prev; return p; } @Override public String mimeType() { return "video/mpeg"; } @Override public String name() { return "tsMuxeR"; } @Override public int type() { return Format.VIDEO; } private JCheckBox tsmuxerforcefps; private JCheckBox muxallaudiotracks; @Override public JComponent config() { // Apply the orientation for the locale <API key> orientation = <API key>.getOrientation(PMS.getLocale()); String colSpec = FormLayoutUtil.getColSpec(COL_SPEC, orientation); FormLayout layout = new FormLayout(colSpec, ROW_SPEC); PanelBuilder builder = new PanelBuilder(layout); builder.border(Borders.EMPTY); builder.opaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(2, 1, 1), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); tsmuxerforcefps = new JCheckBox(Messages.getString("TsMuxeRVideo.2"), configuration.isTsmuxerForceFps()); tsmuxerforcefps.<API key>(false); tsmuxerforcefps.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setTsmuxerForceFps(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.<API key>(tsmuxerforcefps), FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation)); muxallaudiotracks = new JCheckBox(Messages.getString("TsMuxeRVideo.19"), configuration.isMuxAllAudioTracks()); muxallaudiotracks.<API key>(false); muxallaudiotracks.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.<API key>(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(GuiUtil.<API key>(muxallaudiotracks), FormLayoutUtil.flip(cc.xy(2, 5), colSpec, orientation)); JPanel panel = builder.getPanel(); // Apply the orientation to the panel and all components in it panel.<API key>(orientation); return panel; } @Override public boolean <API key>() { return false; } @Override public boolean <API key>() { return false; } @Override public boolean isPlayerCompatible(<API key> mediaRenderer) { return mediaRenderer != null && mediaRenderer.isMuxH264MpegTS(); } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { DLNAMediaSubtitle subtitle = resource.getMediaSubtitle(); // Check whether the subtitle actually has a language defined, // uninitialized DLNAMediaSubtitle objects have a null language. if (subtitle != null && subtitle.getLang() != null) { // The resource needs a subtitle, but PMS does not support subtitles for tsMuxeR. return false; } try { String audioTrackName = resource.getMediaAudio().toString(); String <API key> = resource.getMedia().getAudioTracksList().get(0).toString(); if (!audioTrackName.equals(<API key>)) { // PMS only supports playback of the default audio track for tsMuxeR return false; } } catch (<API key> e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on audio track for " + resource.getSystemName()); } catch (<API key> e) { LOGGER.trace("tsMuxeR cannot determine compatibility based on default audio track for " + resource.getSystemName()); } if ( PlayerUtil.isVideo(resource, Format.Identifier.MKV) || PlayerUtil.isVideo(resource, Format.Identifier.MPG) ) { return true; } return false; } }
#include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/pm.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/wakelock.h> /* wake_lock, unlock */ #include <mach/board_lge.h> #include "../../<API key>.h" #include "../inc/broadcast_t3900.h" struct <API key> { int pwr_state; struct wake_lock wakelock; struct i2c_client* pclient; struct <API key>* pctrl_fun; /* defined in board_lge.h */ }; static struct <API key> TdmbCtrlInfo; static uint32 user_stop_flg = 0; static uint32 mdelay_in_flg = 0; struct i2c_client* INC_GET_I2C_DRIVER(void) { return TdmbCtrlInfo.pclient; } void <API key>(void) { user_stop_flg = ((mdelay_in_flg == 1)? 1: 0 ); } int tdmb_t3900_mdelay(int32 ms) { int rc = 1; /* 0 : false, 1 : ture */ #if 1 int32 wait_loop =0; int32 wait_ms = ms; if(ms > 100) { wait_loop = (ms /100); /* 100, 200, 300 more only , Otherwise this must be modified e.g (ms + 40)/50 */ wait_ms = 100; } mdelay_in_flg = 1; do { msleep(wait_ms); if(user_stop_flg == 1) { printk("~~~~~~~~ Ustop flag is set so return false ~~~~~~~~\n"); rc = 0; break; } }while((--wait_loop) > 0); mdelay_in_flg = 0; user_stop_flg = 0; #else msleep(ms); #endif if(rc == 0) { printk("tdmb_t3900_delay return abnormal\n"); } return rc; } void <API key>(int32 ms) { msleep(ms); } int tdmb_t3900_power_on(void) { /* if(TdmbCtrlInfo.pwr_state == 1) { printk("tdmb_t3900_power is immediately on\n"); return TRUE; } */ if((TdmbCtrlInfo.pctrl_fun == NULL) ||(TdmbCtrlInfo.pctrl_fun->dmb_power_on == NULL)) { printk("tdmb_t3900_power_on function NULL\n"); return FALSE; } wake_lock(&TdmbCtrlInfo.wakelock); TdmbCtrlInfo.pctrl_fun->dmb_power_on( ); TdmbCtrlInfo.pwr_state = 1; return TRUE; } int <API key>(void) { if(TdmbCtrlInfo.pwr_state == 0) { printk("tdmb_t3900_power is immediately off\n"); return TRUE; } if((TdmbCtrlInfo.pctrl_fun == NULL) ||(TdmbCtrlInfo.pctrl_fun->dmb_power_off == NULL)) { printk("<API key> function NULL\n"); return FALSE; } TdmbCtrlInfo.pwr_state = 0; TdmbCtrlInfo.pctrl_fun->dmb_power_off( ); wake_unlock(&TdmbCtrlInfo.wakelock); return TRUE; } int <API key>(unsigned int sel) { return FALSE; } static int <API key>(uint8* txdata, int length) { int rc; struct i2c_msg msg = { TdmbCtrlInfo.pclient->addr, 0, length, txdata }; //if(i2c_transfer(TdmbCtrlInfo.pclient->adapter, &msg, 1) < 0) rc = i2c_transfer(TdmbCtrlInfo.pclient->adapter, &msg, 1); if(rc < 0) { printk("<API key> fail rc = (%d) addr =(0x%X)\n", rc, TdmbCtrlInfo.pclient->addr); return FALSE; } return TRUE; } int <API key>(uint16 waddr, uint8* wdata, int length) { uint8* buf; int wlen; int rc; /* success : 1 , fail : 0 */ wlen = length + 2; buf = (uint8*)kmalloc(wlen, GFP_KERNEL); if((buf == NULL) || (length <= 0)) { printk("<API key> buf alloc fail\n"); return FALSE; } buf[0] = (waddr>>8)&0xFF; buf[1] = (waddr&0xFF); memcpy(&buf[2], wdata, length); rc = <API key>(buf, wlen); kfree(buf); return rc; } static int tdmb_t3900_i2c_read( uint16 raddr, uint8 *rxdata, int length) { int rc; uint8 r_addr[2] = {raddr>>8, raddr&0xFF}; struct i2c_msg msgs[2] = { { .addr = TdmbCtrlInfo.pclient->addr, .flags = 0, .len = 2, .buf = &r_addr[0], }, { .addr = TdmbCtrlInfo.pclient->addr, .flags = I2C_M_RD, .len = length, .buf = rxdata, }, }; //if (i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2) < 0) rc = i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2); if(rc < 0) { printk("tdmb_t3900_i2c_read failed! rc =(%d),%x \n", rc, TdmbCtrlInfo.pclient->addr); return FALSE; } return TRUE; }; int <API key>(uint16 raddr, uint8* rdata, int length) { int rc; rc = tdmb_t3900_i2c_read(raddr, rdata, length); return rc; } int <API key>(unsigned short reg, unsigned short val) { int err; unsigned char buf[4] = { reg>>8, reg&0xff, val>>8, val&0xff }; struct i2c_msg msg = { TdmbCtrlInfo.pclient->addr, 0, 4, buf }; if ((err = i2c_transfer( TdmbCtrlInfo.pclient->adapter, &msg, 1)) < 0) { dev_err(&TdmbCtrlInfo.pclient->dev, "i2c write error\n"); err = FALSE; } else { //printk(KERN_INFO "tdmb : i2c write ok:addr = %x data = %x\n", reg, val); err = TRUE; } return err; } int <API key>(uint16 reg, uint16 *ret) { int err; uint8 w_buf[2] = {reg>>8, reg&0xff}; uint8 r_buf[2] = {0,0}; struct i2c_msg msgs[2] = { { .addr = TdmbCtrlInfo.pclient->addr, .flags = 0, .len = 2, .buf = &w_buf[0], }, { .addr = TdmbCtrlInfo.pclient->addr, .flags = I2C_M_RD, .len = 2, .buf = &r_buf[0], }, }; if ((err = i2c_transfer(TdmbCtrlInfo.pclient->adapter, msgs, 2)) < 0) { dev_err(&TdmbCtrlInfo.pclient->dev, "i2c read error\n"); err = FALSE; } else { //printk( "tdmb addr = %x : i2c read ok: data[0] = %x data[1] = %x \n", TdmbCtrlInfo.pClient->addr, r_buf[0], r_buf[1]); *ret = r_buf[0]<<8 | r_buf[1]; //printk( "tdmb : i2c read ok: data = %x\n", *ret); err = TRUE; } return err; } void tdmb_rw_test(void) { unsigned short i = 0; unsigned short w_val = 0; unsigned short r_val = 0; unsigned short err_cnt = 0; err_cnt = 0; for(i=1;i<11;i++) { w_val = (i%0xFF); <API key>( 0x0a00+ 0x05, w_val); <API key>(0x0a00+ 0x05, &r_val ); if(r_val != w_val) { err_cnt++; printk("w_val:%x, r_val:%x\n", w_val,r_val); } } } static int <API key>(struct i2c_client *client, const struct i2c_device_id *id) { int rc; struct <API key> *pdata; memset((void*)&TdmbCtrlInfo, 0x00, sizeof(struct <API key>)); printk("<API key>( )\n"); if(!<API key>(client->adapter, I2C_FUNC_I2C)) { printk(KERN_ERR "<API key>: need I2C_FUNC_I2C\n"); rc = -ENODEV; return rc; } TdmbCtrlInfo.pclient = client; i2c_set_clientdata(client, (void*)&TdmbCtrlInfo); /* Register power control function */ TdmbCtrlInfo.pwr_state = 0; pdata = (struct <API key>*)client->dev.platform_data; TdmbCtrlInfo.pctrl_fun = pdata; if(TdmbCtrlInfo.pctrl_fun && TdmbCtrlInfo.pctrl_fun->dmb_gpio_init) { TdmbCtrlInfo.pctrl_fun->dmb_gpio_init( ); } else { printk("<API key> dmb_gpio_init is not called\n"); } wake_lock_init(&TdmbCtrlInfo.wakelock, WAKE_LOCK_SUSPEND, dev_name(&client->dev)); return OK; } static int <API key>(struct i2c_client* client) { printk("<API key> is called\n"); wake_lock_destroy(&TdmbCtrlInfo.wakelock); return OK; } static const struct i2c_device_id tdmb_t3900_id[] = { {"tdmb_t3900", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, tdmb_t3900_id); static struct i2c_driver t3900_i2c_driver = { .probe = <API key>, .remove = <API key>, .id_table = tdmb_t3900_id, .driver = { .name = "tdmb_t3900", .owner = THIS_MODULE, }, }; int __devinit <API key>(void) { int rc; printk("<API key>\n"); rc = <API key>(); if (rc) { printk("<API key> %s failed to load\n", __func__); return rc; } rc = i2c_add_driver(&t3900_i2c_driver); printk("<API key> rc = (%d)\n", rc); return rc; } static void __exit <API key>(void) { i2c_del_driver(&t3900_i2c_driver); } /* EXPORT_SYMBOL() : when we use external symbol which is not included in current module - over kernel 2.6 */ //EXPORT_SYMBOL(<API key>); module_init(<API key>); module_exit(<API key>); MODULE_DESCRIPTION("<API key>"); MODULE_LICENSE("INC");
<html> <head> <title>XPP - 3D PARAMETERS</title> </head> <body bgcolor="#ffffff" link="#330099" alink="#FF3300" vlink="#330099"> <a href="xpprestore.html">Back</a> | <a href="xppbdry.html">Next</a> | <a href="xpphelp.html">Contents</a> <hr> <h1>3d params</h1>Brings up a dialog box allowing you to rotate the axes in three-dimensional plots and make animations. The items are: <br><ul> <li><b>theta</b>, the angle about the <font color=#77aa00> z-axis </font> to use this. <li><b>phi</b>, the angle about the <font color=#77aa00> y-axis </font> <li><b>Movie</b> set this to 1 if you want to create a little movie in which the box rotates about one of the two principle axes. <li> Choose which angle you want to rotate about: <font color=#77aa00>theta or phi</font> <li> Choose the starting angle <li> Choose the increment <li> Choose the number of frames </ul><p>If you select <b> Movie </b> then a series of frames will be drawn. You can use the <a href="xppkine.html"> Kinescope </a> command to play these back or save them in an animated gif file.<p>
<?php /** * Template Name: Template Content Sidebar Sidebar * * Page template for * * @package Openstrap * @since Openstrap 0.1 */ get_header(); ?> <!-- Main Content --> <div class="col-md-6" role="main"> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; ?> <?php else : ?> <h2><?php _e('No posts.', 'openstrap' ); ?></h2> <p class="lead"><?php _e('Sorry about this, I couldn\'t seem to find what you were looking for.', 'openstrap' ); ?></p> <?php endif; ?> <?php <API key>(); ?> </div> <!-- End Main Content --> <?php get_sidebar('left'); ?> <?php get_sidebar(); ?> <?php get_footer(); ?>
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace STSdb4.Data { public class DataComparer : IComparer<IData> { public readonly Func<IData, IData, int> compare; public readonly Type Type; public readonly Type DataType; public readonly CompareOption[] CompareOptions; public readonly Func<Type, MemberInfo, int> MembersOrder; public DataComparer(Type type, CompareOption[] compareOptions, Func<Type, MemberInfo, int> membersOrder = null) { Type = type; DataType = typeof(Data<>).MakeGenericType(type); CompareOption.CheckCompareOptions(type, compareOptions, membersOrder); CompareOptions = compareOptions; MembersOrder = membersOrder; compare = CreateCompareMethod().Compile(); } public DataComparer(Type type, Func<Type, MemberInfo, int> membersOrder = null) : this(type, CompareOption.<API key>(type, membersOrder), membersOrder) { } public Expression<Func<IData, IData, int>> CreateCompareMethod() { var x = Expression.Parameter(typeof(IData)); var y = Expression.Parameter(typeof(IData)); List<Expression> list = new List<Expression>(); List<ParameterExpression> parameters = new List<ParameterExpression>(); var value1 = Expression.Variable(Type, "value1"); parameters.Add(value1); list.Add(Expression.Assign(value1, Expression.Convert(x, DataType).Value())); var value2 = Expression.Variable(Type, "value2"); parameters.Add(value2); list.Add(Expression.Assign(value2, Expression.Convert(y, DataType).Value())); return Expression.Lambda<Func<IData, IData, int>>(ComparerHelper.CreateComparerBody(list, parameters, value1, value2, CompareOptions, MembersOrder), x, y); } public int Compare(IData x, IData y) { return compare(x, y); } } }
/* $Id: macucs.c 5322 2005-02-16 23:30:10Z owen $ */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include "putty.h" #include "charset.h" #include "terminal.h" #include "misc.h" #include "mac.h" /* * Mac Unicode-handling routines. * * BJH: * What we _should_ do is to use the Text Encoding Conversion Manager * when it's available, and have our own routines for converting to * standard Mac OS scripts when it's not. Support for ATSUI might be * nice, too. * * I (OSD) am unsure any of the above is necessary if we just use * libcharset */ /* * Determine whether a byte is the first byte of a double-byte * character in a system character set. Only MI use is by clipme() * when copying direct-to-font text to the clipboard. */ int is_dbcs_leadbyte(int codepage, char byte) { return 0; /* we don't do DBCS */ } /* * Convert from Unicode to a system character set. MI uses are: * (1) by lpage_send(), whose only MI use is to convert the answerback * string to Unicode, and * (2) by clipme() when copying direct-to-font text to the clipboard. */ int mb_to_wc(int codepage, int flags, char *mbstr, int mblen, wchar_t *wcstr, int wclen) { int ret = 0; while (mblen > 0 && wclen > 0) { *wcstr++ = (unsigned char) *mbstr++; mblen--, wclen--, ret++; } return ret; /* FIXME: check error codes! */ } /* * Convert from a system character set to Unicode. Used by luni_send * to convert Unicode into the line character set. */ int wc_to_mb(int codepage, int flags, wchar_t *wcstr, int wclen, char *mbstr, int mblen, char *defchr, int *defused, struct unicode_data *ucsdata) { int ret = 0; if (defused) *defused = 0; while (mblen > 0 && wclen > 0) { if (*wcstr >= 0x100) { if (defchr) *mbstr++ = *defchr; else *mbstr++ = '.'; if (defused) *defused = 1; } else *mbstr++ = (unsigned char) *wcstr; wcstr++; mblen--, wclen--, ret++; } return ret; /* FIXME: check error codes! */ } /* Character conversion array, * the xterm one has the four scanlines that have no unicode 2.0 * equivalents mapped to their unicode 3.0 locations. */ static const wchar_t unitab_xterm_std[32] = { 0x2666, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0x23ba, 0x23bb, 0x2500, 0x23bc, 0x23bd, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03c0, 0x2260, 0x00a3, 0x00b7, 0x0020 }; void init_ucs(Session *s) { int i; s->ucsdata.line_codepage = decode_codepage(s->cfg.line_codepage); /* Find the line control characters. FIXME: this is not right. */ for (i = 0; i < 256; i++) if (i < ' ' || (i >= 0x7F && i < 0xA0)) s->ucsdata.unitab_ctrl[i] = i; else s->ucsdata.unitab_ctrl[i] = 0xFF; for (i = 0; i < 256; i++) s->ucsdata.unitab_line[i] = s->ucsdata.unitab_scoacs[i] = i; /* VT100 graphics - NB: Broken for non-ascii CP's */ memcpy(s->ucsdata.unitab_xterm, s->ucsdata.unitab_line, sizeof(s->ucsdata.unitab_xterm)); memcpy(s->ucsdata.unitab_xterm + '`', unitab_xterm_std, sizeof(unitab_xterm_std)); s->ucsdata.unitab_xterm['_'] = ' '; } int decode_codepage(char *cp_name) { if (!*cp_name) return CS_NONE; /* use font encoding */ return <API key>(cp_name); } char const *cp_enumerate (int index) { int charset; if (index == 0) return "Use font encoding"; charset = <API key>(index-1); if (charset == CS_NONE) return NULL; return charset_to_localenc(charset); } char const *cp_name(int codepage) { if (codepage == CS_NONE) return "Use font encoding"; return charset_to_localenc(codepage); }
<?php /** * This script is included by the <API key>.php script for arabic languages */ # Version History: # Bug Report and Suggestion to: # Walid Fathalla # fathalla_w@hotmail.com # Modifications by Elpidio 2004-02-07 include_once($root_path.'include/inc_ttf_ar2uni.php'); /* Load the barcode image*/ $bc = ImageCreateFrompng($root_path.'cache/barcodes/en_'.$full_en.'.png'); /* Load the wristband images */ $wb_lrg = ImageCreateFrompng('wristband_large.png'); $wb_med = ImageCreateFrompng('wristband_medium.png'); $wb_sml = ImageCreateFrompng('wristband_small.png'); $wb_bby = ImageCreateFrompng('wristband_baby.png'); /* Get the image sizes*/ $size_lrg = GetImageSize('wristband_large.png'); $size_med = GetImageSize('wristband_medium.png'); $size_sml = GetImageSize('wristband_small.png'); $size_bby = GetImageSize('wristband_baby.png'); $w=1085; // The width of the image = equal to the DIN-A4 paper $h=700; // The height of the image = egual to the DIN-A4 paper /* Create the main image */ $im=ImageCreate($w,$h); $white = ImageColorAllocate ($im, 255,255,255); //white bkgrnd /* $background= ImageColorAllocate ($im, 205, 225, 236); $blue=ImageColorAllocate($im, 0, 127, 255); */ $black = ImageColorAllocate ($im, 0, 0, 0); # Check if ttf is ok include_once($root_path.'include/inc_ttf_check.php'); # Write the print instructions $lmargin=10; # Left margin $tmargin=2; # Top margin if($ttf_ok){ ImageTTFText($im,12,0,$lmargin,$tmargin+10,$black,$arial,ar2uni($<API key>)); ImageTTFText($im,12,0,$lmargin,$tmargin+25,$black,$arial,ar2uni($LDClickImgToPrint)); }else{ ImageString($im,2,10,2,$<API key>,$black); ImageString($im,2,10,15,$LDClickImgToPrint,$black); } # Create the name label $namelabel=ImageCreate(145,40); $nm_white = ImageColorAllocate ($namelabel, 255,255,255); //white bkgrnd $nm_black= ImageColorAllocate ($namelabel, 0, 0, 0); $lmargin=1; # Left margin $tmargin=11; # Top margin $dataline1=ar2uni($result['name_last']).', '.ar2uni($result['name_first']); $dataline2=$result['date_birth']; $dataline3=$result['current_ward'].' '.$result['current_dept'].' '.ar2uni($result['insurance_co_id']).' '.ar2uni($result['insurance_2_co_id']); //$ttf_ok=0; if($ttf_ok){ ImageTTFText($namelabel,11,0,$lmargin,$tmargin,$nm_black,$arial,$dataline1); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+13,$nm_black,$arial,$dataline2); ImageTTFText($namelabel,10,0,$lmargin,$tmargin+26,$nm_black,$arial,$dataline3); }else{ ImageString($namelabel,2,1,2,$dataline1,$nm_black); ImageString($namelabel,2,1,15,$dataline2,$nm_black); ImageString($namelabel,2,1,28,$dataline3,$nm_black); } $topm=$topmargin; ImageCopy($im,$wb_lrg,$leftmargin,$topm,0,0,$size_lrg[0],$size_lrg[1]); $topm+=$yoffset; ImageCopy($im,$wb_med,$leftmargin,$topm,0,0,$size_med[0],$size_med[1]); $topm+=$yoffset; ImageCopy($im,$wb_sml,$leftmargin,$topm,0,0,$size_sml[0],$size_sml[1]); $topm+=$yoffset; ImageCopy($im,$wb_bby,$leftmargin,$topm,0,0,$size_bby[0],$size_bby[1]); //* Place the barcodes */ $topm=$topmargin+15; $topm2=$topmargin+60; ImageCopy($im,$bc,$leftmargin+220,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+480,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+230,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+490,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+435,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+225,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+485,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+420,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+430,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+440,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+395,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+205,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+435,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+380,$topm+78,$full_en,$black); } $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$bc,$leftmargin+160,$topm,9,9,170,37); ImageCopy($im,$bc,$leftmargin+340,$topm2,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+180,$topm-1,$black,$arial,$full_en); ImageTTFText($im,10,0,$leftmargin+360,$topm2-3,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+340,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+175,$topm-13,$full_en,$black); ImageString($im,2,$leftmargin+355,$topm2-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+325,$topm+78,$full_en,$black); } $topm+=$yoffset; ImageCopy($im,$bc,$leftmargin+200,$topm,9,9,170,37); # Print admit nr vertically if($ttf_ok){ ImageTTFText($im,10,0,$leftmargin+210,$topm-1,$black,$arial,$full_en); ImageTTFText($im,11,90,$leftmargin+385,$topm+77,$black,$arial,$full_en); }else{ ImageString($im,2,$leftmargin+215,$topm-13,$full_en,$black); ImageStringUp($im,5,$leftmargin+370,$topm+78,$full_en,$black); } //* Place the name labels*/ $topm=$topmargin+53; $topm2=$topmargin+5; ImageCopy($im,$namelabel,$leftmargin+225,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+485,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+205,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+435,$topm2,0,0,144,39); $topm+=$yoffset; $topm2+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+175,$topm,0,0,144,39); ImageCopy($im,$namelabel,$leftmargin+355,$topm2,0,0,144,39); $topm+=$yoffset; ImageCopy($im,$namelabel,$leftmargin+210,$topm,0,0,144,39); /* Create the final image */ Imagepng ($im); // Do not edit the following lines ImageDestroy ($wb_lrg); ImageDestroy ($wb_med); ImageDestroy ($wb_sml); ImageDestroy ($wb_bby); ImageDestroy ($im); ?>
<?php namespace Webservices\Controller; use Webservices\Helper; use Webservices\Model\WebserviceModel; /** * Apply Webservice Controller * * @package Joomla! * @subpackage Webservices * @since 1.0 */ class ApplyController extends DisplayController { /** * Execute the controller. * * @return void Redirects the application * * @since 2.0 */ public function execute() { try { $model = new WebserviceModel; // Initialize the state for the model $model->setState($this->initializeState($model)); $id = $this->getInput()->getUint('id'); $data = $this->getInput()->getArray()['jform']; if ($model->save($data)) { $msg = \JText::_('<API key>'); } else { $msg = \JText::_('<API key>'); } $type = 'message'; $url = 'index.php?option=com_webservices&task=edit&id=' . $id; } catch (\Exception $e) { $msg = $e->getMessage(); $type = 'error'; } $url = isset($this->returnurl) ? $this->returnurl : $url; $this->getApplication()->enqueueMessage($msg, $type); $this->getApplication()->redirect(\JRoute::_($url, false)); } }
/* * @test * @bug 4997799 * @summary Basic test of ThreadMXBean.getThreadUserTime and * <API key>. * @author Mandy Chung * @modules java.management */ import java.lang.management.*; public class ThreadUserTime { private static ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); private static boolean testFailed = false; private static boolean done = false; private static Object obj = new Object(); private static final int NUM_THREADS = 10; private static Thread[] threads = new Thread[NUM_THREADS]; private static long[] times = new long[NUM_THREADS]; // careful about this value private static final int DELTA = 100; public static void main(String[] argv) throws Exception { if (!mbean.<API key>()) { return; } // disable user time if (mbean.<API key>()) { mbean.<API key>(false); } Thread curThread = Thread.currentThread(); long t = mbean.<API key>(); if (t != -1) { throw new RuntimeException("Invalid <API key> returned = " + t + " expected = -1"); } if (mbean.<API key>()) { long t1 = mbean.getThreadUserTime(curThread.getId()); if (t1 != -1) { throw new RuntimeException("Invalid ThreadUserTime returned = " + t1 + " expected = -1"); } } // Enable CPU Time measurement if (!mbean.<API key>()) { mbean.<API key>(true); } if (!mbean.<API key>()) { throw new RuntimeException("ThreadUserTime is expected to be enabled"); } long time = mbean.<API key>(); if (time < 0) { throw new RuntimeException("Invalid user time returned = " + time); } if (!mbean.<API key>()) { return; } // Expected to be time1 >= time long time1 = mbean.getThreadUserTime(curThread.getId()); if (time1 < time) { throw new RuntimeException("User time " + time1 + " expected >= " + time); } System.out.println(curThread.getName() + " Current Thread User Time = " + time + " user time = " + time1); for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new MyThread("MyThread-" + i); threads[i].start(); } <API key>(); for (int i = 0; i < NUM_THREADS; i++) { times[i] = mbean.getThreadUserTime(threads[i].getId()); } goSleep(200); for (int i = 0; i < NUM_THREADS; i++) { long newTime = mbean.getThreadUserTime(threads[i].getId()); if (times[i] > newTime) { throw new RuntimeException("TEST FAILED: " + threads[i].getName() + " previous user user time = " + times[i] + " > current user user time = " + newTime); } if ((times[i] + DELTA) < newTime) { throw new RuntimeException("TEST FAILED: " + threads[i].getName() + " user time = " + newTime + " previous user time " + times[i] + " out of expected range"); } System.out.println(threads[i].getName() + " Previous User Time = " + times[i] + " Current User time = " + newTime); } synchronized (obj) { done = true; obj.notifyAll(); } for (int i = 0; i < NUM_THREADS; i++) { try { threads[i].join(); } catch (<API key> e) { System.out.println("Unexpected exception is thrown."); e.printStackTrace(System.out); testFailed = true; break; } } if (testFailed) { throw new RuntimeException("TEST FAILED"); } System.out.println("Test passed"); } private static void goSleep(long ms) throws Exception { try { Thread.sleep(ms); } catch (<API key> e) { System.out.println("Unexpected exception is thrown."); throw e; } } private static void <API key>() throws Exception { int count = 0; while (count != NUM_THREADS) { goSleep(100); count = 0; for (int i = 0; i < NUM_THREADS; i++) { ThreadInfo info = mbean.getThreadInfo(threads[i].getId()); if (info.getThreadState() == Thread.State.WAITING) { count++; } } } } static class MyThread extends Thread { public MyThread(String name) { super(name); } public void run() { double sum = 0; for (int i = 0; i < 5000; i++) { double r = Math.random(); double x = Math.pow(3, r); sum += x - r; } synchronized (obj) { while (!done) { try { obj.wait(); } catch (<API key> e) { System.out.println("Unexpected exception is thrown."); e.printStackTrace(System.out); testFailed = true; break; } } } sum = 0; for (int i = 0; i < 5000; i++) { double r = Math.random(); double x = Math.pow(3, r); sum += x - r; } long time1 = mbean.<API key>(); long utime1 = mbean.<API key>(); long time2 = mbean.getThreadCpuTime(getId()); long utime2 = mbean.getThreadUserTime(getId()); System.out.println(getName() + ":"); System.out.println("<API key> = " + utime1 + " ThreadUserTime = " + utime2); System.out.println("<API key> = " + time1 + " ThreadCpuTime = " + time2); if (time1 > time2) { throw new RuntimeException("TEST FAILED: " + getName() + " <API key> = " + time1 + " > ThreadCpuTime = " + time2); } if (utime1 > utime2) { throw new RuntimeException("TEST FAILED: " + getName() + " <API key> = " + utime1 + " > ThreadUserTime = " + utime2); } } } }
<?php require_once 'PEAR.php'; require_once dirname(__FILE__) . '/Writer/Workbook.php'; /** * Class for writing Excel Spreadsheets. This class should change COMPLETELY. * * @author Xavier Noguer <xnoguer@rezebra.com> * @category FileFormats * @package <API key> */ class <API key> extends <API key> { /** * The constructor. It just creates a Workbook * * @param string $filename The optional filename for the Workbook. * @return <API key> The Workbook created */ function <API key>($filename = '') { $this->_filename = $filename; $this-><API key>($filename); } /** * Send HTTP headers for the Excel file. * * @param string $filename The filename to use for HTTP headers * @access public */ function send($filename) { header("Content-type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0,pre-check=0"); header("Pragma: public"); } /** * Utility function for writing formulas * Converts a cell's coordinates to the A1 format. * * @access public * @static * @param integer $row Row for the cell to convert (0-indexed). * @param integer $col Column for the cell to convert (0-indexed). * @return string The cell identifier in A1 format */ function rowcolToCell($row, $col) { if ($col > 255) { //maximum column value exceeded return new PEAR_Error("Maximum column value exceeded: $col"); } $int = (int)($col / 26); $frac = $col % 26; $chr1 = ''; if ($int > 0) { $chr1 = chr(ord('A') + $int - 1); } $chr2 = chr(ord('A') + $frac); $row++; return $chr1 . $chr2 . $row; } }
/* FileName: v_int.c */ /* Description: implement int function */ /* Others: */ /* History: */ /* Modification: Create this file */ /* Modification: Standardize code */ #ifdef __cplusplus #if __cplusplus extern "C" { #endif /* __cpluscplus */ #endif /* __cpluscplus */ #include "vos_config.h" #include "v_typdef.h" #include "v_lib.h" #if (VOS_WIN32 == VOS_OS_VER) CRITICAL_SECTION VOS_CriticalSection; VOS_VOID VOS_SplInit() { <API key>( &VOS_CriticalSection ); } VOS_CPU_SR VOS_SplIMP(VOS_VOID) { <API key>( &VOS_CriticalSection ); return VOS_OK; } VOS_VOID VOS_Splx( VOS_CPU_SR s ) { <API key> ( &VOS_CriticalSection ); } #endif #ifdef __cplusplus #if __cplusplus } #endif /* __cpluscplus */ #endif /* __cpluscplus */
package org.videolan.vlc.gui.tv; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.ObjectAdapter; import android.support.v17.leanback.widget.<API key>; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.text.TextUtils; import org.videolan.vlc.R; import org.videolan.vlc.VLCApplication; import org.videolan.vlc.media.MediaLibrary; import org.videolan.vlc.media.MediaWrapper; import java.util.ArrayList; public class SearchFragment extends android.support.v17.leanback.app.SearchFragment implements android.support.v17.leanback.app.SearchFragment.<API key> { private static final String TAG = "SearchFragment"; private ArrayObjectAdapter mRowsAdapter; private Handler mHandler = new Handler(); private SearchRunnable mDelayedLoad; protected Activity mActivity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); <API key>(this); <API key>(<API key>()); mDelayedLoad = new SearchRunnable(); mActivity = getActivity(); } @Override public ObjectAdapter getResultsAdapter() { return mRowsAdapter; } private void queryByWords(String words) { mRowsAdapter.clear(); if (!TextUtils.isEmpty(words) && words.length() > 2) { mDelayedLoad.setSearchQuery(words); mDelayedLoad.setSearchType(MediaWrapper.TYPE_ALL); VLCApplication.runBackground(mDelayedLoad); } } @Override public boolean onQueryTextChange(String newQuery) { queryByWords(newQuery); return true; } @Override public boolean onQueryTextSubmit(String query) { queryByWords(query); return true; } private void loadRows(String query, int type) { ArrayList<MediaWrapper> mediaList = MediaLibrary.getInstance().searchMedia(query); final ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter(mActivity)); listRowAdapter.addAll(0, mediaList); mHandler.post(new Runnable() { @Override public void run() { HeaderItem header = new HeaderItem(0, getResources().getString(R.string.search_results)); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } }); } protected <API key> <API key>() { return new <API key>() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item instanceof MediaWrapper) { TvUtil.openMedia(mActivity, (MediaWrapper) item, row); } } }; } private class SearchRunnable implements Runnable { private volatile String searchQuery; private volatile int searchType; public SearchRunnable() {} public void run() { loadRows(searchQuery, searchType); } public void setSearchQuery(String value) { this.searchQuery = value; } public void setSearchType(int value) { this.searchType = value; } } }
#include "webrtc/modules/audio_processing/transient/transient_detector.h" #include <sstream> #include <string> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/audio_processing/transient/common.h" #include "webrtc/modules/audio_processing/transient/file_utils.h" #include "webrtc/system_wrappers/include/file_wrapper.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/typedefs.h" namespace webrtc { static const int kSampleRatesHz[] = {ts::kSampleRate8kHz, ts::kSampleRate16kHz, ts::kSampleRate32kHz, ts::kSampleRate48kHz}; static const size_t <API key> = sizeof(kSampleRatesHz) / sizeof(*kSampleRatesHz); // This test is for the correctness of the transient detector. // Checks the results comparing them with the ones stored in the detect files in // the directory: resources/audio_processing/transient/ // The files contain all the results in double precision (Little endian). // The audio files used with different sample rates are stored in the same // directory. TEST(<API key>, DISABLED_ON_IOS(<API key>)) { for (size_t i = 0; i < <API key>; ++i) { int sample_rate_hz = kSampleRatesHz[i]; // Prepare detect file. std::stringstream detect_file_name; detect_file_name << "audio_processing/transient/detect" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> detect_file(FileWrapper::Create()); detect_file->OpenFile( test::ResourcePath(detect_file_name.str(), "dat").c_str(), true, // Read only. false, // No loop. false); // No text. bool file_opened = detect_file->Open(); ASSERT_TRUE(file_opened) << "File could not be opened.\n" << detect_file_name.str().c_str(); // Prepare audio file. std::stringstream audio_file_name; audio_file_name << "audio_processing/transient/audio" << (sample_rate_hz / 1000) << "kHz"; rtc::scoped_ptr<FileWrapper> audio_file(FileWrapper::Create()); audio_file->OpenFile( test::ResourcePath(audio_file_name.str(), "pcm").c_str(), true, // Read only. false, // No loop. false); // No text. // Create detector. TransientDetector detector(sample_rate_hz); const size_t buffer_length = sample_rate_hz * ts::kChunkSizeMs / 1000; rtc::scoped_ptr<float[]> buffer(new float[buffer_length]); const float kTolerance = 0.02f; size_t frames_read = 0; while (<API key>(audio_file.get(), buffer_length, buffer.get()) == buffer_length) { ++frames_read; float detector_value = detector.Detect(buffer.get(), buffer_length, NULL, 0); double file_value; ASSERT_EQ(1u, <API key>(detect_file.get(), 1, &file_value)) << "Detect test file is malformed.\n"; // Compare results with data from the matlab test file. EXPECT_NEAR(file_value, detector_value, kTolerance) << "Frame: " << frames_read; } detect_file->CloseFile(); audio_file->CloseFile(); } } } // namespace webrtc
<HTML> <HEAD> <TITLE>Contact Information</TITLE> </HEAD> <BODY BGCOLOR=#FFFFFF> <H1>Contact Information and Copyright</H1> SheepShaver was brought to you by <UL> <LI><A HREF="mailto:Christian.Bauer@uni-mainz.de">Christian Bauer</A> (kernel, disk I/O) <LI><A HREF="mailto:Marc.Hellwig@uni-mainz.de">Marc Hellwig</A> (graphics, sound, networking) </UL> <H3><IMG SRC="iconsmall.gif" ALIGN=MIDDLE>SheepShaver WWW Site:</H3> <BLOCKQUOTE> <A HREF="http: </BLOCKQUOTE> <H3>EMail:</H3> <BLOCKQUOTE> <A HREF="mailto:Christian.Bauer@uni-mainz.de">Christian.Bauer@uni-mainz.de</A><BR> </BLOCKQUOTE> <H3>License</H3> <P>SheepShaver is available under the terms of the GNU General Public License. See the file "COPYING" that is included in the distribution for details. <P>&copy; Copyright 1997-2004 Christian Bauer and Marc Hellwig <P>Names of hardware and software items mentioned in this manual and in program texts are in most cases registered trade marks of the respective companies and not marked as such. So the lack of such a note may not be used as an indication that these names are free. <P>SheepShaver is not designed, intended, or authorized for use as a component in systems intended for surgical implant within the body, or other applications intended to support or sustain life, or for any other application in which the failure of SheepShaver could create a situation where personal injury or death may occur (so-called "killer application"). <HR> <ADDRESS> SheepShaver User's Guide </ADDRESS> </BODY> </HTML>
// Locale support -*- C++ -*- // 2006, 2007 // Free Software Foundation, Inc. // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 2, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // invalidate any other reasons why the executable file might be covered by /** @file ctype_noninline.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. */ // ISO C++ 14882: 22.1 Locales // Information as gleaned from /usr/include/ctype.h #if <API key> const ctype_base::mask* ctype<char>::classic_table() throw() { return _S_get_c_locale()->__ctype_b; } #else const ctype_base::mask* ctype<char>::classic_table() throw() { const ctype_base::mask* __ret; char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __ret = *__ctype_b_loc(); #else __ret = __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } return __ret; } #endif #if <API key> ctype<char>::ctype(__c_locale __cloc, const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_clone_c_locale(__cloc)), _M_del(__table != 0 && __del), _M_toupper(_M_c_locale_ctype->__ctype_toupper), _M_tolower(_M_c_locale_ctype->__ctype_tolower), _M_table(__table ? __table : _M_c_locale_ctype->__ctype_b), _M_widen_ok(0), _M_narrow_ok(0) { __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #else ctype<char>::ctype(__c_locale, const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_widen_ok(0), _M_narrow_ok(0) { char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) _M_toupper = *__ctype_toupper_loc(); _M_tolower = *__ctype_tolower_loc(); _M_table = __table ? __table : *__ctype_b_loc(); #else _M_toupper = __ctype_toupper; _M_tolower = __ctype_tolower; _M_table = __table ? __table : __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #endif #if <API key> ctype<char>::ctype(const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_toupper(_M_c_locale_ctype->__ctype_toupper), _M_tolower(_M_c_locale_ctype->__ctype_tolower), _M_table(__table ? __table : _M_c_locale_ctype->__ctype_b), _M_widen_ok(0), _M_narrow_ok(0) { __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #else ctype<char>::ctype(const mask* __table, bool __del, size_t __refs) : facet(__refs), _M_c_locale_ctype(_S_get_c_locale()), _M_del(__table != 0 && __del), _M_widen_ok(0), _M_narrow_ok(0) { char* __old = setlocale(LC_CTYPE, NULL); char* __sav = NULL; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); setlocale(LC_CTYPE, "C"); } #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) _M_toupper = *__ctype_toupper_loc(); _M_tolower = *__ctype_tolower_loc(); _M_table = __table ? __table : *__ctype_b_loc(); #else _M_toupper = __ctype_toupper; _M_tolower = __ctype_tolower; _M_table = __table ? __table : __ctype_b; #endif if (__sav) { setlocale(LC_CTYPE, __sav); delete [] __sav; } __builtin_memset(_M_widen, 0, sizeof(_M_widen)); __builtin_memset(_M_narrow, 0, sizeof(_M_narrow)); } #endif char ctype<char>::do_toupper(char __c) const { return _M_toupper[static_cast<unsigned char>(__c)]; } const char* ctype<char>::do_toupper(char* __low, const char* __high) const { while (__low < __high) { *__low = _M_toupper[static_cast<unsigned char>(*__low)]; ++__low; } return __high; } char ctype<char>::do_tolower(char __c) const { return _M_tolower[static_cast<unsigned char>(__c)]; } const char* ctype<char>::do_tolower(char* __low, const char* __high) const { while (__low < __high) { *__low = _M_tolower[static_cast<unsigned char>(*__low)]; ++__low; } return __high; }
/* { dg-do compile } */ /* { dg-options "-O2 -fdump-tree-ccp1" } */ typedef char char16[16] __attribute__ ((aligned (16))); char16 c16[4] __attribute__ ((aligned (4))); int f5 (int i) { __SIZE_TYPE__ s = (__SIZE_TYPE__)&c16[i]; return 3 & s; } /* { dg-final { scan-tree-dump "return 0;" "ccp1" } } */ /* { dg-final { cleanup-tree-dump "ccp1" } } */
// This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see // { dg-options "-std=gnu++11" } // { dg-do compile { target c++11 } } // This macro should have no effect now #define _GLIBCXX_PROFILE 1 #include <vector>
#include "sw.h" #include "sw_ioctl.h" #include "fal_cosmap.h" #include "fal_uk_if.h" sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t pri) { sw_error_t rv; rv= sw_uk_exec(<API key>, dev_id, dscp, pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, dscp, (a_uint32_t)pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t dp) { sw_error_t rv; rv= sw_uk_exec(<API key>, dev_id, dscp, dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, dscp, (a_uint32_t)dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, (a_uint32_t)pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, (a_uint32_t)dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t queue) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, pri, queue); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t * queue) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, pri, (a_uint32_t)queue); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t queue) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, pri, queue); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t pri, a_uint32_t * queue) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, pri, (a_uint32_t)queue); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t tbl_id, <API key> * tbl) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, tbl_id, tbl); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t tbl_id, <API key> * tbl) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, tbl_id, tbl); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t pri) { sw_error_t rv; rv= sw_uk_exec(<API key>, dev_id, dscp, pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, dscp, (a_uint32_t)pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t dp) { sw_error_t rv; rv= sw_uk_exec(<API key>, dev_id, dscp, dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t dscp, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, dscp, (a_uint32_t)dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * pri) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, (a_uint32_t)pri); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, dp); return rv; } sw_error_t <API key>(a_uint32_t dev_id, a_uint32_t up, a_uint32_t * dp) { sw_error_t rv; rv = sw_uk_exec(<API key>, dev_id, up, (a_uint32_t)dp); return rv; }
<?php defined( 'SOBIPRO' ) || exit( 'Restricted access' ); /** * @author Radek Suski * @version 1.0 * @created 10-Jan-2009 5:24:28 PM */ abstract class SPDBObject extends SPObject { /** * @var bool */ protected $approved = false; /** * @var bool */ protected $confirmed = false; /** * @var int */ protected $counter = 0; /** * @var int */ protected $section = 0; /** * @var bool */ protected $cout = false; /** * @var string */ protected $coutTime = null; /** * @var string */ protected $createdTime = null; /** * @var string */ protected $defURL = null; /** * @var int database object id */ protected $id = 0; /** * @var string */ protected $nid = null; /** * @var string */ protected $metaDesc = null; /** * @var string */ protected $metaKeys = null; /** * @var string */ protected $metaAuthor = null; /** * @var string */ protected $metaRobots = null; /** * @var string */ protected $name = null; /** * @var array */ protected $options = array(); /** * @var string */ protected $oType = null; /** * @var int */ protected $owner = 0; /** * @var string */ protected $ownerIP = null; /** * @var array */ protected $params = array(); /** * @var int */ protected $parent = 0; /** * @var string */ protected $query = null; /** * @var int */ protected $state = 0; /** * @var string */ protected $stateExpl = null; /** * @var string */ protected $template = null; /** * @var string */ protected $updatedTime = null; /** * @var int */ protected $updater = 0; /** * @var string */ protected $updaterIP = null; /** * @var string */ protected $validSince = null; /** * @var string */ protected $validUntil = null; /** * @var int */ protected $version = 0; /** * @var array */ protected $properties = array(); /** * @param string $name * @param array $data */ public function setProperty( $name, $data ) { $this->properties[ $name ] = $data; } /** * list of adjustable properties and the corresponding request method for each property. * If a property isn't declared here, it will be ignored in the getRequest method * @var array */ private static $types = array( 'approved' => 'bool', 'state' => 'int', 'confirmed' => 'bool', 'counter' => 'int', 'createdTime' => 'timestamp', 'defURL' => 'string', 'metaAuthor' => 'string', 'metaDesc' => 'string', 'metaKeys' => 'string', 'metaRobots' => 'string', 'name' => 'string', 'nid' => 'cmd', /** * the id is not needed (and it's dangerous) because if we updating an object it's being created through the id anyway * so at that point we have to already have it. If not, we don't need it because then we are creating a new object */ // 'id' => 'int', 'owner' => 'int', 'ownerIP' => 'ip', 'parent' => 'int', 'stateExpl' => 'string', 'validSince' => 'timestamp', 'validUntil' => 'timestamp', ); /** * @var array */ private static $translatable = array( 'nid', 'metaDesc', 'metaKeys' ); /** * @return \SPDBObject */ public function __construct() { $this->validUntil = SPFactory::config()->date( SPFactory::db()->getNullDate(), 'date.db_format' ); $this->createdTime = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->validSince = SPFactory::config()->date( gmdate( 'U' ), 'date.db_format', null, true ); $this->ownerIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->owner = Sobi::My( 'id' ); $this->updatedTime = SPFactory::config()->date( time(), 'date.db_format' ); Sobi::Trigger( 'CreateModel', $this->name(), array( &$this ) ); } public function formatDatesToEdit() { if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil, 'date.publishing_format' ); } $this->createdTime = SPFactory::config()->date( $this->createdTime, 'date.publishing_format' ); $this->validSince = SPFactory::config()->date( $this->validSince, 'date.publishing_format' ); } /** * @param int $state * @param string $reason */ public function changeState( $state, $reason = null ) { try { SPFactory::db()->update( 'spdb_object', array( 'state' => ( int )$state, 'stateExpl' => $reason ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } SPFactory::cache() ->purgeSectionVars() ->deleteObj( $this->type(), $this->id ) ->deleteObj( 'category', $this->parent ); } /** * Checking in current object */ public function checkIn() { if ( $this->id ) { $this->cout = 0; $this->coutTime = null; try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } /** * checking out current object */ public function checkOut() { if ( $this->id ) { /* @var SPdb $db */ $config =& SPFactory::config(); $this->cout = Sobi::My( 'id' ); $this->coutTime = $config->date( ( time() + $config->key( 'editing.def_cout_time', 3600 ) ), 'date.db_format' ); try { SPFactory::db()->update( 'spdb_object', array( 'coutTime' => $this->coutTime, 'cout' => $this->cout ), array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } } public function delete() { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( $this->id ) ); try { SPFactory::db()->delete( 'spdb_object', array( 'id' => $this->id ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_relations', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } try { SPFactory::db()->delete( 'spdb_language', array( 'id' => $this->id, 'oType' => $this->type() ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } /** * @param string $type * @param bool $recursive * @param int $state * @param bool $name * @return array */ public function getChilds( $type = 'entry', $recursive = false, $state = 0, $name = false ) { static $lang = null; if ( !( $lang ) ) { $lang = Sobi::Lang( false ); } $childs = SPFactory::cache()->getVar( 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); if ( $childs ) { return $childs == SPC::NO_VALUE ? array() : $childs; } $db = SPFactory::db(); $childs = array(); try { $cond = array( 'pid' => $this->id ); if ( $state ) { $cond[ 'so.state' ] = $state; $cond[ 'so.approved' ] = $state; $tables = $db->join( array( array( 'table' => 'spdb_object', 'as' => 'so', 'key' => 'id' ), array( 'table' => 'spdb_relations', 'as' => 'sr', 'key' => 'id' ) ) ); $db->select( array( 'sr.id', 'sr.oType' ), $tables, $cond ); } else { $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ); } $results = $db->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( $recursive && count( $results ) ) { foreach ( $results as $cid ) { $this->rGetChilds( $results, $cid, $type ); } } if ( count( $results ) ) { if ( $type == 'all' ) { foreach ( $results as $id => $r ) { $childs[ $id ] = $r[ 'id' ]; } } else { foreach ( $results as $id => $r ) { if ( $r[ 'oType' ] == $type ) { $childs[ $id ] = $id; } } } } if ( $name && count( $childs ) ) { $names = SPLang::translateObject( $childs, array( 'name', 'alias' ), $type ); if ( is_array( $names ) && !empty( $names ) ) { foreach ( $childs as $i => $id ) { $childs[ $i ] = array( 'name' => $names[ $id ][ 'value' ], 'alias' => $names[ $id ][ 'alias' ] ); } } } if ( !$state ) { SPFactory::cache()->addVar( $childs, 'childs_' . $lang . $type . ( $recursive ? '_recursive' : '' ) . ( $name ? '_full' : '' ) . $state, $this->id ); } return $childs; } /** * @param array $results * @param string $type * @param int $id */ private function rGetChilds( &$results, $id, $type = 'entry' ) { if ( is_array( $id ) ) { $id = $id[ 'id' ]; } /* @var SPdb $db */ $db =& SPFactory::db(); try { $cond = array( 'pid' => $id ); /** Tue, Mar 25, 2014 12:46:08 - it's a recursive function so we need entries and categories * See Issue #1211 * Thanks Marcel * */ // if ( $type ) { // $cond[ 'oType' ] = $type; $r = $db->select( array( 'id', 'oType' ), 'spdb_relations', $cond ) ->loadAssocList( 'id' ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $r ) ) { foreach ( $r as $id => $rs ) { if ( $rs[ 'oType' ] == 'entry' ) { continue; } $results[ $id ] = $rs; $this->rGetChilds( $results, $id, $type ); } } } protected function createAlias() { /* check nid */ $c = 1; static $add = 0; $suffix = null; if ( !( strlen( $this->nid ) ) ) { $this->nid = SPLang::nid( $this->name, true ); } while ( $c ) { try { $condition = array( 'oType' => $this->oType, 'nid' => $this->nid . $suffix ); if ( $this->id ) { $condition[ '!id' ] = $this->id; } $c = SPFactory::db() ->select( 'COUNT( nid )', 'spdb_object', $condition ) ->loadResult(); if ( $c > 0 ) { $suffix = '_' . ++$add; } } catch ( SPException $x ) { } } return $this->nid . $suffix; } /** * Gettin data from request for this object * @param string $prefix * @param string $request */ public function getRequest( $prefix = null, $request = 'POST' ) { $prefix = $prefix ? $prefix . '_' : null; /* get data types of my properties */ $properties = get_object_vars( $this ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$properties ) ); /* and of the parent properties */ $types = array_merge( $this->types(), self::$types ); foreach ( $properties as $property => $values ) { /* if this is an internal variable */ if ( substr( $property, 0, 1 ) == '_' ) { continue; } /* if no data type has been declared */ if ( !isset( $types[ $property ] ) ) { continue; } /* if there was no data for this property ( not if it was just empty ) */ if ( !( SPRequest::exists( $prefix . $property, $request ) ) ) { continue; } /* if the declared data type has not handler in request class */ if ( !method_exists( 'SPRequest', $types[ $property ] ) ) { Sobi::Error( $this->name(), SPLang::e( 'Method %s does not exist!', $types[ $property ] ), SPC::WARNING, 0, __LINE__, __FILE__ ); continue; } /* now we get it ;) */ $this->$property = SPRequest::$types[ $property ]( $prefix . $property, null, $request ); } /* trigger plugins */ Sobi::Trigger( 'getRequest', $this->name(), array( &$this ) ); } public function countChilds( $type = null, $state = 0 ) { return count( $this->getChilds( $type, true, $state ) ); } /** * @return string */ public function type() { return $this->oType; } public function countVisit( $reset = false ) { $count = true; Sobi::Trigger( 'CountVisit', ucfirst( $this->type() ), array( &$count, $this->id ) ); if ( $this->id && $count ) { try { SPFactory::db()->insertUpdate( 'spdb_counter', array( 'sid' => $this->id, 'counter' => ( $reset ? '0' : ++$this->counter ), 'lastUpdate' => 'FUNCTION:NOW()' ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::ERROR, 0, __LINE__, __FILE__ ); } } } public function save( $request = 'post' ) { $this->version++; /* get current data */ $this->updatedTime = SPRequest::now(); $this->updaterIP = SPRequest::ip( 'REMOTE_ADDR', 0, 'SERVER' ); $this->updater = Sobi::My( 'id' ); $this->nid = SPLang::nid( $this->nid, true ); if ( !( $this->nid ) ) { $this->nid = SPLang::nid( $this->name, true ); } /* get THIS class properties */ $properties = get_class_vars( __CLASS__ ); /* if new object */ if ( !$this->id ) { /** @var the notification App is using it to recognise if it is a new entry or an update */ $this->createdTime = $this->updatedTime; $this->owner = $this->owner ? $this->owner : $this->updater; $this->ownerIP = $this->updaterIP; } /* just a security check to avoid mistakes */ else { /** Fri, Dec 19, 2014 19:33:52 * When storing it we should actually get already UTC unix time stamp * so there is not need to remove it again */ // $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime - SPFactory::config()->getTimeOffset() ) : $this->createdTime; $this->createdTime = $this->createdTime && is_numeric( $this->createdTime ) ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->createdTime ) : $this->createdTime; $obj = SPFactory::object( $this->id ); if ( $obj->oType != $this->oType ) { Sobi::Error( 'Object Save', sprintf( 'Serious security violation. Trying to save an object which claims to be an %s but it is a %s. Task was %s', $this->oType, $obj->oType, SPRequest::task() ), SPC::ERROR, 403, __LINE__, __FILE__ ); exit; } } if ( is_numeric( $this->validUntil ) ) { // $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil - SPFactory::config()->getTimeOffset() ) : null; $this->validUntil = $this->validUntil ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validUntil ) : null; } if ( is_numeric( $this->validSince ) ) { $this->validSince = $this->validSince ? gmdate( Sobi::Cfg( 'db.date_format', 'Y-m-d H:i:s' ), $this->validSince ) : null; } /* @var SPdb $db */ $db = SPFactory::db(); $db->transaction(); /* get database columns and their ordering */ $cols = $db->getColumns( 'spdb_object' ); $values = array(); /* * @todo: manage own is not implemented yet */ //$this->approved = Sobi::Can( $this->type(), 'manage', 'own' ); /* if not published, check if user can manage own and if yes, publish it */ if ( !( $this->state ) && !( defined( 'SOBIPRO_ADM' ) ) ) { $this->state = Sobi::Can( $this->type(), 'publish', 'own' ); } if ( !( defined( 'SOBIPRO_ADM' ) ) ) { $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); } // elseif ( defined( 'SOBIPRO_ADM' ) ) { // $this->approved = Sobi::Can( $this->type(), 'publish', 'own' ); /* and sort the properties in the same order */ foreach ( $cols as $col ) { $values[ $col ] = array_key_exists( $col, $properties ) ? $this->$col : ''; } /* trigger plugins */ Sobi::Trigger( 'save', $this->name(), array( &$this ) ); /* try to save */ try { /* if new object */ if ( !$this->id ) { $db->insert( 'spdb_object', $values ); $this->id = $db->insertid(); } /* if update */ else { $db->update( 'spdb_object', $values, array( 'id' => $this->id ) ); } } catch ( SPException $x ) { $db->rollback(); Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } /* get translatable properties */ $attributes = array_merge( $this->translatable(), self::$translatable ); $labels = array(); $defLabels = array(); foreach ( $attributes as $attr ) { if ( $this->has( $attr ) ) { $labels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::Lang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); if ( Sobi::Lang() != Sobi::DefLang() ) { $defLabels[ ] = array( 'sKey' => $attr, 'sValue' => $this->$attr, 'language' => Sobi::DefLang(), 'id' => $this->id, 'oType' => $this->type(), 'fid' => 0 ); } } } /* save translatable properties */ if ( count( $labels ) ) { try { if ( Sobi::Lang() != Sobi::DefLang() ) { $db->insertArray( 'spdb_language', $defLabels, false, true ); } $db->insertArray( 'spdb_language', $labels, true ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } } $db->commit(); $this->checkIn(); } /** * Dummy function */ public function update() { return $this->save(); } /** * @param stdClass $obj */ public function extend( $obj, $cache = false ) { if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); $this->loadTable( $cache ); $this->validUntil = SPFactory::config()->date( $this->validUntil, 'Y-m-d H:i:s' ); } /** * @param int $id * @return \SPDBObject * @internal param \stdClass $obj */ public function & init( $id = 0 ) { Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$id ) ); $this->id = $id ? $id : $this->id; if ( $this->id ) { try { $obj = SPFactory::object( $this->id ); if ( !empty( $obj ) ) { /* ensure that the id was right */ if ( $obj->oType == $this->oType ) { $this->extend( $obj ); } else { $this->id = 0; } } $this->createdTime = SPFactory::config()->date( $this->createdTime ); $this->validSince = SPFactory::config()->date( $this->validSince ); if ( $this->validUntil ) { $this->validUntil = SPFactory::config()->date( $this->validUntil ); } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '<API key>', $x->getMessage() ), SPC::ERROR, 500, __LINE__, __FILE__ ); } $this->loadTable(); } return $this; } public function load( $id ) { return $this->init( $id ); } public function loadTable() { if ( $this->has( '_dbTable' ) && $this->_dbTable ) { try { $db = SPFactory::db(); $obj = $db->select( '*', $this->_dbTable, array( 'id' => $this->id ) ) ->loadObject(); $counter = $db->select( 'counter', 'spdb_counter', array( 'sid' => $this->id ) ) ->loadResult(); if ( $counter !== null ) { $this->counter = $counter; } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$obj ) ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( !empty( $obj ) ) { foreach ( $obj as $k => $v ) { $this->_set( $k, $v ); } } else { Sobi::Error( $this->name(), SPLang::e( 'NO_ENTRIES' ), SPC::WARNING, 0, __LINE__, __FILE__ ); } } $this->translate(); } protected function translate() { $attributes = array_merge( $this->translatable(), self::$translatable ); Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ) . 'Start', array( &$attributes ) ); $db =& SPFactory::db(); try { $labels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::Lang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); /* get labels in the default lang first */ if ( Sobi::Lang( false ) != Sobi::DefLang() ) { $dlabels = $db ->select( 'sValue, sKey', 'spdb_language', array( 'id' => $this->id, 'sKey' => $attributes, 'language' => Sobi::DefLang(), 'oType' => $this->type() ) ) ->loadAssocList( 'sKey' ); if ( count( $dlabels ) ) { foreach ( $dlabels as $k => $v ) { if ( !( isset( $labels[ $k ] ) ) || !( $labels[ $k ] ) ) { $labels[ $k ] = $v; } } } } } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( 'DB_REPORTS_ERR', $x->getMessage() ), SPC::WARNING, 0, __LINE__, __FILE__ ); } if ( count( $labels ) ) { foreach ( $labels as $k => $v ) { $this->_set( $k, $v[ 'sValue' ] ); } } Sobi::Trigger( $this->name(), ucfirst( __FUNCTION__ ), array( &$labels ) ); } /** * @param string $var * @param mixed $val */ protected function _set( $var, $val ) { if ( $this->has( $var ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return bool */ public function isCheckedOut() { if ( $this->cout && $this->cout != Sobi::My( 'id' ) && strtotime( $this->coutTime ) > time() ) { return true; } else { return false; } } /** * @param string $var * @param mixed $val * @return \SPObject|void */ public function set( $var, $val ) { static $types = array(); if ( !count( $types ) ) { $types = array_merge( $this->types(), self::$types ); } if ( $this->has( $var ) && isset( $types[ $var ] ) ) { if ( is_array( $this->$var ) && is_string( $val ) && strlen( $val ) > 2 ) { try { $val = SPConfig::unserialize( $val, $var ); } catch ( SPException $x ) { Sobi::Error( $this->name(), SPLang::e( '%s.', $x->getMessage() ), SPC::NOTICE, 0, __LINE__, __FILE__ ); } } $this->$var = $val; } } /** * @return array */ protected function translatable() { return array(); } }
#ifndef emul_init #define emul_init common_emul_init #endif #ifndef emul_bfd_name #define emul_bfd_name <API key> #endif #ifndef <API key> #define <API key> 0 #endif #ifndef <API key> #define <API key> 0 #endif #ifndef <API key> #define <API key> 2 #endif #ifndef <API key> #define <API key> 0 #endif #ifndef emul_default_endian #define emul_default_endian 2 #endif #ifndef <API key> #define <API key> 0 #endif struct emulation emul_struct_name = { 0, emul_name, emul_init, emul_bfd_name, <API key>, <API key>, <API key>, <API key>, emul_default_endian, <API key>, emul_format, };
package projekt.substratum.common; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import androidx.<API key>.content.<API key>; import projekt.substratum.Substratum; import projekt.substratum.services.crash.AppCrashReceiver; import projekt.substratum.services.packages.OverlayFound; import projekt.substratum.services.packages.OverlayUpdater; import projekt.substratum.services.packages.<API key>; import projekt.substratum.services.profiles.<API key>; import projekt.substratum.services.system.Interfacer<API key>; import static projekt.substratum.common.Internal.<API key>; import static projekt.substratum.common.Internal.<API key>; import static projekt.substratum.common.Internal.<API key>; import static projekt.substratum.common.Internal.OVERLAY_REFRESH; import static projekt.substratum.common.Internal.<API key>; import static projekt.substratum.common.References.ACTIVITY_FINISHER; import static projekt.substratum.common.References.APP_CRASHED; import static projekt.substratum.common.References.INTERFACER_PACKAGE; import static projekt.substratum.common.References.KEY_RETRIEVAL; import static projekt.substratum.common.References.MANAGER_REFRESH; import static projekt.substratum.common.References.PACKAGE_ADDED; import static projekt.substratum.common.References.<API key>; import static projekt.substratum.common.References.SUBSTRATUM_LOG; import static projekt.substratum.common.References.<API key>; import static projekt.substratum.common.References.<API key>; public class Broadcasts { /** * Send a localized key message for encryption to take place * * @param context Context * @param encryptionKey Encryption key * @param ivEncryptKey IV encryption key */ private static void <API key>(Context context, byte[] encryptionKey, byte[] ivEncryptKey) { Substratum.log("KeyRetrieval", "The system has completed the handshake for keys retrieval " + "and is now passing it to the activity..."); Intent intent = new Intent(KEY_RETRIEVAL); intent.putExtra(<API key>, encryptionKey); intent.putExtra(<API key>, ivEncryptKey); <API key>.getInstance(context).sendBroadcast(intent); } /** * Close Substratum as a whole * * @param context Context */ public static void sendKillMessage(Context context) { Substratum.log("SubstratumKiller", "A crucial action has been conducted by the user and " + "Substratum is now shutting down!"); Intent intent = new Intent(<API key>); <API key>.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ThemeFragment * * @param context Context */ public static void sendRefreshMessage(Context context) { Substratum.log("<API key>", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(<API key>); <API key>.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the Overlays tab * * @param context Context */ public static void <API key>(Context context) { Substratum.log("OverlayRefresher", "A theme has been modified, sending update signal to refresh the list!"); Intent intent = new Intent(OVERLAY_REFRESH); <API key>.getInstance(context).sendBroadcast(intent); } /** * Activity finisher when a theme was updated * * @param context Context * @param packageName Package of theme to close */ public static void <API key>(Context context, String packageName) { Substratum.log("ThemeInstaller", "A theme has been installed, sending update signal to app for further processing!"); Intent intent = new Intent(ACTIVITY_FINISHER); intent.putExtra(Internal.THEME_PID, packageName); <API key>.getInstance(context).sendBroadcast(intent); } /** * A package was installed, refresh the ManagerFragment * * @param context Context */ public static void <API key>(Context context) { Intent intent = new Intent(MANAGER_REFRESH); <API key>.getInstance(context).sendBroadcast(intent); } /** * Register the implicit intent broadcast receivers * * @param context Context */ public static void <API key>(Context context) { try { IntentFilter intentPackageAdded = new IntentFilter(PACKAGE_ADDED); intentPackageAdded.addDataScheme("package"); IntentFilter <API key> = new IntentFilter(<API key>); <API key>.addDataScheme("package"); if (Systems.checkOMS(context)) { IntentFilter intentAppCrashed = new IntentFilter(APP_CRASHED); context.<API key>().registerReceiver( new AppCrashReceiver(), intentAppCrashed); context.<API key>().registerReceiver( new OverlayUpdater(), intentPackageAdded); } if (Systems.<API key>(context)) { IntentFilter interfacerAuthorize = new IntentFilter( INTERFACER_PACKAGE + ".CALLER_AUTHORIZED"); context.<API key>().registerReceiver( new Interfacer<API key>(), interfacerAuthorize); } context.<API key>().registerReceiver( new OverlayFound(), intentPackageAdded); context.<API key>().registerReceiver( new <API key>(), intentPackageAdded); context.<API key>().registerReceiver( new <API key>(), <API key>); Substratum.log(SUBSTRATUM_LOG, "Successfully registered broadcast receivers for Substratum functionality!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register broadcast receivers for Substratum functionality..."); } } /** * Register the profile screen off receiver * * @param context Context */ public static void <API key>(Context context) { <API key> = new <API key>(); context.registerReceiver(<API key>, new IntentFilter(Intent.ACTION_SCREEN_OFF)); } /** * Unload the profile screen off receiver * * @param context Context */ public static void <API key>(Context context) { try { context.unregisterReceiver(<API key>); } catch (Exception ignored) { } } /** * Start the key retrieval receiver to obtain the key from the theme * * @param context Context */ public static void <API key>(Context context) { try { IntentFilter intentGetKeys = new IntentFilter(<API key>); context.<API key>().registerReceiver( new KeyRetriever(), intentGetKeys); Substratum.log(SUBSTRATUM_LOG, "Successfully registered key retrieval receiver!"); } catch (Exception e) { Log.e(SUBSTRATUM_LOG, "Failed to register key retrieval receiver..."); } } /** * Key Retriever Receiver */ public static class KeyRetriever extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { <API key>( context, intent.getByteArrayExtra(<API key>), intent.getByteArrayExtra(<API key>)); } } }
<?php function tous_les_fonds($dir,$pattern){ $liste = find_all_in_path($dir,$pattern); foreach($liste as $k=>$v) $liste[$k] = $dir . basename($v,'.html'); return $liste; } ?>
<?php namespace Nooku\Library; class ObjectSet extends Object implements \IteratorAggregate, \ArrayAccess, \Countable, \Serializable { /** * Object set * * @var array */ protected $_object_set = null; /** * Constructor * * @param ObjectConfig $config A ObjectConfig object with configuration options * @return ObjectSet */ public function __construct(ObjectConfig $config) { parent::__construct($config); $this->_object_set = new \ArrayObject(); } /** * Inserts an object in the set * * @param ObjectHandlable $object * @return boolean TRUE on success FALSE on failure */ public function insert(ObjectHandlable $object) { $result = false; if ($handle = $object->getHandle()) { $this->_object_set->offsetSet($handle, $object); $result = true; } return $result; } /** * Removes an object from the set * * All numerical array keys will be modified to start counting from zero while literal keys won't be touched. * * @param ObjectHandlable $object * @return ObjectSet */ public function extract(ObjectHandlable $object) { $handle = $object->getHandle(); if ($this->_object_set->offsetExists($handle)) { $this->_object_set->offsetUnset($handle); } return $this; } /** * Checks if the set contains a specific object * * @param ObjectHandlable $object * @return bool Returns TRUE if the object is in the set, FALSE otherwise */ public function contains(ObjectHandlable $object) { return $this->_object_set->offsetExists($object->getHandle()); } /** * Merge-in another object set * * @param ObjectSet $set * @return ObjectSet */ public function merge(ObjectSet $set) { foreach ($set as $object) { $this->insert($object); } return $this; } /** * Check if the object exists in the queue * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return bool Returns TRUE if the object exists in the storage, and FALSE otherwise * @throws \<API key> if the object doesn't implement ObjectHandlable */ public function offsetExists($object) { if (!$object instanceof ObjectHandlable) { throw new \<API key>('Object needs to implement ObjectHandlable'); } return $this->contains($object); } /** * Returns the object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectHandlable * @throws \<API key> if the object doesn't implement ObjectHandlable */ public function offsetGet($object) { if (!$object instanceof ObjectHandlable) { throw new \<API key>('Object needs to implement ObjectHandlable'); } return $this->_object_set->offsetGet($object->getHandle()); } /** * Store an object in the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @param mixed $data The data to associate with the object [UNUSED] * @return ObjectSet * @throws \<API key> if the object doesn't implement ObjectHandlable */ public function offsetSet($object, $data) { if (!$object instanceof ObjectHandlable) { throw new \<API key>('Object needs to implement ObjectHandlable'); } $this->insert($object); return $this; } /** * Removes an object from the set * * Required by interface ArrayAccess * * @param ObjectHandlable $object * @return ObjectSet * @throws <API key> if the object doesn't implement the ObjectHandlable interface */ public function offsetUnset($object) { if (!$object instanceof ObjectHandlable) { throw new \<API key>('Object needs to implement ObjectHandlable'); } $this->extract($object); return $this; } /** * Return a string representation of the set * * Required by interface \Serializable * * @return string A serialized object */ public function serialize() { return serialize($this->_object_set); } /** * Unserializes a set from its string representation * * Required by interface \Serializable * * @param string $serialized The serialized data */ public function unserialize($serialized) { $this->_object_set = unserialize($serialized); } /** * Returns the number of elements in the collection. * * Required by the Countable interface * * @return int */ public function count() { return $this->_object_set->count(); } /** * Return the first object in the set * * @return ObjectHandlable or NULL is queue is empty */ public function top() { $objects = array_values($this->_object_set->getArrayCopy()); $object = null; if (isset($objects[0])) { $object = $objects[0]; } return $object; } /** * Defined by IteratorAggregate * * @return \ArrayIterator */ public function getIterator() { return $this->_object_set->getIterator(); } /** * Return an associative array of the data. * * @return array */ public function toArray() { return $this->_object_set->getArrayCopy(); } /** * Preform a deep clone of the object * * @retun void */ public function __clone() { parent::__clone(); $this->_object_set = clone $this->_object_set; } }
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the defined('MOODLE_INTERNAL') || die(); /* Do not include any libraries here! */ /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will create a new instance and return the id number * of the new instance. * * @global object * @global object * @param object $lesson Lesson post data from the form * @return int **/ function lesson_add_instance($data, $mform) { global $DB; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); <API key>($data); unset($data->mediafile); $lessonid = $DB->insert_record("lesson", $data); $data->id = $lessonid; <API key>($lessonid, $context, $draftitemid); <API key>($data); <API key>($data); return $lessonid; } /** * Given an object containing all the necessary data, * (defined by the form in mod_form.php) this function * will update an existing instance with new data. * * @global object * @param object $lesson Lesson post data from the form * @return boolean **/ function <API key>($data, $mform) { global $DB; $data->id = $data->instance; $cmid = $data->coursemodule; $draftitemid = $data->mediafile; $context = context_module::instance($cmid); <API key>($data); unset($data->mediafile); $DB->update_record("lesson", $data); <API key>($data->id, $context, $draftitemid); <API key>($data); // update grade item definition <API key>($data); // update grades - TODO: do it only when grading style changes <API key>($data, 0, false); return true; } /** * This function updates the events associated to the lesson. * If $override is non-zero, then it updates only the events * associated with the specified override. * * @uses <API key> * @param object $lesson the lesson object. * @param object $override (optional) limit to a specific override */ function <API key>($lesson, $override = null) { global $CFG, $DB; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); require_once($CFG->dirroot . '/calendar/lib.php'); // Load the old events relating to this lesson. $conds = array('modulename' => 'lesson', 'instance' => $lesson->id); if (!empty($override)) { // Only load events for this override. if (isset($override->userid)) { $conds['userid'] = $override->userid; } else { $conds['groupid'] = $override->groupid; } } $oldevents = $DB->get_records('event', $conds); // Now make a to-do list of all that needs to be updated. if (empty($override)) { // We are updating the primary settings for the lesson, so we need to add all the overrides. $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id)); // As well as the original lesson (empty override). $overrides[] = new stdClass(); } else { // Just do the one override. $overrides = array($override); } // Get group override priorities. $grouppriorities = <API key>($lesson->id); foreach ($overrides as $current) { $groupid = isset($current->groupid) ? $current->groupid : 0; $userid = isset($current->userid) ? $current->userid : 0; $available = isset($current->available) ? $current->available : $lesson->available; $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline; // Only add open/close events for an override if they differ from the lesson default. $addopen = empty($current->id) || !empty($current->available); $addclose = empty($current->id) || !empty($current->deadline); if (!empty($lesson->coursemodule)) { $cmid = $lesson->coursemodule; } else { $cmid = <API key>('lesson', $lesson->id, $lesson->course)->id; } $event = new stdClass(); $event->description = format_module_intro('lesson', $lesson, $cmid); // Events module won't show user events when the courseid is nonzero. $event->courseid = ($userid) ? 0 : $lesson->course; $event->groupid = $groupid; $event->userid = $userid; $event->modulename = 'lesson'; $event->instance = $lesson->id; $event->timestart = $available; $event->timeduration = max($deadline - $available, 0); $event->visible = instance_is_visible('lesson', $lesson); $event->eventtype = 'open'; // Determine the event name and priority. if ($groupid) { // Group override event. $params = new stdClass(); $params->lesson = $lesson->name; $params->group = <API key>($groupid); if ($params->group === false) { // Group doesn't exist, just skip it. continue; } $eventname = get_string('<API key>', 'lesson', $params); // Set group override priority. if ($grouppriorities !== null) { $openpriorities = $grouppriorities['open']; if (isset($openpriorities[$available])) { $event->priority = $openpriorities[$available]; } } } else if ($userid) { // User override event. $params = new stdClass(); $params->lesson = $lesson->name; $eventname = get_string('<API key>', 'lesson', $params); // Set user override priority. $event->priority = <API key>; } else { // The parent event. $eventname = $lesson->name; } if ($addopen or $addclose) { // Separate start and end events. $event->timeduration = 0; if ($available && $addopen) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessonopens', 'lesson').')'; // The method calendar_event::create will reuse a db record if the id field is set. calendar_event::create($event); } if ($deadline && $addclose) { if ($oldevent = array_shift($oldevents)) { $event->id = $oldevent->id; } else { unset($event->id); } $event->name = $eventname.' ('.get_string('lessoncloses', 'lesson').')'; $event->timestart = $deadline; $event->eventtype = 'close'; if ($groupid && $grouppriorities !== null) { $closepriorities = $grouppriorities['close']; if (isset($closepriorities[$deadline])) { $event->priority = $closepriorities[$deadline]; } } calendar_event::create($event); } } } // Delete any leftover events. foreach ($oldevents as $badevent) { $badevent = calendar_event::load($badevent); $badevent->delete(); } } /** * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson. * * @param int $lessonid The quiz ID. * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides. */ function <API key>($lessonid) { global $DB; // Fetch group overrides. $where = 'lessonid = :lessonid AND groupid IS NOT NULL'; $params = ['lessonid' => $lessonid]; $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline'); if (!$overrides) { return null; } $grouptimeopen = []; $grouptimeclose = []; foreach ($overrides as $override) { if ($override->available !== null && !in_array($override->available, $grouptimeopen)) { $grouptimeopen[] = $override->available; } if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) { $grouptimeclose[] = $override->deadline; } } // Sort open times in descending manner. The earlier open time gets higher priority. rsort($grouptimeopen); // Set priorities. $opengrouppriorities = []; $openpriority = 1; foreach ($grouptimeopen as $timeopen) { $opengrouppriorities[$timeopen] = $openpriority++; } // Sort close times in ascending manner. The later close time gets higher priority. sort($grouptimeclose); // Set priorities. $<API key> = []; $closepriority = 1; foreach ($grouptimeclose as $timeclose) { $<API key>[$timeclose] = $closepriority++; } return [ 'open' => $opengrouppriorities, 'close' => $<API key> ]; } /** * This standard function will check all instances of this module * and make sure there are up-to-date events created for each of them. * If courseid = 0, then every lesson event in the site is checked, else * only lesson events belonging to the course specified are checked. * This function is used, in its new format, by <API key>() * * @param int $courseid * @return bool */ function <API key>($courseid = 0) { global $DB; if ($courseid == 0) { if (!$lessons = $DB->get_records('lesson')) { return true; } } else { if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) { return true; } } foreach ($lessons as $lesson) { <API key>($lesson); } return true; } /** * Given an ID of an instance of this module, * this function will permanently delete the instance * and any data that depends on it. * * @global object * @param int $id * @return bool */ function <API key>($id) { global $DB, $CFG; require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST); $lesson = new lesson($lesson); return $lesson->delete(); } /** * Return a small object with summary information about what a * user has done with a given particular instance of this module * Used for user activity reports. * $return->time = the time they did it * $return->info = a short text description * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return object */ function lesson_user_outline($course, $user, $mod, $lesson) { global $CFG, $DB; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); $return = new stdClass(); if (empty($grades->items[0]->grades)) { $return->info = get_string("nolessonattempts", "lesson"); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER BY starttime DESC"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) { $attempt = reset($attempts); if ($attempt->completed) { $return->info = get_string("completed", "lesson"); } else { $return->info = get_string("notyetcompleted", "lesson"); } $return->time = $attempt->lessontime; } else { $return->info = get_string("nolessonattempts", "lesson"); } } else { $return->info = get_string("grade") . ': ' . $grade->str_long_grade; // Datesubmitted == time created. dategraded == time modified or time overridden. // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704. if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) { $return->time = $grade->dategraded; } else { $return->time = $grade->datesubmitted; } } } return $return; } /** * Print a detailed representation of what a user has done with * a given particular instance of this module, for user activity reports. * * @global object * @param object $course * @param object $user * @param object $mod * @param object $lesson * @return bool */ function <API key>($course, $user, $mod, $lesson) { global $DB, $OUTPUT, $CFG; require_once("$CFG->libdir/gradelib.php"); $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id); // Display the grade and feedback. if (empty($grades->items[0]->grades)) { echo $OUTPUT->container(get_string("nolessonattempts", "lesson")); } else { $grade = reset($grades->items[0]->grades); if (empty($grade->grade)) { // Check to see if it an ungraded / incomplete attempt. $sql = "SELECT * FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid ORDER by starttime desc"; $params = array('lessonid' => $lesson->id, 'userid' => $user->id); if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) { if ($attempt->completed) { $status = get_string("completed", "lesson"); } else { $status = get_string("notyetcompleted", "lesson"); } } else { $status = get_string("nolessonattempts", "lesson"); } } else { $status = get_string("grade") . ': ' . $grade->str_long_grade; } // Display the grade or lesson status if there isn't one. echo $OUTPUT->container($status); if ($grade->str_feedback) { echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback); } } // Display the lesson progress. // Attempt, pages viewed, questions answered, correct answers, time. $params = array ("lessonid" => $lesson->id, "userid" => $user->id); $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen"); if (!empty($attempts) or !empty($branches)) { echo $OUTPUT->box_start(); $table = new html_table(); // Table Headings. $table->head = array (get_string("attemptheader", "lesson"), get_string("<API key>", "lesson"), get_string("<API key>", "lesson"), get_string("<API key>", "lesson"), get_string("time")); $table->width = "100%"; $table->align = array ("center", "center", "center", "center", "center"); $table->size = array ("*", "*", "*", "*", "*"); $table->cellpadding = 2; $table->cellspacing = 0; $retry = 0; $nquestions = 0; $npages = 0; $ncorrect = 0; // Filter question pages (from lesson_attempts). foreach ($attempts as $attempt) { if ($attempt->retry == $retry) { $npages++; $nquestions++; if ($attempt->correct) { $ncorrect++; } $timeseen = $attempt->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $nquestions = 1; $npages = 1; if ($attempt->correct) { $ncorrect = 1; } else { $ncorrect = 0; } } } // Filter content pages (from lesson_branch). foreach ($branches as $branch) { if ($branch->retry == $retry) { $npages++; $timeseen = $branch->timeseen; } else { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); $retry++; $npages = 1; } } if ($npages > 0) { $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen)); } echo html_writer::table($table); echo $OUTPUT->box_end(); } return true; } /** * Prints lesson summaries on MyMoodle Page * * Prints lesson name, due date and attempt information on * lessons that have a deadline that has not already passed * and it is available for taking. * * @global object * @global stdClass * @global object * @uses CONTEXT_MODULE * @param array $courses An array of course objects to get lesson instances from * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output ) * @return void */ function <API key>($courses, &$htmlarray) { global $USER, $CFG, $DB, $OUTPUT; if (!$lessons = <API key>('lesson', $courses)) { return; } // Get all of the current users attempts on all lessons. $params = array($USER->id); $sql = 'SELECT lessonid, userid, count(userid) as attempts FROM {lesson_grades} WHERE userid = ? GROUP BY lessonid, userid'; $allattempts = $DB->get_records_sql($sql, $params); $completedattempts = array(); foreach ($allattempts as $myattempt) { $completedattempts[$myattempt->lessonid] = $myattempt->attempts; } // Get the current course ID. $listoflessons = array(); foreach ($lessons as $lesson) { $listoflessons[] = $lesson->id; } // Get the last page viewed by the current user for every lesson in this course. list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED); $dbparams = array_merge($inparams, array('userid' => $USER->id)); // Get the lesson attempts for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype "; $from = "FROM {lesson_attempts} l JOIN ( SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id FROM {lesson_attempts} idselect JOIN ( SELECT lessonid, userid, MAX(timeseen) AS timeseen FROM {lesson_attempts} WHERE userid = :userid AND lessonid $insql GROUP BY userid, lessonid ) timeselect ON timeselect.timeseen = idselect.timeseen AND timeselect.userid = idselect.userid AND timeselect.lessonid = idselect.lessonid GROUP BY idselect.userid, idselect.lessonid ) aid ON l.id = aid.id JOIN {lesson_pages} p ON l.pageid = p.id "; $lastattempts = $DB->get_records_sql($select . $from, $dbparams); // Now, get the lesson branches for the user that have the maximum 'timeseen' value. $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype "; $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from); $lastbranches = $DB->get_records_sql($select . $from, $dbparams); $lastviewed = array(); foreach ($lastattempts as $lastattempt) { $lastviewed[$lastattempt->lessonid] = $lastattempt; } // Go through the branch times and record the 'timeseen' value if it doesn't exist // for the lesson, or replace it if it exceeds the current recorded time. foreach ($lastbranches as $lastbranch) { if (!isset($lastviewed[$lastbranch->lessonid])) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) { $lastviewed[$lastbranch->lessonid] = $lastbranch; } } // Since we have lessons in this course, now include the constants we need. require_once($CFG->dirroot . '/mod/lesson/locallib.php'); $now = time(); foreach ($lessons as $lesson) { if ($lesson->deadline != 0 // The lesson has a deadline and $lesson->deadline >= $now // And it is before the deadline has been met and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available // Visibility. $class = (!$lesson->visible) ? 'dimmed' : ''; // Context. $context = context_module::instance($lesson->coursemodule); // Link to activity. $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule)); $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class)); $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name'); // Deadline. $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info'); // Attempt information. if (has_capability('mod/lesson:manage', $context)) { // This is a teacher, Get the Number of user attempts. $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id)); $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // This is a student, See if the user has at least started the lesson. if (isset($lastviewed[$lesson->id]->timeseen)) { // See if the user has finished this attempt. if (isset($completedattempts[$lesson->id]) && ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) { // Are additional attempts allowed? if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('<API key>', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last attempt was not finished or the lesson does not contain questions. // See if the last page viewed was a branchtable. require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php'); if ($lastviewed[$lesson->id]->qtype == <API key>) { // See if the next pageid is the end of lesson. if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) { // The last page viewed was the End of Lesson. if ($lesson->retake) { // User can retake the lesson. $str .= $OUTPUT->box(get_string('<API key>', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } else { // User has completed the lesson and no retakes are allowed. $str = ''; } } else { // The last page viewed was NOT the end of lesson. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } else { // Last page was a question page, so the attempt is not completed yet. $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } } else { // User has not yet started this lesson. $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info'); $str = $OUTPUT->box($str, 'lesson overview'); } } if (!empty($str)) { if (empty($htmlarray[$lesson->course]['lesson'])) { $htmlarray[$lesson->course]['lesson'] = $str; } else { $htmlarray[$lesson->course]['lesson'] .= $str; } } } } } /** * Function to be run periodically according to the moodle cron * This function searches for things that need to be done, such * as sending out mail, toggling flags etc ... * @global stdClass * @return bool true */ function lesson_cron () { global $CFG; return true; } /** * Return grade for given user or all users. * * @global stdClass * @global object * @param int $lessonid id of lesson * @param int $userid optional user id, 0 means all users * @return array array of grades */ function <API key>($lesson, $userid=0) { global $CFG, $DB; $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id); if (!empty($userid)) { $params["userid"] = $userid; $params["userid2"] = $userid; $user = "AND u.id = :userid"; $fuser = "AND uu.id = :userid2"; } else { $user=""; $fuser=""; } if ($lesson->retake) { if ($lesson->usemaxgrade) { $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } else { $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade FROM {user} u, {lesson_grades} g WHERE u.id = g.userid AND g.lessonid = :lessonid $user GROUP BY u.id"; } unset($params['lessonid2']); unset($params['userid2']); } else { // use only first attempts (with lowest id in lesson_grades table) $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted FROM {user} uu, {lesson_grades} gg WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2 $fuser GROUP BY uu.id"; $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade FROM {user} u, {lesson_grades} g, ($firstonly) f WHERE u.id = g.userid AND g.lessonid = :lessonid AND g.id = f.firstcompleted AND g.userid=f.userid $user"; } return $DB->get_records_sql($sql, $params); } /** * Update grades in central gradebook * * @category grade * @param object $lesson * @param int $userid specific user only, 0 means all * @param bool $nullifnone */ function <API key>($lesson, $userid=0, $nullifnone=true) { global $CFG, $DB; require_once($CFG->libdir.'/gradelib.php'); if ($lesson->grade == 0 || $lesson->practice) { <API key>($lesson); } else if ($grades = <API key>($lesson, $userid)) { <API key>($lesson, $grades); } else if ($userid and $nullifnone) { $grade = new stdClass(); $grade->userid = $userid; $grade->rawgrade = null; <API key>($lesson, $grade); } else { <API key>($lesson); } } /** * Create grade item for given lesson * * @category grade * @uses GRADE_TYPE_VALUE * @uses GRADE_TYPE_NONE * @param object $lesson object with extra cmidnumber * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook * @return int 0 if ok, error code otherwise */ function <API key>($lesson, $grades=null) { global $CFG; if (!function_exists('grade_update')) { //workaround for buggy PHP versions require_once($CFG->libdir.'/gradelib.php'); } if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber); } else { $params = array('itemname'=>$lesson->name); } if (!$lesson->practice and $lesson->grade > 0) { $params['gradetype'] = GRADE_TYPE_VALUE; $params['grademax'] = $lesson->grade; $params['grademin'] = 0; } else if (!$lesson->practice and $lesson->grade < 0) { $params['gradetype'] = GRADE_TYPE_SCALE; $params['scaleid'] = -$lesson->grade; // Make sure current grade fetched correctly from $grades $currentgrade = null; if (!empty($grades)) { if (is_array($grades)) { $currentgrade = reset($grades); } else { $currentgrade = $grades; } } // When converting a score to a scale, use scale's grade maximum to calculate it. if (!empty($currentgrade) && $currentgrade->rawgrade !== null) { $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid); $params['grademax'] = reset($grade->items)->grademax; } } else { $params['gradetype'] = GRADE_TYPE_NONE; } if ($grades === 'reset') { $params['reset'] = true; $grades = null; } else if (!empty($grades)) { // Need to calculate raw grade (Note: $grades has many forms) if (is_object($grades)) { $grades = array($grades->userid => $grades); } else if (array_key_exists('userid', $grades)) { $grades = array($grades['userid'] => $grades); } foreach ($grades as $key => $grade) { if (!is_array($grade)) { $grades[$key] = $grade = (array) $grade; } //check raw grade isnt null otherwise we erroneously insert a grade of 0 if ($grade['rawgrade'] !== null) { $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100); } else { //setting rawgrade to null just in case user is deleting a grade $grades[$key]['rawgrade'] = null; } } } return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params); } /** * List the actions that correspond to a view of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = 'r' and edulevel = LEVEL_PARTICIPATING will * be considered as view action. * * @return array */ function <API key>() { return array('view','view all'); } /** * List the actions that correspond to a post of this module. * This is used by the participation report. * * Note: This is not used by new logging system. Event with * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING * will be considered as post action. * * @return array */ function <API key>() { return array('end','start'); } /** * Runs any processes that must run before * a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function <API key>(&$lesson) { global $DB; $lesson->timemodified = time(); if (empty($lesson->timelimit)) { $lesson->timelimit = 0; } if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) { $lesson->timespent = 0; } if (!isset($lesson->completed)) { $lesson->completed = 0; } if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) { $lesson->gradebetterthan = 0; } else if ($lesson->gradebetterthan > 100) { $lesson->gradebetterthan = 100; } if (empty($lesson->width)) { $lesson->width = 640; } if (empty($lesson->height)) { $lesson->height = 480; } if (empty($lesson->bgcolor)) { $lesson->bgcolor = '#FFFFFF'; } // Conditions for dependency $conditions = new stdClass; $conditions->timespent = $lesson->timespent; $conditions->completed = $lesson->completed; $conditions->gradebetterthan = $lesson->gradebetterthan; $lesson->conditions = serialize($conditions); unset($lesson->timespent); unset($lesson->completed); unset($lesson->gradebetterthan); if (empty($lesson->password)) { unset($lesson->password); } } /** * Runs any processes that must be run * after a lesson insert/update * * @global object * @param object $lesson Lesson form data * @return void **/ function <API key>(&$lesson) { // Update the events relating to this lesson. <API key>($lesson); } /** * Implementation of the function for printing the form elements that control * whether the course reset functionality affects the lesson. * * @param $mform form passed by reference */ function <API key>(&$mform) { $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson')); $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson')); $mform->addElement('advcheckbox', '<API key>', get_string('<API key>', 'lesson')); $mform->addElement('advcheckbox', '<API key>', get_string('<API key>', 'lesson')); } /** * Course reset form defaults. * @param object $course * @return array */ function <API key>($course) { return array('reset_lesson' => 1, '<API key>' => 1, '<API key>' => 1); } /** * Removes all grades from gradebook * * @global stdClass * @global object * @param int $courseid * @param string optional type */ function <API key>($courseid, $type='') { global $CFG, $DB; $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid FROM {lesson} l, {course_modules} cm, {modules} m WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course"; $params = array ("course" => $courseid); if ($lessons = $DB->get_records_sql($sql,$params)) { foreach ($lessons as $lesson) { <API key>($lesson, 'reset'); } } } /** * Actual implementation of the reset course functionality, delete all the * lesson attempts for course $data->courseid. * * @global stdClass * @global object * @param object $data the data submitted from the reset course. * @return array status array */ function <API key>($data) { global $CFG, $DB; $componentstr = get_string('modulenameplural', 'lesson'); $status = array(); if (!empty($data->reset_lesson)) { $lessonssql = "SELECT l.id FROM {lesson} l WHERE l.course=:course"; $params = array ("course" => $data->courseid); $lessons = $DB->get_records_sql($lessonssql, $params); // Get rid of attempts files. $fs = get_file_storage(); if ($lessons) { foreach ($lessons as $lessonid => $unused) { if (!$cm = <API key>('lesson', $lessonid)) { continue; } $context = context_module::instance($cm->id); $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses'); } } $DB-><API key>('lesson_timer', "lessonid IN ($lessonssql)", $params); $DB-><API key>('lesson_grades', "lessonid IN ($lessonssql)", $params); $DB-><API key>('lesson_attempts', "lessonid IN ($lessonssql)", $params); $DB-><API key>('lesson_branch', "lessonid IN ($lessonssql)", $params); // remove all grades from gradebook if (empty($data-><API key>)) { <API key>($data->courseid); } $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false); } // Remove user overrides. if (!empty($data-><API key>)) { $DB-><API key>('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('<API key>', 'lesson'), 'error' => false); } // Remove group overrides. if (!empty($data-><API key>)) { $DB-><API key>('lesson_overrides', 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid)); $status[] = array( 'component' => $componentstr, 'item' => get_string('<API key>', 'lesson'), 'error' => false); } updating dates - shift may be negative too if ($data->timeshift) { $DB->execute("UPDATE {lesson_overrides} SET available = available + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND available <> 0", array($data->timeshift, $data->courseid)); $DB->execute("UPDATE {lesson_overrides} SET deadline = deadline + ? WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND deadline <> 0", array($data->timeshift, $data->courseid)); <API key>('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid); $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false); } return $status; } /** * Returns all other caps used in module * @return array */ function <API key>() { return array('moodle/site:accessallgroups'); } /** * @uses FEATURE_GROUPS * @uses FEATURE_GROUPINGS * @uses FEATURE_MOD_INTRO * @uses <API key> * @uses <API key> * @uses <API key> * @param string $feature FEATURE_xx constant for requested feature * @return mixed True if module supports feature, false if not, null if doesn't know */ function lesson_supports($feature) { switch($feature) { case FEATURE_GROUPS: return true; case FEATURE_GROUPINGS: return true; case FEATURE_MOD_INTRO: return true; case <API key>: return true; case <API key>: return true; case <API key>: return true; case <API key>: return true; case <API key>: return true; case <API key>: return true; default: return null; } } /** * Obtains the automatic completion state for this lesson based on any conditions * in lesson settings. * * @param object $course Course * @param object $cm course-module * @param int $userid User ID * @param bool $type Type of comparison (or/and; can be used as return value if no conditions) * @return bool True if completed, false if not, $type if conditions not set. */ function <API key>($course, $cm, $userid, $type) { global $CFG, $DB; // Get lesson details. $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST); $result = $type; // Default return value. // If completion option is enabled, evaluate it and return true/false. if ($lesson-><API key>) { $value = $DB->record_exists('lesson_timer', array( 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1)); if ($type == COMPLETION_AND) { $result = $result && $value; } else { $result = $result || $value; } } if ($lesson->completiontimespent != 0) { $duration = $DB->get_field_sql( "SELECT SUM(lessontime - starttime) FROM {lesson_timer} WHERE lessonid = :lessonid AND userid = :userid", array('userid' => $userid, 'lessonid' => $lesson->id)); if (!$duration) { $duration = 0; } if ($type == COMPLETION_AND) { $result = $result && ($lesson->completiontimespent < $duration); } else { $result = $result || ($lesson->completiontimespent < $duration); } } return $result; } /** * This function extends the settings navigation block for the site. * * It is safe to rely on PAGE here as we will only ever be within the module * context when this is called * * @param settings_navigation $settings * @param navigation_node $lessonnode */ function <API key>($settings, $lessonnode) { global $PAGE, $DB; // We want to add these new nodes after the Edit settings node, and before the // Locally assigned roles node. Of course, both of those are controlled by capabilities. $keys = $lessonnode-><API key>(); $beforekey = null; $i = array_search('modedit', $keys); if ($i === false and array_key_exists(0, $keys)) { $beforekey = $keys[0]; } else if (array_key_exists($i + 1, $keys)) { $beforekey = $keys[$i + 1]; } if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id)); $node = navigation_node::create(get_string('groupoverrides', 'lesson'), new moodle_url($url, array('mode' => 'group')), navigation_node::TYPE_SETTING, null, '<API key>'); $lessonnode->add_node($node, $beforekey); $node = navigation_node::create(get_string('useroverrides', 'lesson'), new moodle_url($url, array('mode' => 'user')), navigation_node::TYPE_SETTING, null, '<API key>'); $lessonnode->add_node($node, $beforekey); } if (has_capability('mod/lesson:edit', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id)); $lessonnode->add(get_string('preview', 'lesson'), $url); $editnode = $lessonnode->add(get_string('edit', 'lesson')); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed')); $editnode->add(get_string('collapsed', 'lesson'), $url); $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full')); $editnode->add(get_string('full', 'lesson'), $url); } if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) { $reportsnode = $lessonnode->add(get_string('reports', 'lesson')); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview')); $reportsnode->add(get_string('overview', 'lesson'), $url); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail')); $reportsnode->add(get_string('detailedstats', 'lesson'), $url); } if (has_capability('mod/lesson:grade', $PAGE->cm->context)) { $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id)); $lessonnode->add(get_string('manualgrading', 'lesson'), $url); } } /** * Get list of available import or export formats * * Copied and modified from lib/questionlib.php * * @param string $type 'import' if import list, otherwise export list assumed * @return array sorted list of import/export formats available */ function <API key>($type) { global $CFG; $fileformats = core_component::get_plugin_list("qformat"); $fileformatname=array(); foreach ($fileformats as $fileformat=>$fdir) { $format_file = "$fdir/format.php"; if (file_exists($format_file) ) { require_once($format_file); } else { continue; } $classname = "qformat_$fileformat"; $format_class = new $classname(); if ($type=='import') { $provided = $format_class->provide_import(); } else { $provided = $format_class->provide_export(); } if ($provided) { $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat); } } natcasesort($fileformatnames); return $fileformatnames; } /** * Serves the lesson attachments. Implements needed access control ;-) * * @package mod_lesson * @category files * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param array $args extra arguments * @param bool $forcedownload whether or not force download * @param array $options additional options affecting the file serving * @return bool false if file not found, does not return if found - justsend the file */ function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) { global $CFG, $DB; if ($context->contextlevel != CONTEXT_MODULE) { return false; } $fileareas = <API key>(); if (!array_key_exists($filearea, $fileareas)) { return false; } if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) { return false; } <API key>($course, true, $cm); if ($filearea === 'page_contents') { $pageid = (int)array_shift($args); if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args); } else if ($filearea === 'page_answers' || $filearea === 'page_responses') { $itemid = (int)array_shift($args); if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'essay_responses') { $itemid = (int)array_shift($args); if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) { return false; } $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args); } else if ($filearea === 'mediafile') { if (count($args) > 1) { // Remove the itemid when it appears to be part of the arguments. If there is only one argument // then it is surely the file name. The itemid is sometimes used to prevent browser caching. array_shift($args); } $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args); } else { return false; } $fs = get_file_storage(); if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { return false; } // finally send the file send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security! } /** * Returns an array of file areas * * @package mod_lesson * @category files * @return array a list of available file areas */ function <API key>() { $areas = array(); $areas['page_contents'] = get_string('pagecontents', 'mod_lesson'); $areas['mediafile'] = get_string('mediafile', 'mod_lesson'); $areas['page_answers'] = get_string('pageanswers', 'mod_lesson'); $areas['page_responses'] = get_string('pageresponses', 'mod_lesson'); $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson'); return $areas; } /** * Returns a file_info_stored object for the file being requested here * * @package mod_lesson * @category files * @global stdClass $CFG * @param file_browse $browser file browser instance * @param array $areas file areas * @param stdClass $course course object * @param stdClass $cm course module object * @param stdClass $context context object * @param string $filearea file area * @param int $itemid item ID * @param string $filepath file path * @param string $filename file name * @return file_info_stored */ function <API key>($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { global $CFG, $DB; if (!has_capability('moodle/course:managefiles', $context)) { // No peaking here for students! return null; } // Mediafile area does not have sub directories, so let's select the default itemid to prevent // the user from selecting a directory to access the mediafile content. if ($filearea == 'mediafile' && is_null($itemid)) { $itemid = 0; } if (is_null($itemid)) { return new <API key>($browser, $course, $cm, $context, $areas, $filearea); } $fs = get_file_storage(); $filepath = is_null($filepath) ? '/' : $filepath; $filename = is_null($filename) ? '.' : $filename; if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) { return null; } $itemname = $filearea; if ($filearea == 'page_contents') { $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid)); $itemname = format_string($itemname, true, array('context' => $context)); } else { $areas = <API key>(); if (isset($areas[$filearea])) { $itemname = $areas[$filearea]; } } $urlbase = $CFG->wwwroot . '/pluginfile.php'; return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false); } /** * Return a list of page types * @param string $pagetype current page type * @param stdClass $parentcontext Block's parent context * @param stdClass $currentcontext Current context of block */ function <API key>($pagetype, $parentcontext, $currentcontext) { $module_pagetype = array( 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'), 'mod-lesson-view'=>get_string('<API key>', 'lesson'), 'mod-lesson-edit'=>get_string('<API key>', 'lesson')); return $module_pagetype; } /** * Update the lesson activity to include any file * that was uploaded, or if there is none, set the * mediafile field to blank. * * @param int $lessonid the lesson id * @param stdClass $context the context * @param int $draftitemid the draft item */ function <API key>($lessonid, $context, $draftitemid) { global $DB; // Set the filestorage object. $fs = get_file_storage(); // Save the file if it exists that is currently in the draft area. <API key>($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0); // Get the file if it exists. $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false); // Check that there is a file to process. if (count($files) == 1) { // Get the first (and only) file. $file = reset($files); // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid)); } else { // Set the mediafile column in the lessons table. $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid)); } } /** * Get icon mapping for font-awesome. */ function <API key>() { return [ 'mod_lesson:e/copy' => 'fa-clone', ]; }
// Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "MediaInfo/Setup.h" #if defined(MEDIAINFO_7Z_YES) #include "MediaInfo/Archive/File_7z.h" namespace MediaInfoLib {
Graphic.Ellipse = Class.create(); Object.extend(Graphic.Ellipse.prototype, Graphic.Shape.prototype); // Keep parent initialize Graphic.Ellipse.prototype._shapeInitialize = Graphic.Shape.prototype.initialize; Object.extend(Graphic.Ellipse.prototype, { initialize: function(renderer) { this._shapeInitialize(renderer, "ellipse"); Object.extend(this.attributes, {cx: 0, cy: 0, rx: 0, ry: 0}) return this; }, getSize: function() { return {w: 2 * this.attributes.rx, h: 2 * this.attributes.ry} }, setSize: function(width, height) { var location = this.getLocation(); this._setAttributes({rx: width/2, ry: height/2}); this.setLocation(location.x, location.y); return this; }, getLocation: function() { return {x: this.attributes.cx - this.attributes.rx, y: this.attributes.cy - this.attributes.ry} }, setLocation: function(x, y) { this._setAttributes({cx: x + this.attributes.rx, cy: y + this.attributes.ry}); return this; } })
#ifndef <API key> #define <API key> #include <asn_application.h> /* Including external dependencies */ #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct S1ap_IE; /* <API key> */ typedef struct <API key> { struct <API key> { A_SEQUENCE_OF(struct S1ap_IE) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } <API key>; /* * This type is extensible, * possible extensions are below. */ /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } <API key>; /* Implementation */ extern <API key> <API key>; #ifdef __cplusplus } #endif /* Referred external types */ #include "S1ap-IE.h" #endif /* <API key> */ #include <asn_internal.h>
/** * @file chschd.c * @brief Scheduler code. * * @addtogroup scheduler * @details This module provides the default portable scheduler code. * @{ */ #include "ch.h" /* Module local definitions. */ /* Module exported variables. */ /** * @brief System data structures. */ ch_system_t ch; /* Module local types. */ /* Module local variables. */ /* Module local functions. */ /* Module exported functions. */ /** * @brief Scheduler initialization. * * @notapi */ void _scheduler_init(void) { queue_init(&ch.rlist.queue); ch.rlist.prio = NOPRIO; #if CH_CFG_USE_REGISTRY == TRUE ch.rlist.newer = (thread_t *)&ch.rlist; ch.rlist.older = (thread_t *)&ch.rlist; #endif } #if (<API key> == FALSE) || defined(__DOXYGEN__) /** * @brief Inserts a thread into a priority ordered queue. * @note The insertion is done by scanning the list from the highest * priority toward the lowest. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tqp the pointer to the threads list header * * @notapi */ void queue_prio_insert(thread_t *tp, threads_queue_t *tqp) { thread_t *cp = (thread_t *)tqp; do { cp = cp->queue.next; } while ((cp != (thread_t *)tqp) && (cp->prio >= tp->prio)); tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; } /** * @brief Inserts a thread into a queue. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tqp the pointer to the threads list header * * @notapi */ void queue_insert(thread_t *tp, threads_queue_t *tqp) { tp->queue.next = (thread_t *)tqp; tp->queue.prev = tqp->prev; tp->queue.prev->queue.next = tp; tqp->prev = tp; } /** * @brief Removes the first-out thread from a queue and returns it. * @note If the queue is priority ordered then this function returns the * thread with the highest priority. * * @param[in] tqp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *queue_fifo_remove(threads_queue_t *tqp) { thread_t *tp = tqp->next; tqp->next = tp->queue.next; tqp->next->queue.prev = (thread_t *)tqp; return tp; } /** * @brief Removes the last-out thread from a queue and returns it. * @note If the queue is priority ordered then this function returns the * thread with the lowest priority. * * @param[in] tqp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *queue_lifo_remove(threads_queue_t *tqp) { thread_t *tp = tqp->prev; tqp->prev = tp->queue.prev; tqp->prev->queue.next = (thread_t *)tqp; return tp; } /** * @brief Removes a thread from a queue and returns it. * @details The thread is removed from the queue regardless of its relative * position and regardless the used insertion method. * * @param[in] tp the pointer to the thread to be removed from the queue * @return The removed thread pointer. * * @notapi */ thread_t *queue_dequeue(thread_t *tp) { tp->queue.prev->queue.next = tp->queue.next; tp->queue.next->queue.prev = tp->queue.prev; return tp; } /** * @brief Pushes a thread_t on top of a stack list. * * @param[in] tp the pointer to the thread to be inserted in the list * @param[in] tlp the pointer to the threads list header * * @notapi */ void list_insert(thread_t *tp, threads_list_t *tlp) { tp->queue.next = tlp->next; tlp->next = tp; } /** * @brief Pops a thread from the top of a stack list and returns it. * @pre The list must be non-empty before calling this function. * * @param[in] tlp the pointer to the threads list header * @return The removed thread pointer. * * @notapi */ thread_t *list_remove(threads_list_t *tlp) { thread_t *tp = tlp->next; tlp->next = tp->queue.next; return tp; } #endif /* <API key> */ /** * @brief Inserts a thread in the Ready List placing it behind its peers. * @details The thread is positioned behind all threads with higher or equal * priority. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @post This function does not reschedule so a call to a rescheduling * function must be performed before unlocking the kernel. Note that * interrupt handlers always reschedule on exit so an explicit * reschedule must not be performed in ISRs. * * @param[in] tp the thread to be made ready * @return The thread pointer. * * @iclass */ thread_t *chSchReadyI(thread_t *tp) { thread_t *cp; chDbgCheckClassI(); chDbgCheck(tp != NULL); chDbgAssert((tp->state != CH_STATE_READY) && (tp->state != CH_STATE_FINAL), "invalid state"); tp->state = CH_STATE_READY; cp = (thread_t *)&ch.rlist.queue; do { cp = cp->queue.next; } while (cp->prio >= tp->prio); /* Insertion on prev.*/ tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; return tp; } /** * @brief Inserts a thread in the Ready List placing it ahead its peers. * @details The thread is positioned ahead all threads with higher or equal * priority. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @post This function does not reschedule so a call to a rescheduling * function must be performed before unlocking the kernel. Note that * interrupt handlers always reschedule on exit so an explicit * reschedule must not be performed in ISRs. * * @param[in] tp the thread to be made ready * @return The thread pointer. * * @iclass */ thread_t *chSchReadyAheadI(thread_t *tp) { thread_t *cp; chDbgCheckClassI(); chDbgCheck(tp != NULL); chDbgAssert((tp->state != CH_STATE_READY) && (tp->state != CH_STATE_FINAL), "invalid state"); tp->state = CH_STATE_READY; cp = (thread_t *)&ch.rlist.queue; do { cp = cp->queue.next; } while (cp->prio > tp->prio); /* Insertion on prev.*/ tp->queue.next = cp; tp->queue.prev = cp->queue.prev; tp->queue.prev->queue.next = tp; cp->queue.prev = tp; return tp; } /** * @brief Puts the current thread to sleep into the specified state. * @details The thread goes into a sleeping state. The possible * @ref thread_states are defined into @p threads.h. * * @param[in] newstate the new thread state * * @sclass */ void chSchGoSleepS(tstate_t newstate) { thread_t *otp = currp; chDbgCheckClassS(); /* New state.*/ otp->state = newstate; #if CH_CFG_TIME_QUANTUM > 0 /* The thread is renouncing its remaining time slices so it will have a new time quantum when it will wakeup.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; #endif /* Next thread in ready list becomes current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-enter hook.*/ if (currp->prio == IDLEPRIO) { <API key>(); } /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } /* * Timeout wakeup callback. */ static void wakeup(void *p) { thread_t *tp = (thread_t *)p; chSysLockFromISR(); switch (tp->state) { case CH_STATE_READY: /* Handling the special case where the thread has been made ready by another thread with higher priority.*/ chSysUnlockFromISR(); return; case CH_STATE_SUSPENDED: *tp->u.wttrp = NULL; break; #if <API key> == TRUE case CH_STATE_WTSEM: chSemFastSignalI(tp->u.wtsemp); #endif /* Falls through.*/ case CH_STATE_QUEUED: /* Falls through.*/ #if (CH_CFG_USE_CONDVARS == TRUE) && (<API key> == TRUE) case CH_STATE_WTCOND: #endif /* States requiring dequeuing.*/ (void) queue_dequeue(tp); break; default: /* Any other state, nothing to do.*/ break; } tp->u.rdymsg = MSG_TIMEOUT; (void) chSchReadyI(tp); chSysUnlockFromISR(); } /** * @brief Puts the current thread to sleep into the specified state with * timeout specification. * @details The thread goes into a sleeping state, if it is not awakened * explicitly within the specified timeout then it is forcibly * awakened with a @p MSG_TIMEOUT low level message. The possible * @ref thread_states are defined into @p threads.h. * * @param[in] newstate the new thread state * @param[in] timeout the number of ticks before the operation timeouts, the * special values are handled as follow: * - @a TIME_INFINITE the thread enters an infinite sleep * state, this is equivalent to invoking * @p chSchGoSleepS() but, of course, less efficient. * - @a TIME_IMMEDIATE this value is not allowed. * . * @return The wakeup message. * @retval MSG_TIMEOUT if a timeout occurs. * * @sclass */ msg_t <API key>(tstate_t newstate, sysinterval_t timeout) { chDbgCheckClassS(); if (TIME_INFINITE != timeout) { virtual_timer_t vt; chVTDoSetI(&vt, timeout, wakeup, currp); chSchGoSleepS(newstate); if (chVTIsArmedI(&vt)) { chVTDoResetI(&vt); } } else { chSchGoSleepS(newstate); } return currp->u.rdymsg; } /** * @brief Wakes up a thread. * @details The thread is inserted into the ready list or immediately made * running depending on its relative priority compared to the current * thread. * @pre The thread must not be already inserted in any list through its * @p next and @p prev or list corruption would occur. * @note It is equivalent to a @p chSchReadyI() followed by a * @p chSchRescheduleS() but much more efficient. * @note The function assumes that the current thread has the highest * priority. * * @param[in] ntp the thread to be made ready * @param[in] msg the wakeup message * * @sclass */ void chSchWakeupS(thread_t *ntp, msg_t msg) { thread_t *otp = currp; chDbgCheckClassS(); chDbgAssert((ch.rlist.queue.next == (thread_t *)&ch.rlist.queue) || (ch.rlist.current->prio >= ch.rlist.queue.next->prio), "priority order violation"); /* Storing the message to be retrieved by the target thread when it will restart execution.*/ ntp->u.rdymsg = msg; /* If the waken thread has a not-greater priority than the current one then it is just inserted in the ready list else it made running immediately and the invoking thread goes in the ready list instead.*/ if (ntp->prio <= otp->prio) { (void) chSchReadyI(ntp); } else { otp = chSchReadyI(otp); /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { <API key>(); } /* The extracted thread is marked as current.*/ currp = ntp; ntp->state = CH_STATE_CURRENT; /* Swap operation as tail call.*/ chSysSwitch(ntp, otp); } } /** * @brief Performs a reschedule if a higher priority thread is runnable. * @details If a thread with a higher priority than the current thread is in * the ready list then make the higher priority thread running. * * @sclass */ void chSchRescheduleS(void) { chDbgCheckClassS(); if (<API key>()) { <API key>(); } } #if !defined(<API key>) /** * @brief Evaluates if preemption is required. * @details The decision is taken by comparing the relative priorities and * depending on the state of the round robin timeout counter. * @note Not a user function, it is meant to be invoked by the scheduler * itself or from within the port layer. * * @retval true if there is a thread that must go in running state * immediately. * @retval false if preemption is not required. * * @special */ bool <API key>(void) { tprio_t p1 = firstprio(&ch.rlist.queue); tprio_t p2 = currp->prio; #if CH_CFG_TIME_QUANTUM > 0 /* If the running thread has not reached its time quantum, reschedule only if the first thread on the ready queue has a higher priority. Otherwise, if the running thread has used up its time quantum, reschedule if the first thread on the ready queue has equal or higher priority.*/ return (currp->ticks > (tslices_t)0) ? (p1 > p2) : (p1 >= p2); #else /* If the round robin preemption feature is not enabled then performs a simpler comparison.*/ return p1 > p2; #endif } #endif /* !defined(<API key>) */ /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list behind all * threads having the same priority. The thread regains its time * quantum. * @note Not a user function, it is meant to be invoked by the scheduler * itself. * * @special */ void <API key>(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { <API key>(); } #if CH_CFG_TIME_QUANTUM > 0 /* It went behind peers so it gets a new time quantum.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; #endif /* Placing in ready list behind peers.*/ otp = chSchReadyI(otp); /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list ahead of all * threads having the same priority. * @note Not a user function, it is meant to be invoked by the scheduler * itself. * * @special */ void <API key>(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { <API key>(); } /* Placing in ready list ahead of peers.*/ otp = chSchReadyAheadI(otp); /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } #if !defined(<API key>) /** * @brief Switches to the first thread on the runnable queue. * @details The current thread is positioned in the ready list behind or * ahead of all threads having the same priority depending on * if it used its whole time slice. * @note Not a user function, it is meant to be invoked by the scheduler * itself or from within the port layer. * * @special */ void chSchDoReschedule(void) { thread_t *otp = currp; /* Picks the first thread from the ready queue and makes it current.*/ currp = queue_fifo_remove(&ch.rlist.queue); currp->state = CH_STATE_CURRENT; /* Handling idle-leave hook.*/ if (otp->prio == IDLEPRIO) { <API key>(); } #if CH_CFG_TIME_QUANTUM > 0 /* If CH_CFG_TIME_QUANTUM is enabled then there are two different scenarios to handle on preemption: time quantum elapsed or not.*/ if (currp->ticks == (tslices_t)0) { /* The thread consumed its time quantum so it is enqueued behind threads with same priority level, however, it acquires a new time quantum.*/ otp = chSchReadyI(otp); /* The thread being swapped out receives a new time quantum.*/ otp->ticks = (tslices_t)CH_CFG_TIME_QUANTUM; } else { /* The thread didn't consume all its time quantum so it is put ahead of threads with equal priority and does not acquire a new time quantum.*/ otp = chSchReadyAheadI(otp); } #else /* !(CH_CFG_TIME_QUANTUM > 0) */ /* If the round-robin mechanism is disabled then the thread goes always ahead of its peers.*/ otp = chSchReadyAheadI(otp); #endif /* !(CH_CFG_TIME_QUANTUM > 0) */ /* Swap operation as tail call.*/ chSysSwitch(currp, otp); } #endif /*!defined(<API key>) */
<?php namespace Magento\Setup\Module\Di\Compiler\Config; interface <API key> { /** * Modifies input config * * @param array $config * @return array */ public function modify(array $config); }
#ifndef _SOCKS_H #define _SOCKS_H #pragma pack(push,1) struct <API key> { char ver; char nmethods; char methods[255]; }; struct <API key> { char ver; char method; }; struct xsocks_request { char atyp; char addr[0]; }; struct socks5_request { char ver; char cmd; char rsv; char atyp; char addr[0]; }; struct socks5_response { char ver; char rep; char rsv; char atyp; }; #pragma pack(pop) enum s5_auth_method { S5_AUTH_NONE = 0x00, S5_AUTH_GSSAPI = 0x01, S5_AUTH_PASSWD = 0x02, }; enum s5_auth_result { S5_AUTH_ALLOW = 0x00, S5_AUTH_DENY = 0x01, }; enum xsocks_atyp { ATYP_IPV4 = 0x01, ATYP_HOST = 0x03, ATYP_IPV6 = 0x04, }; enum s5_cmd { S5_CMD_CONNECT = 0x01, S5_CMD_BIND = 0x02, <API key> = 0x03, }; enum s5_rep { S5_REP_SUCCESSED = 0X00, <API key> = 0X01, S5_REP_RULESET_DENY = 0X02, <API key> = 0X03, <API key> = 0X04, <API key> = 0X05, S5_REP_TTL_EXPIRED = 0X06, <API key> = 0X07, <API key> = 0X08, S5_REP_UNASSIGNED = 0X09, }; enum xstage { XSTAGE_HANDSHAKE, XSTAGE_REQUEST, XSTAGE_RESOLVE, XSTAGE_CONNECT, XSTAGE_UDP_RELAY, XSTAGE_FORWARD, XSTAGE_TERMINATE, XSTAGE_DEAD, }; #endif // for #ifndef _SOCKS_H
/* * SUBSUMPTION * */ /* * $Module: SUBSUMPTION * */ /* * MPI fuer Informatik * */ /* * This program is free software; you can redistribute * */ /* * it and/or modify it under the terms of the FreeBSD * */ /* * Licence. * */ /* * This program is distributed in the hope that it will * */ /* * FOR A PARTICULAR PURPOSE. See the LICENCE file * */ /* * for more details. * */ /* $Revision: 1.3 $ * */ /* $State: Exp $ * */ /* * Contact: * */ /* * Christoph Weidenbach * */ /* * MPI fuer Informatik * */ /* * Stuhlsatzenhausweg 85 * */ /* * 66123 Saarbruecken * */ /* * Email: spass@mpi-inf.mpg.de * */ /* * Germany * */ /* $RCSfile: subsumption.h,v $ */ #ifndef _SUBSUMPTION_ #define _SUBSUMPTION_ /* Includes */ #include "misc.h" #include "unify.h" #include "component.h" #include "vector.h" #include "clause.h" /* Functions */ static __inline__ int subs_NoException(void) { return -1; } void subs_Init(void); void subs_Free(void); BOOL subs_Subsumes(CLAUSE, CLAUSE, int, int); BOOL subs_SubsumesBasic(CLAUSE, CLAUSE, int, int); BOOL <API key>(CLAUSE, CLAUSE, BOOL, LIST*); BOOL subs_Idc(CLAUSE, CLAUSE); BOOL subs_IdcRes(CLAUSE, int, int); BOOL subs_IdcEq(CLAUSE, CLAUSE); BOOL subs_IdcEqMatch(CLAUSE, CLAUSE, SUBST); BOOL <API key>(CLAUSE, int, CLAUSE, int, SUBST); #endif
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the defined('MOODLE_INTERNAL') || die(); // get parent class require_once($CFG->dirroot.'/mod/hotpot/attempt/hp/renderer.php'); class <API key> extends <API key> { /** * init * * @param xxx $hotpot */ function init($hotpot) { parent::init($hotpot); array_unshift($this->templatesfolders, 'mod/hotpot/attempt/hp/6/templates'); } /** * <API key> for JMix and JMatch */ function <API key>() { // replace one line functions that get and set positions of positionable elements $search = array( '/(?<=function CardGetL).*/', '/(?<=function CardGetT).*/', '/(?<=function CardGetW).*/', '/(?<=function CardGetH).*/', '/(?<=function CardGetB).*/', '/(?<=function CardGetR).*/', '/(?<=function CardSetL).*/', '/(?<=function CardSetT).*/', '/(?<=function CardSetW).*/', '/(?<=function CardSetH).*/', ); $replace = array( "(){return getOffset(this.elm, 'Left')}", "(){return getOffset(this.elm, 'Top')}", "(){return getOffset(this.elm, 'Width')}", "(){return getOffset(this.elm, 'Height')}", "(){return getOffset(this.elm, 'Bottom')}", "(){return getOffset(this.elm, 'Right')}", "(NewL){setOffset(this.elm, 'Left', NewL)}", "(NewT){setOffset(this.elm, 'Top', NewT)}", "(NewW){setOffset(this.elm, 'Width', NewW)}", "(NewH){setOffset(this.elm, 'Height', NewH)}" ); $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } /** * <API key> * * @param xxx $type (optional, default='') */ function <API key>($type='') { switch ($type) { case 'dropdown': // adding missing brackets to call to Is_ExerciseFinished() in CheckAnswers() $search = '/(Finished\s*=\s*Is_ExerciseFinished)(;)/'; $this->headcontent = preg_replace($search, '$1()$2', $this->headcontent); break; case 'findit': // get position of last </style> tag and // insert CSS to make <b> and <em> tags bold // even within GapSpans added by javascript $search = '</style>'; if ($pos = strrpos($this->headcontent, $search)) { $insert = "\n" .'<!--[if IE 6]><style type="text/css">'."\n" .'span.GapSpan{'."\n" .' font-size:24px;'."\n" .'}'."\n" .'</style><![endif] .'<style type="text/css">'."\n" .'b span.GapSpan,'."\n" .'em span.GapSpan{'."\n" .' font-weight:inherit;'."\n" .'}'."\n" .'</style>'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos + strlen($search), 0); } break; case 'jintro': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; case 'jmemori': // add TimeOver variable, so we can use standard detection of quiz completion if ($pos = strpos($this->headcontent, 'var Score = 0;')) { $insert = "var TimeOver = false;\n"; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } // override table border collapse from standard Moodle styles if ($pos = strrpos($this->headcontent, '</style>')) { $insert = '' .'#'.$this->themecontainer.' form table'."\n" .'{'."\n" .' border-collapse: separate;'."\n" .' border-spacing: 2px;'."\n" .'}'."\n" ; $this->headcontent = substr_replace($this->headcontent, $insert, $pos, 0); } break; } } /** * <API key> * * @param xxx $hideclozeform (optional, default=false) */ function <API key>($hideclozeform=false) { // fix left aligned instructions in Rottmeier-based formats // JCloze: DropDown, FindIt(a)+(b), JGloss // JMatch: JMemori $search = '/<p id="Instructions">(.*?)<\/p>/is'; $replace = '<div id="Instructions">$1</div>'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); if ($hideclozeform) { // initially hide the Cloze text (so gaps are not revealed) $search = '/<(form id="Cloze" [^>]*)>/is'; $replace = '<$1 style="display:none;">'; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * <API key> * * @return xxx */ function <API key>() { // return a comma-separated list of js functions to be "fixed". // Each function name requires an corresponding function called: // fix_js_{$name} return 'Client,ShowElements,GetViewportHeight,PageDim,TrimString,<API key>,StartUp,GetUserName,PreloadImages,ShowMessage,HideFeedback,SendResults,Finish,WriteToInstructions,<API key>'; } /** * fix_js_Client * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Client(&$str, $start, $length) { $substr = substr($str, $start, $length); // refine detection of Chrome browser $search = 'this.geckoVer < 20020000'; if ($pos = strpos($substr, $search)) { $substr = substr_replace($substr, 'this.geckoVer > 10000000 && ', $pos, 0); } // add detection of Chrome browser $search = '/(\s*)if \(this\.min == false\)\{/s'; $replace = '$1' ."this.chrome = (this.ua.indexOf('Chrome') > 0);".'$1' ."if (this.chrome) {".'$1' ." this.geckoVer = 0;".'$1' ." this.safari = false;".'$1' ." this.min = true;".'$1' ."}$0" ; $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowElements * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_ShowElements(&$str, $start, $length) { $substr = substr($str, $start, $length); // hide <embed> tags (required for Chrome browser) if ($pos = strpos($substr, 'TagName == "object"')) { $substr = substr_replace($substr, 'TagName == "embed" || ', $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_PageDim * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_PageDim(&$str, $start, $length) { if ($this->usemoodletheme) { $obj = "document.getElementById('$this->themecontainer')"; // moodle } else { $obj = "document.<API key>('body')[0]"; // original } $replace = '' ."function getStyleValue(obj, property_name, propertyName){\n" ." var value = 0;\n" ." // Watch out for HTMLDocument which has no style property\n" ." // as this causes errors later in getComputedStyle() in FF\n" ." if (obj && obj.style){\n" ." ." if (document.defaultView && document.defaultView.getComputedStyle){\n" ." // Firefox, Opera, Safari\n" ." value = document.defaultView.getComputedStyle(obj, null).getPropertyValue(property_name);\n" ." } else if (obj.currentStyle) {" ." // IE (and Opera)\n" ." value = obj.currentStyle[propertyName];\n" ." }\n" ." if (typeof(value)=='string'){\n" ." var r = new RegExp('([0-9.]*)([a-z]+)');\n" ." var m = value.match(r);\n" ." if (m){\n" ." switch (m[2]){\n" ." case 'em':\n" ." // as far as I can see, only IE needs this\n" ." // other browsers have getComputedStyle() in px\n" ." if (typeof(obj.EmInPx)=='undefined'){\n" ." var div = obj.parentNode.appendChild(document.createElement('div'));\n" ." div.style.margin = '0px';\n" ." div.style.padding = '0px';\n" ." div.style.border = 'none';\n" ." div.style.height = '1em';\n" ." obj.EmInPx = getOffset(div, 'Height');\n" ." obj.parentNode.removeChild(div);\n" ." }\n" ." value = parseFloat(m[1] * obj.EmInPx);\n" ." break;\n" ." case 'px':\n" ." value = parseFloat(m[1]);\n" ." break;\n" ." default:\n" ." value = 0;\n" ." }\n" ." } else {\n" ." value = 0 ;\n" ." }\n" ." } else {\n" ." value = 0;\n" ." }\n" ." }\n" ." return value;\n" ."}\n" ."function isStrict(){\n" ." return false;\n" ." if (typeof(window.cache_isStrict)=='undefined'){\n" ." if (document.compatMode) { // ie6+\n" ." window.cache_isStrict = (document.compatMode=='CSS1Compat');\n" ." } else if (document.doctype){\n" ." var s = document.doctype.systemId || document.doctype.name; // n6 OR ie5mac\n" ." window.cache_isStrict = (s && s.indexOf('strict.dtd') >= 0);\n" ." } else {\n" ." window.cache_isStrict = false;\n" ." }\n" ." }\n" ." return window.cache_isStrict;\n" ."}\n" ."function setOffset(obj, type, value){\n" ." if (! obj){\n" ." return false;\n" ." }\n" ."\n" ." switch (type){\n" ." case 'Right':\n" ." return setOffset(obj, 'Width', value - getOffset(obj, 'Left'));\n" ." case 'Bottom':\n" ." return setOffset(obj, 'Height', value - getOffset(obj, 'Top'));\n" ." }\n" ."\n" ." if (isStrict()){\n" ." // set arrays of p(roperties) and s(ub-properties)\n" ." var properties = new Array('margin', 'border', 'padding');\n" ." switch (type){\n" ." case 'Top':\n" ." var sides = new Array('Top');\n" ." break;\n" ." case 'Left':\n" ." var sides = new Array('Left');\n" ." break;\n" ." case 'Width':\n" ." var sides = new Array('Left', 'Right');\n" ." break;\n" ." case 'Height':\n" ." var sides = new Array('Top', 'Bottom');\n" ." break;\n" ." default:\n" ." return 0;\n" ." }\n" ." for (var p=0; p<properties.length; p++){\n" ." for (var s=0; s<sides.length; s++){\n" ." var propertyName = properties[p] + sides[s];\n" ." var property_name = properties[p] + '-' + sides[s].toLowerCase();\n" ." value -= getStyleValue(obj, property_name, propertyName);\n" ." }\n" ." }\n" ." value = Math.floor(value);\n" ." }\n" ." if (type=='Top' || type=='Left') {\n" ." value -= getOffset(obj.offsetParent, type);\n" ." }\n" ." if (obj.style) {\n" ." obj.style[type.toLowerCase()] = value + 'px';\n" ." }\n" ."}\n" ."function getOffset(obj, type){\n" ." if (! obj){\n" ." return 0;\n" ." }\n" ." switch (type){\n" ." case 'Width':\n" ." case 'Height':\n" ." return eval('(obj.offset'+type+'||0)');\n" ."\n" ." case 'Top':\n" ." case 'Left':\n" ." return eval('(obj.offset'+type+'||0) + getOffset(obj.offsetParent, type)');\n" ."\n" ." case 'Right':\n" ." return getOffset(obj, 'Left') + getOffset(obj, 'Width');\n" ."\n" ." case 'Bottom':\n" ." return getOffset(obj, 'Top') + getOffset(obj, 'Height');\n" ."\n" ." default:\n" ." return 0;\n" ." } // end switch\n" ."}\n" ."function PageDim(){\n" ." var obj = $obj;\n" ." this.W = getOffset(obj, 'Width');\n" ." this.H = getOffset(obj, 'Height');\n" ." this.Top = getOffset(obj, 'Top');\n" ." this.Left = getOffset(obj, 'Left');\n" ."}\n" ."function getClassAttribute(className, attributeName){\n" ." ." if (! document.styleSheets){\n" ." return null; // old browser\n" ." }\n" ." var css = document.styleSheets;\n" ." var rules = (document.all ? 'rules' : 'cssRules');\n" ." var regexp = new RegExp('\\\\.'+className+'\\\\b');\n" ." try {\n" ." var i_max = css.length;\n" ." } catch(err) {\n" ." var i_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var i=0; i<i_max; i++){\n" ." try {\n" ." var ii_max = css[i][rules].length;\n" ." } catch(err) {\n" ." var ii_max = 0; // shouldn't happen !!\n" ." }\n" ." for (var ii=0; ii<ii_max; ii++){\n" ." if (! css[i][rules][ii].selectorText){\n" ." continue;\n" ." }\n" ." if (css[i][rules][ii].selectorText.match(regexp)){\n" ." if (css[i][rules][ii].style[attributeName]){\n" ." // class/attribute found\n" ." return css[i][rules][ii].style[attributeName];\n" ." }\n" ." }\n" ." }\n" ." }\n" ." // class/attribute not found\n" ." return null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * <API key> * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function <API key>(&$str, $start, $length) { $replace = '' ."function GetViewportSize(type){\n" ." if (eval('window.inner' + type)){\n" ." return eval('window.inner' + type);\n" ." }\n" ." if (document.documentElement){\n" ." if (eval('document.documentElement.client' + type)){\n" ." return eval('document.documentElement.client' + type);\n" ." }\n" ." }\n" ." if (document.body){\n" ." if (eval('document.body.client' + type)){\n" ." return eval('document.body.client' + type);\n" ." }\n" ." }\n" ." return 0;\n" ."}\n" ."function GetViewportHeight(){\n" ." return GetViewportSize('Height');\n" ."}\n" ."function GetViewportWidth(){\n" ." return GetViewportSize('Width');\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * remove_js_function * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @param xxx $function */ function remove_js_function(&$str, $start, $length, $function) { // remove this function $str = substr_replace($str, '', $start, $length); // remove all direct calls to this function $search = '/\s*'.$function.'\([^)]*\);/s'; $str = preg_replace($search, '', $str); } /** * fix_js_TrimString * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_TrimString(&$str, $start, $length) { $replace = '' ."function TrimString(InString){\n" ." if (typeof(InString)=='string'){\n" ." InString = InString.replace(new RegExp('^\\\\s+', 'g'), ''); // left\n" ." InString = InString.replace(new RegExp('\\\\s+$', 'g'), ''); // right\n" ." InString = InString.replace(new RegExp('\\\\s+', 'g'), ' '); // inner\n" ." }\n" ." return InString;\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_TypeChars * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_TypeChars(&$str, $start, $length) { if ($obj = $this-><API key>()) { $substr = substr($str, $start, $length); if (strpos($substr, 'document.selection')===false) { $replace = '' ."function TypeChars(Chars){\n" .$this-><API key>() ." if ($obj==null || $obj.style.display=='none') {\n" ." return;\n" ." }\n" ." $obj.focus();\n" ." if (typeof($obj.selectionStart)=='number') {\n" ." // FF, Safari, Chrome, Opera\n" ." var startPos = $obj.selectionStart;\n" ." var endPos = $obj.selectionEnd;\n" ." $obj.value = $obj.value.substring(0, startPos) + Chars + $obj.value.substring(endPos);\n" ." var newPos = startPos + Chars.length;\n" ." $obj.setSelectionRange(newPos, newPos);\n" ." } else if (document.selection) {\n" ." // IE (tested on IE6, IE7, IE8)\n" ." var rng = document.selection.createRange();\n" ." rng.text = Chars;\n" ." rng = null; // prevent memory leak\n" ." } else {\n" ." // this browser can't insert text, so append instead\n" ." $obj.value += Chars;\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } } } /** * <API key> * * @return xxx */ function <API key>() { return ''; } /** * <API key> * * @return xxx */ function <API key>() { return ''; } /** * fix_js_SendResults * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_SendResults(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'SendResults'); } /** * fix_js_GetUserName * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_GetUserName(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'GetUserName'); } /** * fix_js_Finish * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_Finish(&$str, $start, $length) { $this->remove_js_function($str, $start, $length, 'Finish'); } /** * <API key> * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function <API key>(&$str, $start, $length) { $substr = substr($str, $start, $length); // fix issue in IE8 which sometimes doesn't have Image object in popups $search = "Imgs[i] = new Image();"; if ($pos = strpos($substr, $search)) { $replace = "Imgs[i] = (window.Image ? new Image() : document.createElement('img'));"; $substr = substr_replace($substr, $replace, $pos, strlen($search)); } $str = substr_replace($str, $substr, $start, $length); } /** * <API key> * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function <API key>(&$str, $start, $length) { $substr = substr($str, $start, $length); if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML element exists\n" ." if (! document.getElementById('InstructionsDiv')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } if ($pos = strrpos($substr, '}')) { $append = "\n" ." <API key>(true);\n" ; $substr = substr_replace($substr, $append, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_ShowMessage * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length * @return xxx */ function fix_js_ShowMessage(&$str, $start, $length) { // the ShowMessage function is used by all HP6 quizzes $substr = substr($str, $start, $length); // only show feedback if the required HTML elements exist // this prevents JavaScript errors which block the returning of the quiz results to Moodle if ($pos = strpos($substr, '{')) { $insert = "\n" ." // check required HTML elements exist\n" ." if (! document.getElementById('FeedbackDiv')) return false;\n" ." if (! document.getElementById('FeedbackContent')) return false;\n" ." if (! document.getElementById('FeedbackOKButton')) return false;\n" ; $substr = substr_replace($substr, $insert, $pos+1, 0); } // hide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object', 'FeedbackContent'\);/s"; $replace = '' ."$0".'$1' ."if (C.chrome) {".'$1' ." ShowElements(false, 'embed');".'$1' ." ShowElements(true, 'embed', 'FeedbackContent');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); // fix "top" setting to position FeedbackDiv if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.<API key>('body')[0]"; // original } $search = "/FDiv.style.top = [^;]*;(\s*)(FDiv.style.display = [^;]*;)/s"; $replace = '' .'$1$2' .'$1'."var t = getOffset($canvas, 'Top');" .'$1'."setOffset(FDiv, 'Top', Math.max(t, <API key>(30)));" ; $substr = preg_replace($search, $replace, $substr, 1); // append link to student feedback form, if necessary if ($this->hotpot->studentfeedback) { $search = '/(\s*)var Output = [^;]*;/'; $replace = '' ."$0".'$1' ."if (window.FEEDBACK) {".'$1' ." Output += '".'<a href="javascript:hpFeedback();">'."' + FEEDBACK[6] + '</a>';".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); } $str = substr_replace($str, $substr, $start, $length); } /** * <API key> * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function <API key>(&$str, $start, $length) { $replace = '' ."function <API key>(){\n" ." if (C.ie) {\n" ." if (document.getElementById('Reading')){\n" ." var obj = document.getElementById('BottomNavBar');\n" ." if (obj){\n" ." obj.parentNode.removeChild(obj);\n" ." }\n" ." }\n" ." }\n" ."}" ; $str = substr_replace($str, $replace, $start, $length); } /** * <API key> * * @param xxx $substr (passed by reference) */ function <API key>(&$substr) { // fixes for Drag and Drop (JMatch and JMix) } /** * <API key> * * @param xxx $substr (passed by reference) */ function <API key>(&$substr) { // fix LeftCol (=left side of drag area) $search = '/(LeftColPos = [^;]+);/'; $replace = '$1 + pg.Left;'; $substr = preg_replace($search, $replace, $substr, 1); // fix DragTop (=top side of Drag area) $search = '/DragTop = [^;]+;/'; $replace = "DragTop = getOffset(document.getElementById('CheckButtonDiv'),'Bottom') + 10;"; $substr = preg_replace($search, $replace, $substr, 1); } /** * fix_js_StartUp * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_StartUp(&$str, $start, $length) { $substr = substr($str, $start, $length); // if necessary, fix drag area for JMatch or JMix drag-and-drop $this-><API key>($substr); if ($pos = strrpos($substr, '}')) { if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceajax = 1; } else { $forceajax = 0; } if ($this->can_continue()==hotpot::CONTINUE_RESUMEQUIZ) { $onunload_status = hotpot::STATUS_INPROGRESS; } else { $onunload_status = hotpot::STATUS_ABANDONED; } $append = "\n" ."// adjust size and position of Feedback DIV\n" ." if (! window.pg){\n" ." window.pg = new PageDim();\n" ." }\n" ." var FDiv = document.getElementById('FeedbackDiv');\n" ." if (FDiv){\n" ." var w = getOffset(FDiv, 'Width') || FDiv.style.width || getClassAttribute(FDiv.className, 'width');\n" ." if (w){\n" ." if (typeof(w)=='string' && w.indexOf('%')>=0){\n" ." var percent = parseInt(w);\n" ." } else {\n" ." var percent = Math.floor(100 * parseInt(w) / pg.W);\n" ." }\n" ." } else if (window.FeedbackWidth && window.DivWidth){\n" ." var percent = Math.floor(100 * FeedbackWidth / DivWidth);\n" ." } else {\n" ." var percent = 34; // default width as percentage\n" ." }\n" ." FDiv.style.display = 'block';\n" ." setOffset(FDiv, 'Left', pg.Left + Math.floor(pg.W * (50 - percent/2) / 100));\n" ." setOffset(FDiv, 'Width', Math.floor(pg.W * percent / 100));\n" ." FDiv.style.display = 'none';\n" ." }\n" ."\n" ."// create HP object (to collect and send responses)\n" ." window.HP = new ".$this->js_object_type."('".$this->can_clickreport()."','".$forceajax."');\n" ."\n" //."// call HP.onunload to send results when this page unloads\n" //." var s = '';\n" //." if (typeof(window.onunload)=='function'){\n" //." window.onunload_StartUp = onunload;\n" //." s += 'window.onunload_StartUp();'\n" //." window.onunload = new Function(s + 'if(window.HP){HP.status=$onunload_status;HP.onunload();object_destroy(HP);}return true;');\n" ." window.onunload = function() {\n" ." if (window.HP) {\n" ." HP.status=$onunload_status;\n" ." HP.onunload();\n" ." object_destroy(HP);\n" ." }\n" ." return true;\n" ." }\n" ."\n" ; $substr = substr_replace($substr, $append, $pos, 0); } // stretch the canvas vertically down, if there is a reading if ($pos = strrpos($substr, '}')) { // Reading is contained in <div class="LeftContainer"> // MainDiv is contained in <div class="RightContainer"> // when there is a reading. Otherwise, MainDiv is not contained. // ReadingDiv is used to show different reading for each question if ($this->usemoodletheme) { $canvas = "document.getElementById('$this->themecontainer')"; // moodle } else { $canvas = "document.<API key>('body')[0]"; // original } // None: $canvas = "document.getElementById('<API key>')" $id = $this->embed_object_id; $onload = $this->embed_object_onload; $insert = "\n" ."// fix canvas height, if necessary\n" ." if (! window.<API key>){\n" ." <API key>();\n" ." }\n" ."}\n" ."function <API key>(skipTimeout){\n" ." if (! skipTimeout){\n" ." if (navigator.userAgent.indexOf('Firefox/3')>=0){\n" ." var millisecs = 1000;\n" ." } else {\n" ." var millisecs = 500;\n" ." }\n" ." setTimeout('<API key>(true)', millisecs);\n" ." return;\n" ." }\n" ." var canvas = $canvas;\n" ." if (canvas){\n" ." var ids = new Array('Reading','ReadingDiv','MainDiv');\n" ." var i_max = ids.length;\n" ." for (var i=i_max-1; i>=0; i ." var obj = document.getElementById(ids[i]);\n" ." if (obj){\n" ." obj.style.height = ''; // reset height\n" ." } else {\n" ." ids.splice(i, 1); // remove this id\n" ." i_max ." }\n" ." }\n" ." var b = 0;\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." if (window.Segments) {\n" // JMix special ." var obj = document.getElementById('D'+(Segments.length-1));\n" ." if (obj) {\n" ." b = Math.max(b, getOffset(obj,'Bottom'));\n" ." }\n" ." }\n" ." if (b){\n" ." setOffset(canvas, 'Bottom', b + 21);\n" ." for (var i=0; i<i_max; i++){\n" ." var obj = document.getElementById(ids[i]);\n" ." setOffset(obj, 'Bottom', b);\n" ." }\n" ." }\n" ." }\n" ; if ($this->hotpot->navigation==hotpot::NAVIGATION_EMBED) { // stretch container object/iframe $insert .= '' ." if (parent.$onload) {\n" ." parent.$onload(null, parent.document.getElementById('".$this->embed_object_id."'));\n" ." }\n" ; } $substr = substr_replace($substr, $insert, $pos, 0); } $str = substr_replace($str, $substr, $start, $length); } /** * fix_js_HideFeedback * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_HideFeedback(&$str, $start, $length) { global $CFG; $substr = substr($str, $start, $length); // unhide <embed> elements on Chrome browser $search = "/(\s*)ShowElements\(true, 'object'\);/s"; $replace = '' .'$0$1' ."if (C.chrome) {".'$1' ." ShowElements(true, 'embed');".'$1' ."}" ; $substr = preg_replace($search, $replace, $substr, 1); $search = '/('.'\s*if \(Finished == true\){\s*)(?:.*?)(\s*})/s'; if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { // -1 : send form only (do not set form values, as that has already been done) $replace = '$1'.'HP.onunload(HP.status,-1);'.'$2'; } else { $replace = ''; // i.e. remove this if-block } $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * <API key> * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function <API key>(&$str, $start, $length) { $replace = '' ."function <API key>(){\n" ." var ReadingDiv = document.getElementById('ReadingDiv');\n" ." if (ReadingDiv){\n" ." var ReadingText = null;\n" ." var divs = ReadingDiv.<API key>('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='ReadingText' || divs[i].className=='TempReadingText'){\n" ." ReadingText = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." if (ReadingText && HiddenReadingShown){\n" ." SwapReadingTexts(ReadingText, HiddenReadingShown);\n" ." ReadingText = HiddenReadingShown;\n" ." HiddenReadingShown = false;\n" ." }\n" ." var HiddenReading = null;\n" ." if (QArray[CurrQNum]){\n" ." var divs = QArray[CurrQNum].<API key>('div');\n" ." for (var i=0; i<divs.length; i++){\n" ." if (divs[i].className=='HiddenReading'){\n" ." HiddenReading = divs[i];\n" ." break;\n" ." }\n" ." }\n" ." }\n" ." if (HiddenReading){\n" ." if (! ReadingText){\n" ." ReadingText = document.createElement('div');\n" ." ReadingText.className = 'ReadingText';\n" ." ReadingDiv.appendChild(ReadingText);\n" ." }\n" ." SwapReadingTexts(ReadingText, HiddenReading);\n" ." HiddenReadingShown = ReadingText;\n" ." }\n" ." var btn = document.getElementById('ShowMethodButton');\n" ." if (btn){\n" ." if (HiddenReadingShown){\n" ." if (btn.style.display!='none'){\n" ." btn.style.display = 'none';\n" ." }\n" ." } else {\n" ." if (btn.style.display=='none'){\n" ." btn.style.display = '';\n" ." }\n" ." }\n" ." }\n" ." btn = null;\n" ." ReadingDiv = null;\n" ." ReadingText = null;\n" ." HiddenReading = null;\n" ." }\n" ."}\n" ."function SwapReadingTexts(ReadingText, HiddenReading) {\n" ." <API key> = HiddenReading.parentNode;\n" ." <API key>.removeChild(HiddenReading);\n" ."\n" ." // replaceChild(new_node, old_node)\n" ." ReadingText.parentNode.replaceChild(HiddenReading, ReadingText);\n" ."\n" ." if (HiddenReading.<API key>){\n" ." HiddenReading.className = 'ReadingText';\n" ." } else {\n" ." HiddenReading.className = 'TempReadingText';\n" ." }\n" ." HiddenReading.style.display = '';\n" ."\n" ." if (ReadingText.className=='ReadingText'){\n" ." ReadingText.<API key> = true;\n" ." } else {\n" ." ReadingText.<API key> = false;\n" ." }\n" ." ReadingText.style.display = 'none';\n" ." ReadingText.className = 'HiddenReading';\n" ."\n" ." <API key>.appendChild(ReadingText);\n" ." <API key> = null;\n" ."}\n" ; $str = substr_replace($str, $replace, $start, $length); } /** * fix_js_CheckAnswers * * @param xxx $str (passed by reference) * @param xxx $start * @param xxx $length */ function fix_js_CheckAnswers(&$str, $start, $length) { // JCloze, JCross, JMatch : CheckAnswers // JMix : CheckAnswer // JQuiz : CheckFinished $substr = substr($str, $start, $length); // intercept Checks, if necessary if ($insert = $this-><API key>()) { if ($pos = strpos($substr, '{')) { $substr = substr_replace($substr, $insert, $pos+1, 0); } } // add extra argument to function - so it can be called from the "Give Up" button $name = $this-><API key>(); $search = '/(function '.$name.'\()(.*?)(\))/s'; $callback = array($this, '<API key>'); $substr = <API key>($search, $callback, $substr, 1); // add call to Finish function (including QuizStatus) $search = $this-><API key>(); $replace = $this-><API key>(); $substr = preg_replace($search, $replace, $substr, 1); $str = substr_replace($str, $substr, $start, $length); } /** * <API key> * * @param xxx $match * @return xxx */ function <API key>($match) { if (empty($match[2])) { return $match[1].'ForceQuizStatus'.$match[3]; } else { return $match[1].$match[2].',ForceQuizStatus'.$match[3]; } } /** * get_stop_onclick * * @return xxx */ function get_stop_onclick() { if ($name = $this-><API key>()) { return 'if('.$this-><API key>().')'.$name.'('.$this-><API key>().')'; } else { return 'if(window.HP)HP.onunload('.hotpot::STATUS_ABANDONED.')'; } } /** * <API key> * * @return xxx */ function <API key>() { // Note: "&&" in onclick must be encoded as html-entities for strict XHTML return '' ."confirm(" ."'".$this->hotpot->source->js_value_safe(get_string('confirmstop', 'hotpot'), true)."'" ."+'\\n\\n'+(window.onbeforeunload &amp;&amp; onbeforeunload()?(onbeforeunload()+'\\n\\n'):'')+" ."'".$this->hotpot->source->js_value_safe(get_string('pressoktocontinue', 'hotpot'), true)."'" .")" ; } /** * <API key> * * @return xxx */ function <API key>() { // the name of the javascript function into which the "give up" code should be inserted return ''; } /** * <API key> * * @return xxx */ function <API key>() { // the arguments required by the javascript function which the stop_function() code calls return hotpot::STATUS_ABANDONED; } /** * <API key> * * @return xxx */ function <API key>() { // JMix and JQuiz each have their own version of this function return "\n" ." // intercept this Check\n" ." HP.onclickCheck();\n" ; } /** * <API key> * * @return xxx */ function <API key>() { // JCloze : AllCorrect || Finished // JCross : AllCorrect || TimeOver // JMatch : AllDone || TimeOver // JMix : AllDone || TimeOver (in the CheckAnswer function) // JQuiz : AllDone (in the CheckFinished function) return '/\s*if \(\((\w+) == true\)\|\|\(\w+ == true\)\)({).*?}\s*/s'; } /** * <API key> * * @return xxx */ function <API key>() { // $1 : name of the "all correct/done" variable // $2 : opening curly brace of if-block plus any following text to be kept if ($this->hotpot->delay3==hotpot::TIME_AFTEROK) { $flag = 1; // set form values only } else { $flag = 0; // set form values and send form } if ($this->hotpot->delay3==hotpot::TIME_DISABLE) { $forceredirect = '(ForceQuizStatus ? 1 : 0)'; } else { $forceredirect = 1; } return "\n" ." if ($1){\n" ." var QuizStatus = 4; // completed\n" ." } else if (ForceQuizStatus){\n" ." var QuizStatus = ForceQuizStatus; // 3=abandoned\n" ." } else if (TimeOver){\n" ." var QuizStatus = 2; // timed out\n" ." } else {\n" ." var QuizStatus = 1; // in progress\n" ." }\n" ." if (QuizStatus > 1) $2\n" ." if (window.Interval) {\n" ." clearInterval(window.Interval);\n" ." }\n" ." TimeOver = true;\n" ." Locked = true;\n" ." Finished = true;\n" ." }\n" ." if (Finished || HP.sendallclicks){\n" ." var ForceRedirect = $forceredirect;\n" ." if (ForceQuizStatus || QuizStatus==1){\n" ." // send results immediately\n" ." HP.onunload(QuizStatus, 0, ForceRedirect);\n" ." } else {\n" ." // send results after delay\n" ." setTimeout('HP.onunload('+QuizStatus+',$flag,'+ForceRedirect+')', SubmissionTimeout);\n" ." }\n" ." }\n" ; } /** * postprocessing * * after headcontent and bodycontent have been setup and * before content is sent to browser, we add title edit icon, * insert submission form, adjust navigation butons (if any) * and add external javascripts (to the top of the page) */ function postprocessing() { $this->fix_title_icons(); $this->fix_submissionform(); $this-><API key>(); foreach ($this->javascripts as $script) { $this->page->requires->js('/'.$script, true); } } /** * <API key> * * @return xxx */ function <API key>() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // replace relative URLs in <button class="NavButton" ... onclick="location='...'"> $search = '/'.'(?<='.'onclick="'."location='".')'."([^']*)".'(?='."'; return false;".'")'.'/is'; $callback = array($this, '<API key>'); $this->bodycontent = <API key>($search, $callback, $this->bodycontent); // replace history.back() in <button class="NavButton" ... onclick="history.back(); ..."> // with a link to the course page $params = array('id'=>$this->hotpot->course->id); $search = '/'.'(?<='.'onclick=")'.'history\.back\(\)'.'(?=; return false;")'.'/'; $replace = "location='".new moodle_url('/course/view.php', $params)."'"; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent); } } /** * fix_TimeLimit */ function fix_TimeLimit() { if ($this->hotpot->timelimit > 0) { $search = '/(?<=var Seconds = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $this->hotpot->timelimit, $this->headcontent, 1); } } /** * <API key> */ function <API key>() { if ($this->hotpot->delay3==hotpot::TIME_TEMPLATE) { // use default from source/template file (=30000 ms =30 seconds) if ($this-><API key>) { $timeout = null; } else { $timeout = 30000; // = 30 secs is HP default } } else { if ($this->hotpot->delay3 >= 0) { $timeout = $this->hotpot->delay3 * 1000; // milliseconds } else { $timeout = 0; // i.e. immediately } } if (is_null($timeout)) { return; // nothing to do } if ($this-><API key>) { // remove HPNStartTime $search = '/var HPNStartTime\b[^;]*?;\s*/'; $this->headcontent = preg_replace($search, '', $this->headcontent, 1); // reset the value of SubmissionTimeout $search = '/(?<=var SubmissionTimeout = )\d+(?=;)/'; $this->headcontent = preg_replace($search, $timeout, $this->headcontent, 1); } else { // Rhubarb, Sequitur and Quandary $search = '/var FinalScore = 0;/'; $replace = '$0'."\n".'var SubmissionTimeout = '.$timeout.';'; $this->headcontent = preg_replace($search, $replace, $this->headcontent, 1); } } /** * fix_navigation */ function fix_navigation() { if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL) { // do nothing - leave navigation as it is return; } // insert the stop button, if required if ($this->hotpot->stopbutton) { // replace top nav buttons with a single stop button if ($this->hotpot->stopbutton==hotpot::STOPBUTTON_LANGPACK) { if ($pos = strpos($this->hotpot->stoptext, '_')) { $mod = substr($this->hotpot->stoptext, 0, $pos); $str = substr($this->hotpot->stoptext, $pos + 1); $stoptext = get_string($str, $mod); } else if ($this->hotpot->stoptext) { $stoptext = get_string($this->hotpot->stoptext); } else { $stoptext = ''; } } else { $stoptext = $this->hotpot->stoptext; } if (trim($stoptext)=='') { $stoptext = get_string('giveup', 'hotpot'); } $confirm = get_string('confirmstop', 'hotpot'); //$search = '/<!-- BeginTopNavButtons -->'.'.*?'.'<!-- EndTopNavButtons -->/s'; $search = '/<(div class="Titles")>/s'; $replace = '<$1 style="position: relative">'."\n\t" .'<div class="hotpotstopbutton">' .'<button class="FuncButton" ' .'onclick="'.$this->get_stop_onclick().'" ' .'onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" ' .'onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" ' .'onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)">' .hotpot_textlib('utf8_to_entities', $stoptext) .'</button>' .'</div>' ; $this->bodycontent = preg_replace($search, $replace, $this->bodycontent, 1); } // remove (remaining) navigation buttons $search = '/<!-- Begin(Top|Bottom)NavButtons -->'.'.*?'.'<!-- End'.'\\1'.'NavButtons -->/s'; $this->bodycontent = preg_replace($search, '', $this->bodycontent); } /** * fix_filters * * @return xxx */ function fix_filters() { global $CFG; if (isset($CFG->textfilters)) { $textfilters = $CFG->textfilters; } else { $textfilters = ''; } if ($this->hotpot->usefilters) { $filters = <API key>($this->hotpot->context); $filters = array_keys($filters); } else { $filters = array(); } if ($this->hotpot->useglossary && ! in_array('mod/glossary', $filters)) { $filters[] = 'mod/glossary'; } if ($this->hotpot->usemediafilter) { // exclude certain unnecessary or miscreant $filters // - "mediaplugins" because it duplicates work done by "usemediafilter" setting // - "asciimath" because it does not behave like a filter is supposed to behave $filters = preg_grep('/^filter\/(mediaplugin|asciimath)$/', $filters, PREG_GREP_INVERT); } $CFG->textfilters = implode(',', $filters); $this-><API key>(); $this-><API key>(); $CFG->textfilters = $textfilters; // fix unwanted conversions by the Moodle's Tex filter if (preg_match('/jcross|jmix/', get_class($this))) { $search = '/(?<=replace\(\/)'.'<a[^>]*><img[^>]*class="texrender"[^>]*title="(.*?)"[^>]*><\/a>'.'(?=\/g)/is'; $replace = '\['.'$1'.'\]'; $this->headcontent = preg_replace($search, $replace, $this->headcontent); } // make sure openpopup() function is available if needed (for glossary entries) // Note: this could also be done using <API key>($this->htmlcontent) // but that function expects entire htmlcontent, where we would prefer just the headcontent if ($this->hotpot->navigation==hotpot::NAVIGATION_ORIGINAL && in_array('mod/glossary', $filters)) { // add openwindow() function (from lib/javascript.php) $this->headcontent .= "\n" .'<script type="text/javascript">'."\n" .'//<![CDATA['."\n" .'function openpopup(url, name, options, fullscreen) {'."\n" .' var fullurl = "'.$CFG->httpswwwroot.'" + url;'."\n" .' var windowobj = window.open(fullurl, name, options);'."\n" .' if (!windowobj) {'."\n" .' return true;'."\n" .' }'."\n" .' if (fullscreen) {'."\n" .' windowobj.moveTo(0, 0);'."\n" .' windowobj.resizeTo(screen.availWidth, screen.availHeight);'."\n" .' }'."\n" .' windowobj.focus();'."\n" .' return false;'."\n" .'}'."\n" .' .'</script>' ; } } /** * <API key> */ function <API key>() { if ($names = $this->headcontent_strings) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])*\s*=\s*')(.*)(';)".'$/m'; $callback = array($this, '<API key>'); $this->headcontent = <API key>($search, $callback, $this->headcontent); } if ($names = $this->headcontent_arrays) { $search = '/^'."((?:var )?(?:$names)(?:\[\d+\])* = new Array\()(.*)(\);)".'$/m'; $callback = array($this, '<API key>'); $this->headcontent = <API key>($search, $callback, $this->headcontent); } } /** * <API key> * * @param xxx $match * @return xxx */ function <API key>($match) { // I[q][0][a] = new Array('JQuiz answer text', 'feedback', 0, 0, 0) $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; $search = "/(')((?:\\\\\\\\|\\\\'|[^'])*)(')/"; $callback = array($this, '<API key>'); return $before.<API key>($search, $callback, $str).$after; } /** * <API key> * * @param xxx $match * @return xxx */ function <API key>($match) { // var YourScoreIs = 'Your score is'; // I[q][1][a][2] = 'JCloze clue'; global $CFG; static $replace_pairs = array( // backslashes and quotes '\\\\'=>'\\', "\\'"=>"'", '\\"'=>'"', // newlines '\\n'=>"\n", // other (closing tag is for XHTML compliance) '\\0'=>"\0", '<\\/'=>'</' ); $before = $match[1]; $str = $match[count($match) - 2]; $after = $match[count($match) - 1]; // unescape backslashes, quote and newlines $str = strtr($str, $replace_pairs); // convert javascript unicode $search = '/\\\\u([0-9a-f]{4})/i'; $str = $this->filter_text_to_utf8($str, $search); // convert html entities $search = '/&#x([0-9a-f]+);/i'; $str = $this->filter_text_to_utf8($str, $search); // fix relative urls $str = $this->fix_relativeurls($str); // filter string, // $str = filter_text($str); // return safe javascript unicode return $before.$this->hotpot->source->js_value_safe($str, true).$after; } /** * <API key> * * @param xxx $str * @param xxx $search * @return string $str * @return boolean $modified */ function filter_text_to_utf8($str, $search) { if (preg_match_all($search, $str, $matches, PREG_OFFSET_CAPTURE)) { $i_max = count($matches[0]) - 1; for ($i=$i_max; $i>=0; $i list($match, $start) = $matches[0][$i]; $char = $matches[1][$i][0]; $char = hotpot_textlib('code2utf8', hexdec($char)); $str = substr_replace($str, $char, $start, strlen($match)); } } return $str; } /** * <API key> */ function <API key>() { // convert entities to utf8, filter text and convert back //$this->bodycontent = hotpot_textlib('entities_to_utf8', $this->bodycontent); //$this->bodycontent = filter_text($this->bodycontent); //$this->bodycontent = hotpot_textlib('utf8_to_entities', $this->bodycontent); } /** * fix_feedbackform */ function fix_feedbackform() { // we are aiming to generate the following javascript to send to the client //FEEDBACK = new Array(); //FEEDBACK[0] = ''; // url of feedback page/script //FEEDBACK[1] = ''; // array of array('teachername', 'value'); //FEEDBACK[2] = ''; // 'student name' [formmail only] //FEEDBACK[3] = ''; // 'student email' [formmail only] //FEEDBACK[4] = ''; // window width //FEEDBACK[5] = ''; // window height //FEEDBACK[6] = ''; // 'Send a message to teacher' [prompt/button text] //FEEDBACK[7] = ''; // 'Title' //FEEDBACK[8] = ''; // 'Teacher' //FEEDBACK[9] = ''; // 'Message' //FEEDBACK[10] = ''; // 'Close this window' global $CFG, $USER; $feedback = array(); switch ($this->hotpot->studentfeedback) { case hotpot::FEEDBACK_NONE: // do nothing - feedback form is not required break; case hotpot::FEEDBACK_WEBPAGE: if ($this->hotpot->studentfeedbackurl) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; } else { $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::FEEDBACK_FORMMAIL: if ($this->hotpot->studentfeedbackurl) { $teachers = $this-><API key>(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'".addslashes_js($this->hotpot->studentfeedbackurl)."'"; $feedback[1] = $teachers; $feedback[2] = "'".addslashes_js(fullname($USER))."'"; $feedback[3] = "'".addslashes_js($USER->email)."'"; $feedback[4] = 500; // width $feedback[5] = 300; // height } else { // no teachers (or no feedback url) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; case hotpot::<API key>: $cmids = array(); if ($modinfo = get_fast_modinfo($this->hotpot->course)) { foreach ($modinfo->cms as $cmid=>$mod) { if ($mod->modname=='forum' && $mod->visible) { $cmids[] = $cmid; } } } switch (count($cmids)) { case 0: $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; break; // no forums !! case 1: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/view.php?id='.$cmids[0]."'"; break; default: $feedback[0] = "'".$CFG->wwwroot.'/mod/forum/index.php?id='.$this->hotpot->course->id."'"; } break; case hotpot::<API key>: if ($CFG->messaging) { $teachers = $this-><API key>(); } else { $teachers = ''; } if ($teachers) { $feedback[0] = "'$CFG->wwwroot/message/discussion.php?id='"; $feedback[1] = $teachers; $feedback[4] = 400; // width $feedback[5] = 500; // height } else { // no teachers (or no Moodle messaging) $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } break; default: // unrecognized feedback setting, so reset it to something valid $this->hotpot->studentfeedback = hotpot::FEEDBACK_NONE; } if ($this->hotpot->studentfeedback==hotpot::FEEDBACK_NONE) { // do nothing - feedback form is not required } else { // complete remaining feedback fields if ($this->hotpot->studentfeedback==hotpot::<API key>) { $feedback[6] = "'".addslashes_js(get_string('feedbackdiscuss', 'hotpot'))."'"; } else { // FEEDBACK_WEBPAGE, FEEDBACK_FORMMAIL, <API key> $feedback[6] = "'".addslashes_js(get_string('feedbacksendmessage', 'hotpot'))."'"; } $feedback[7] = "'".addslashes_js(get_string('feedback'))."'"; $feedback[8] = "'".addslashes_js(get_string('<API key>'))."'"; $feedback[9] = "'".addslashes_js(get_string('messagebody'))."'"; $feedback[10] = "'".addslashes_js(get_string('closewindow'))."'"; $js = ''; foreach ($feedback as $i=>$str) { $js .= 'FEEDBACK['.$i."] = $str;\n"; } $js = '<script type="text/javascript">'."\n//<![CDATA[\n"."FEEDBACK = new Array();\n".$js."//]]>\n</script>\n"; if ($this->usemoodletheme) { $this->headcontent .= $js; } else { $this->bodycontent = preg_replace('/<\/head>/i', "$js</head>", $this->bodycontent, 1); } } } /** * <API key> * * @return xxx */ function <API key>() { $context = hotpot_get_context(CONTEXT_COURSE, $this->hotpot->source->courseid); $teachers = <API key>($context, 'mod/hotpot:reviewallattempts'); $details = array(); if (isset($teachers) && count($teachers)) { if ($this->hotpot->studentfeedback==hotpot::<API key>) { $detail = 'id'; } else { $detail = 'email'; } foreach ($teachers as $teacher) { $details[] = "new Array('".addslashes_js(fullname($teacher))."', '".addslashes_js($teacher->$detail)."')"; } } if ($details = implode(', ', $details)) { return 'new Array('.$details.')'; } else { return ''; // no teachers } } /** * fix_reviewoptions */ function fix_reviewoptions() { // enable / disable review options } /** * fix_submissionform */ function fix_submissionform() { $params = array( 'id' => $this->hotpot->create_attempt(), $this->scorefield => '0', 'detail' => '0', 'status' => '0', 'starttime' => '0', 'endtime' => '0', 'redirect' => '0', ); $attributes = array( 'id' => $this->formid, 'autocomplete' => 'off' ); $form_start = $this->form_start('submit.php', $params, $attributes); $search = '<!-- BeginSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('<API key>', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $form_start, $pos, strlen($search)); $search = '<!-- EndSubmissionForm -->'; if (! $pos = strpos($this->bodycontent, $search)) { throw new moodle_exception('<API key>', 'hotpot'); } $this->bodycontent = substr_replace($this->bodycontent, $this->form_end(), $pos, strlen($search)); } /** * <API key> * * @return xxx */ function <API key>() { return '' .' if(window.<API key>) {'."\n" .' <API key>();'."\n" .' }'."\n" ; } // captions and messages /** * expand_AlsoCorrect * * @return xxx */ function expand_AlsoCorrect() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_BottomNavBar * * @return xxx */ function expand_BottomNavBar() { return $this->expand_NavBar('BottomNavBar'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',<API key>'); } /** * expand_CheckCaption * * @return xxx */ function expand_CheckCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,check-caption'); } /** * expand_ContentsURL * * @return xxx */ function expand_ContentsURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-url'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-indicator'); } /** * expand_Back * * @return xxx */ function expand_Back() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-back'); } /** * expand_BackCaption * * @return xxx */ function expand_BackCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,back-caption'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',case-sensitive'); } /** * expand_ClickToAdd * * @return xxx */ function expand_ClickToAdd() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',click-to-add'); } /** * expand_ClueCaption * * @return xxx */ function expand_ClueCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,clue-caption'); } /** * expand_Clues * * @return xxx */ function expand_Clues() { // Note: WinHotPot6 uses "include-clues", but JavaHotPotatoes6 uses "include-clue" (missing "s") return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clues'); } /** * expand_Contents * * @return xxx */ function expand_Contents() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-contents'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,contents-caption'); } /** * expand_Correct * * @return xxx */ function expand_Correct() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-correct'; } else { $tag = 'guess-correct'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',delete-caption'); } /** * <API key> * * @return xxx */ function <API key>() { $dc = ''; if ($value = $this->hotpot->source->xml_value('', "['rdf:RDF'][0]['@']['xmlns:dc']")) { $dc .= '<link rel="schema.DC" href="'.str_replace('"', '&quot;', $value).'" />'."\n"; } if (is_array($this->hotpot->source->xml_value('rdf:RDF,rdf:Description'))) { $names = array('DC:Creator'=>'dc:creator', 'DC:Title'=>'dc:title'); foreach ($names as $name => $tag) { $i = 0; $values = array(); while($value = $this->hotpot->source->xml_value("rdf:RDF,rdf:Description,$tag", "[$i][' if ($value = trim(strip_tags($value))) { $values[strtoupper($value)] = htmlspecialchars($value); } $i++; } if ($value = implode(', ', $values)) { $dc .= '<meta name="'.$name.'" content="'.$value.'" />'."\n"; } } } return $dc; } /** * expand_EMail * * @return xxx */ function expand_EMail() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,email'); } /** * <API key> * this string only used in <API key>.js_ which is not required in Moodle * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js('data,title'); } /** * expand_ExBGColor * * @return xxx */ function expand_ExBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',exercise-subtitle'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value('data,title'); } /** * expand_FontFace * * @return xxx */ function expand_FontFace() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-face'); } /** * expand_FontSize * * @return xxx */ function expand_FontSize() { $value = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,font-size'); return (empty($value) ? 'small' : $value); } /** * expand_FormMailURL * * @return xxx */ function expand_FormMailURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,formmail-url'); } /** * <API key> * * @return xxx */ function <API key>() { global $CFG; return $this->hotpot->source->xml_value('version').'.x (Moodle '.$CFG->release.', HotPot '.hotpot::get_version_info('release').')'; } /** * <API key> * * @return xxx */ function <API key>() { // top-left of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this-><API key>($color, '#ffffff'); } /** * <API key> * * @return xxx */ function <API key>() { // bottom right of buttons $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ex-bg-color'); return $this-><API key>($color, '#000000'); } /** * expand_GiveHint * * @return xxx */ function expand_GiveHint() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-correct-letter'); } /** * expand_GraphicURL * * @return xxx */ function expand_GraphicURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,graphic-url'); } /** * expand_GuessCorrect * * @return xxx */ function expand_GuessCorrect() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-correct'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',guess-incorrect'); } /** * expand_HeaderCode * * @return xxx */ function expand_HeaderCode() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,header-code'); } /** * expand_Hint * * @return xxx */ function expand_Hint() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-hint'); } /** * expand_HintCaption * * @return xxx */ function expand_HintCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,hint-caption'); } /** * expand_Incorrect * * @return xxx */ function expand_Incorrect() { if ($this->hotpot->source->hbs_quiztype=='jcloze') { $tag = 'guesses-incorrect'; } else { $tag = 'guess-incorrect'; } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,incorrect-indicator'); } /** * expand_Instructions * * @return xxx */ function expand_Instructions() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',instructions'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->expand_template('hp6browsercheck.js_'); } /** * expand_JSButtons * * @return xxx */ function expand_JSButtons() { return $this->expand_template('hp6buttons.js_'); } /** * expand_JSCard * * @return xxx */ function expand_JSCard() { return $this->expand_template('hp6card.js_'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->expand_template('hp6checkshortanswer.js_'); } /** * expand_JSHotPotNet * * @return xxx */ function expand_JSHotPotNet() { return $this->expand_template('hp6hotpotnet.js_'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->expand_template('hp6sendresults.js_'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->expand_template('hp6showmessage.js_'); } /** * expand_JSTimer * * @return xxx */ function expand_JSTimer() { return $this->expand_template('hp6timer.js_'); } /** * expand_JSUtilities * * @return xxx */ function expand_JSUtilities() { return $this->expand_template('hp6utilities.js_'); } /** * expand_LastQCaption * * @return xxx */ function expand_LastQCaption() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,last-q-caption'); return ($caption=='<=' ? '&lt;=' : $caption); } /** * expand_LinkColor * * @return xxx */ function expand_LinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,link-color'); } /** * expand_NamePlease * * @return xxx */ function expand_NamePlease() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,name-please'); } /** * expand_NavBar * * @param xxx $navbarid (optional, default='') * @return xxx */ function expand_NavBar($navbarid='') { $this->navbarid = $navbarid; $navbar = $this->expand_template('hp6navbar.ht_'); unset($this->navbarid); return $navbar; } /** * expand_NavBarID * * @return xxx */ function expand_NavBarID() { // $this->navbarid is set in "$this->expand_NavBar" return empty($this->navbarid) ? '' : $this->navbarid; } /** * expand_NavBarJS * * @return xxx */ function expand_NavBarJS() { return $this->expand_NavButtons(); } /** * expand_NavButtons * * @return xxx */ function expand_NavButtons() { return ($this->expand_Back() || $this->expand_NextEx() || $this->expand_Contents()); } /** * expand_NavTextColor * * @return xxx */ function expand_NavTextColor() { // might be 'title-color' ? return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * expand_NavBarColor * * @return xxx */ function expand_NavBarColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); } /** * <API key> * * @return xxx */ function <API key>() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this-><API key>($color, '#ffffff'); } /** * <API key> * * @return xxx */ function <API key>() { $color = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,nav-bar-color'); return $this-><API key>($color, '#000000'); } /** * expand_NextCaption * * @return xxx */ function expand_NextCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-caption'); } /** * expand_NextCorrect * * @return xxx */ function expand_NextCorrect() { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tag = 'next-correct-letter'; // jquiz } else { $tag = 'next-correct-part'; // jmix } return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.','.$tag); } /** * expand_NextEx * * @return xxx */ function expand_NextEx() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,include-next-ex'); } /** * <API key> * * @return xxx */ function <API key>() { $caption = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-ex-caption'); return ($caption=='=>' ? '=&gt;' : $caption); } /** * expand_NextQCaption * * @return xxx */ function expand_NextQCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,next-q-caption'); } /** * expand_NextExURL * * @return xxx */ function expand_NextExURL() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',next-ex-url'); } /** * expand_OKCaption * * @return xxx */ function expand_OKCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,ok-caption'); } /** * expand_PageBGColor * * @return xxx */ function expand_PageBGColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,page-bg-color'); } /** * expand_PlainTitle * * @return xxx */ function expand_PlainTitle() { return $this->hotpot->source->xml_value('data,title'); } /** * <API key> * * @return xxx */ function <API key>() { $value = $this-><API key>(); return empty($value) ? false : true; } /** * <API key> * * @return xxx */ function <API key>() { if (! isset($this->PreloadImageList)) { $this->PreloadImageList = ''; $images = array(); // extract all src values from <img> tags in the xml file $search = '/&amp;#x003C;img.*?src=&quot;(.*?)&quot;.*?&amp;#x003E;/is'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } // extract all urls from HotPot's [square bracket] notation // e.g. [%sitefiles%/images/screenshot.jpg image 350 265 center] $search = '/\['."([^\?\]]*\.(?:jpg|gif|png)(?:\?[^ \t\r\n\]]*)?)".'[^\]]*'.'\]/s'; if (preg_match_all($search, $this->hotpot->source->filecontents, $matches)) { $images = array_merge($images, $matches[1]); } if (count($images)) { $images = array_unique($images); $this->PreloadImageList = "\n\t\t'".implode("',\n\t\t'", $images)."'\n\t"; } } return $this->PreloadImageList; } /** * expand_Reading * * @return xxx */ function expand_Reading() { return $this->hotpot->source->xml_value_int('data,reading,include-reading'); } /** * expand_ReadingText * * @return xxx */ function expand_ReadingText() { $title = $this->expand_ReadingTitle(); if ($value = $this->hotpot->source->xml_value('data,reading,reading-text')) { $value = '<div class="ReadingText">'.$value.'</div>'; } else { $value = ''; } return $title.$value; } /** * expand_ReadingTitle * * @return xxx */ function expand_ReadingTitle() { $value = $this->hotpot->source->xml_value('data,reading,reading-title'); return empty($value) ? '' : ('<h3 class="ExerciseSubtitle">'.$value.'</h3>'); } /** * expand_Restart * * @return xxx */ function expand_Restart() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-restart'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,restart-caption'); } /** * expand_Scorm12 * * @return xxx */ function expand_Scorm12() { return false; // HP scorm functionality is always disabled in Moodle } /** * expand_Seconds * * @return xxx */ function expand_Seconds() { return $this->hotpot->source->xml_value('data,timer,seconds'); } /** * expand_SendResults * * @return xxx */ function expand_SendResults() { return false; // send results (via formmail) is always disabled in Moodle // $tags = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',send-email'; // return $this->hotpot->source->xml_value($tags); } /** * <API key> * * @return xxx */ function <API key>($convert_to_unicode=false) { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,<API key>'); } /** * expand_ShowAnswer * * @return xxx */ function expand_ShowAnswer() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-show-answer'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,solution-caption'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,<API key>'); } /** * expand_StyleSheet * * @return xxx */ function expand_StyleSheet() { return $this->expand_template('hp6.cs_'); } /** * expand_TextColor * * @return xxx */ function expand_TextColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,text-color'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',also-correct'); } /** * expand_ThisMuch * * @return xxx */ function expand_ThisMuch() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',this-much-correct'); } /** * expand_Timer * * @return xxx */ function expand_Timer() { if ($this->hotpot->timelimit < 0) { // use setting in source file return $this->hotpot->source->xml_value_int('data,timer,include-timer'); } else { // override setting in source file return $this->hotpot->timelimit; } } /** * expand_TimesUp * * @return xxx */ function expand_TimesUp() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,times-up'); } /** * expand_TitleColor * * @return xxx */ function expand_TitleColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,title-color'); } /** * expand_TopNavBar * * @return xxx */ function expand_TopNavBar() { return $this->expand_NavBar('TopNavBar'); } /** * expand_Undo * * @return xxx */ function expand_Undo() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-undo'); } /** * expand_UndoCaption * * @return xxx */ function expand_UndoCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,undo-caption'); } /** * expand_UserDefined1 * * @return xxx */ function expand_UserDefined1() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-1'); } /** * expand_UserDefined2 * * @return xxx */ function expand_UserDefined2() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-2'); } /** * expand_UserDefined3 * * @return xxx */ function expand_UserDefined3() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,user-string-3'); } /** * expand_VLinkColor * * @return xxx */ function expand_VLinkColor() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,vlink-color'); } /** * expand_YourScoreIs * * @return xxx */ function expand_YourScoreIs() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,your-score-is'); } /** * expand_Keypad * * @return xxx */ function expand_Keypad() { $str = ''; if ($this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-keypad')) { // these characters must always be in the keypad $chars = array(); $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,global,keypad-characters')); // append other characters used in the answers switch ($this->hotpot->source->hbs_quiztype) { case 'jcloze': $tags = 'data,gap-fill,question-record'; break; case 'jquiz': $tags = 'data,questions,question-record'; break; case 'rhubarb': $tags = 'data,rhubarb-text'; break; default: $tags = ''; } if ($tags) { $q = 0; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { if ($this->hotpot->source->hbs_quiztype=='jquiz') { $answers = $question."['answers'][0][' } else { $answers = $question; } $a = 0; while (($answer=$answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $this->add_keypad_chars($chars, $this->hotpot->source->xml_value($tags, $answer."['text'][0][' $a++; } $q++; } } // remove duplicate characters and sort $chars = array_unique($chars); usort($chars, array($this, '<API key>')); // create keypad buttons for each character foreach ($chars as $char) { $str .= '<button onclick="'."TypeChars('".$this->hotpot->source->js_value_safe($char, true)."');".'return false;">'.$char.'</button>'; } } return $str; } /** * add_keypad_chars * * @param xxx $chars (passed by reference) * @param xxx $text */ function add_keypad_chars(&$chars, $text) { if (preg_match_all('/&[^;]+;/', $text, $more_chars)) { $chars = array_merge($chars, $more_chars[0]); } } /** * <API key> * * @param xxx $a_char * @param xxx $b_char * @return xxx */ function <API key>($a_char, $b_char) { $a_value = $this-><API key>($a_char); $b_value = $this-><API key>($b_char); if ($a_value < $b_value) { return -1; } if ($a_value > $b_value) { return 1; } // values are equal return 0; } /** * <API key> * * @param xxx $char * @return xxx */ function <API key>($char) { $char = hotpot_textlib('entities_to_utf8', $char); $ord = ord($char); // lowercase letters (plain or accented) if (($ord>=97 && $ord<=122) || ($ord>=224 && $ord<=255)) { return ($ord-31) + ($ord/1000); } // subscripts and superscripts switch ($ord) { case 0x2070: return 48.1; // super 0 = ord('0') + 0.1 case 0x00B9: return 49.1; // super 1 case 0x00B2: return 50.1; // super 2 case 0x00B3: return 51.1; // super 3 case 0x2074: return 52.1; // super 4 case 0x2075: return 53.1; // super 5 case 0x2076: return 54.1; // super 6 case 0x2077: return 55.1; // super 7 case 0x2078: return 56.1; // super 8 case 0x2079: return 57.1; // super 9 case 0x207A: return 43.1; // super + case 0x207B: return 45.1; // super - case 0x207C: return 61.1; // super = case 0x207D: return 40.1; // super ( case 0x207E: return 41.1; // super ) case 0x207F: return 110.1; // super n case 0x2080: return 47.9; // sub 0 = ord('0') - 0.1 case 0x2081: return 48.9; // sub 1 case 0x2082: return 49.9; // sub 2 case 0x2083: return 50.9; // sub 3 case 0x2084: return 51.9; // sub 4 case 0x2085: return 52.9; // sub 5 case 0x2086: return 53.9; // sub 6 case 0x2087: return 54.9; // sub 7 case 0x2088: return 55.9; // sub 8 case 0x2089: return 56.9; // sub 9 case 0x208A: return 42.9; // sub + case 0x208B: return 44.9; // sub - case 0x208C: return 60.9; // sub = case 0x208D: return 39.9; // sub ( case 0x208E: return 40.9; // sub ) case 0x208F: return 109.9; // sub n } return $ord; } // JCloze /** * expand_JSJCloze6 * * @return xxx */ function expand_JSJCloze6() { return $this->expand_template('jcloze6.js_'); } /** * expand_ClozeBody * * @return xxx */ function expand_ClozeBody() { $str = ''; // get drop down list of words, if required $dropdownlist = ''; if ($this->use_DropDownList()) { $this->set_WordList(); foreach ($this->wordlist as $word) { $dropdownlist .= '<option value="'.$word.'">'.$word.'</option>'; } } // cache clues flag and caption $includeclues = $this->expand_Clues(); $cluecaption = $this->expand_ClueCaption(); // detect if cloze starts with gap if (strpos($this->hotpot->source->filecontents, '<gap-fill><question-record>')) { $startwithgap = true; } else { $startwithgap = false; } // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // initialize loop values $q = 0; $tags = 'data,gap-fill'; $question_record = "$tags,question-record"; // loop through text and gaps $looping = true; while ($looping) { $text = $this->hotpot->source->xml_value($tags, "[0][' $gap = ''; if (($question="[$q]['#']") && $this->hotpot->source->xml_value($question_record, $question)) { $gap .= '<span class="GapSpan" id="GapSpan'.$q.'">'; if ($this->use_DropDownList()) { $gap .= '<select id="Gap'.$q.'"><option value=""></option>'.$dropdownlist.'</select>'; } else { // minimum gap size if (! $gapsize = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',minimum-gap-size')) { $gapsize = 6; } // increase gap size to length of longest answer for this gap $a = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($question_record, $answer)) { $answertext = $this->hotpot->source->xml_value($question_record, $answer."['text'][0][' $answertext = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $answertext); $gapsize = max($gapsize, strlen($answertext)); $a++; } $gap .= '<input type="text" id="Gap'.$q.'" onfocus="TrackFocus('.$q.')" onblur="LeaveGap()" class="GapBox" size="'.$gapsize.'"></input>'; } if ($includeclues) { $clue = $this->hotpot->source->xml_value($question_record, $question."['clue'][0][' if (strlen($clue)) { $gap .= '<button style="line-height: 1.0" class="FuncButton" onfocus="FuncBtnOver(this)" onmouseover="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="ShowClue('.$q.')">'.$cluecaption.'</button>'; } } $gap .= '</span>'; } if (strlen($text) || strlen($gap)) { if ($startwithgap) { $str .= $gap.$text; } else { $str .= $text.$gap; } $q++; } else { // no text or gap, so force end of loop $looping = false; } } if ($q==0) { // oops, no gaps found! return $this->hotpot->source->xml_value($tags); } else { return $str; } } /** * expand_ItemArray * * @return xxx */ function expand_ItemArray() { // this method is overridden by JCloze and JQuiz output formats } /** * expand_WordList * * @return xxx */ function expand_WordList() { $str = ''; if ($this->include_WordList()) { $this->set_WordList(); $str = implode(' &#160;&#160; ', $this->wordlist); } return $str; } /** * include_WordList * * @return xxx */ function include_WordList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-word-list'); } /** * use_DropDownList * * @return xxx */ function use_DropDownList() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',use-drop-down-list'); } /** * set_WordList */ function set_WordList() { if (isset($this->wordlist)) { // do nothing } else { $this->wordlist = array(); // is the wordlist required if ($this->include_WordList() || $this->use_DropDownList()) { $q = 0; $tags = 'data,gap-fill,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $a = 0; $aa = 0; while (($answer=$question."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0][' $correct = $this->hotpot->source->xml_value_int($tags, $answer."['correct'][0][' if (strlen($text) && $correct) { // $correct is always true $this->wordlist[] = $text; $aa++; } $a++; } $q++; } $this->wordlist = array_unique($this->wordlist); sort($this->wordlist); } } } // jcross /** * expand_JSJCross6 * * @return xxx */ function expand_JSJCross6() { return $this->expand_template('jcross6.js_'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-across'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',clues-down'); } /** * expand_EnterCaption * * @return xxx */ function expand_EnterCaption() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-caption'); } /** * <API key> * * @return xxx */ function <API key>() { $value = $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',include-clue-list'); return empty($value) ? ' style="display: none;"' : ''; } /** * expand_CluesDown * * @return xxx */ function expand_CluesDown() { return $this->expand_jcross_clues('D'); } /** * expand_CluesAcross * * @return xxx */ function expand_CluesAcross() { return $this->expand_jcross_clues('A'); } /** * expand_jcross_clues * * @param xxx $direction * @return xxx */ function expand_jcross_clues($direction) { // $direction: A(cross) or D(own) $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $clue_i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { for ($c=0; $c<=$c_max; $c++) { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if ($aword || $dword) { $clue_i++; // increment clue index // get the definition for this word $def = ''; $word = ($direction=='A') ? $aword : $dword; $word = hotpot_textlib('utf8_to_entities', $word); $i = 0; $clues = 'data,crossword,clues,item'; while (($clue = "[$i]['#']") && $this->hotpot->source->xml_value($clues, $clue)) { if ($word==$this->hotpot->source->xml_value($clues, $clue."['word'][0][' $def = $this->hotpot->source->xml_value($clues, $clue."['def'][0][' break; } $i++; } if ($def) { $str .= '<tr><td class="ClueNum">'.$clue_i.'. </td><td id="Clue_'.$direction.'_'.$clue_i.'" class="Clue">'.$def.'</td></tr>'; } } } } return $str; } /** * expand_LetterArray * * @return xxx */ function expand_LetterArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "L[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { $str .= ($c>0 ? ',' : '')."'".$this->hotpot->source->js_value_safe($row[$r]['cell'][$c]['#'], true)."'"; } $str .= ");\n"; } return $str; } /** * expand_GuessArray * * @return xxx */ function expand_GuessArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "G[$r] = new Array('".str_repeat("','", $c_max)."');\n"; } return $str; } /** * expand_ClueNumArray * * @return xxx */ function expand_ClueNumArray() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= "CL[$r] = new Array("; for ($c=0; $c<=$c_max; $c++) { if ($c>0) { $str .= ','; } $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= 0; } else { $i++; // increment the clue index $str .= $i; } } $str .= ");\n"; } return $str; } /** * expand_GridBody * * @return xxx */ function expand_GridBody() { $row = null; $r_max = 0; $c_max = 0; $this->get_jcross_grid($row, $r_max, $c_max); $i = 0; // clue index; $str = ''; for ($r=0; $r<=$r_max; $r++) { $str .= '<tr id="Row_'.$r.'">'; for ($c=0; $c<=$c_max; $c++) { if (empty($row[$r]['cell'][$c][' $str .= '<td class="BlankCell">&nbsp;</td>'; } else { $aword = $this->get_jcross_aword($row, $r, $r_max, $c, $c_max); $dword = $this->get_jcross_dword($row, $r, $r_max, $c, $c_max); if (empty($aword) && empty($dword)) { $str .= '<td class="LetterOnlyCell"><span id="L_'.$r.'_'.$c.'">&nbsp;</span></td>'; } else { $i++; // increment clue index $str .= '<td class="NumLetterCell"><a href="javascript:void(0);" class="GridNum" onclick="ShowClue('.$i.','.$r.','.$c.')">'.$i.'</a><span class="NumLetterCellText" id="L_'.$r.'_'.$c.'" onclick="ShowClue('.$i.','.$r.','.$c.')">&nbsp;&nbsp;&nbsp;</span></td>'; } } } $str .= '</tr>'; } return $str; } /** * get_jcross_grid * * @param xxx $rows (passed by reference) * @param xxx $r_max (passed by reference) * @param xxx $c_max (passed by reference) */ function get_jcross_grid(&$rows, &$r_max, &$c_max) { $r_max = 0; $c_max = 0; $r = 0; $tags = 'data,crossword,grid,row'; while (($moretags="[$r]['#']") && $row = $this->hotpot->source->xml_value($tags, $moretags)) { $rows[$r] = $row; for ($c=0; $c<count($row['cell']); $c++) { if (! empty($row['cell'][$c][' $r_max = max($r, $r_max); $c_max = max($c, $c_max); } } $r++; } } /** * get_jcross_dword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_dword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($r==0 || empty($row[$r-1]['cell'][$c]['#'])) && $r<$r_max && !empty($row[$r+1]['cell'][$c]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, true); } return $str; } /** * get_jcross_aword * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @return xxx */ function get_jcross_aword(&$row, $r, $r_max, $c, $c_max) { $str = ''; if (($c==0 || empty($row[$r]['cell'][$c-1]['#'])) && $c<$c_max && !empty($row[$r]['cell'][$c+1]['#'])) { $str = $this->get_jcross_word($row, $r, $r_max, $c, $c_max, false); } return $str; } /** * get_jcross_word * * @param xxx $row (passed by reference) * @param xxx $r * @param xxx $r_max * @param xxx $c * @param xxx $c_max * @param xxx $go_down (optional, default=false) * @return xxx */ function get_jcross_word(&$row, $r, $r_max, $c, $c_max, $go_down=false) { $str = ''; while ($r<=$r_max && $c<=$c_max && !empty($row[$r]['cell'][$c][' $str .= $row[$r]['cell'][$c][' if ($go_down) { $r++; } else { $c++; } } return $str; } // jmatch /** * expand_JSJMatch6 * * @return xxx */ function expand_JSJMatch6() { return $this->expand_template('jmatch6.js_'); } /** * expand_JSDJMatch6 * * @return xxx */ function expand_JSDJMatch6() { return $this->expand_template('djmatch6.js_'); } /** * expand_JSFJMatch6 * * @return xxx */ function expand_JSFJMatch6() { return $this->expand_template('fjmatch6.js_'); } /** * expand_ShuffleQs * * @return xxx */ function expand_ShuffleQs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-questions'); } /** * expand_QsToShow * * @return xxx */ function expand_QsToShow() { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',<API key>'); if ($i) { $i = $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',questions-to-show'); } if (empty($i)) { $i = 0; if ($this->hotpot->source->hbs_quiztype=='jmatch') { $tags = 'data,matching-exercise,pair'; } else if ($this->hotpot->source->hbs_quiztype=='jquiz') { $tags = 'data,questions,question-record'; } else { $tags = ''; } if ($tags) { while (($moretags="[$i]['#']") && $value = $this->hotpot->source->xml_value($tags, $moretags)) { $i++; } } } return $i; } /** * <API key> * * @return xxx */ function <API key>() { $this->set_jmatch_items(); $l_keys = $this-><API key>($this->l_items); $r_keys = $this-><API key>($this->r_items); $options = '<option value="x">'.$this->hotpot->source->xml_value('data,matching-exercise,default-right-item').'</option>'."\n"; foreach ($r_keys as $key) { // only add the first occurrence of the text (i.e. skip duplicates) if ($key==$this->r_items[$key]['key']) { $options .= '<option value="'.$key.'">'.$this->r_items[$key]['text'].'</option>'."\n"; // Note: if the 'text' contains an image, it could be added as the background image of the option // ... or of an optgroup ... } } $str = ''; foreach ($l_keys as $key) { $str .= '<tr><td class="l_item">'.$this->l_items[$key]['text'].'</td>'; $str .= '<td class="r_item">'; if ($this->r_items[$key]['fixed']) { $str .= $this->r_items[$key]['text']; } else { $str .= '<select id="s'.$this->r_items[$key]['key'].'_'.$key.'">'.$options.'</select>'; } $str .= '</td><td></td></tr>'; } return $str; } /** * expand_FixedArray * * @return xxx */ function expand_FixedArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->l_items as $i=>$item) { $str .= "F[$i] = new Array();\n"; $str .= "F[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "F[$i][1] = ".($item['key']+1).";\n"; } return $str; } /** * expand_DragArray * * @return xxx */ function expand_DragArray() { $this->set_jmatch_items(); $str = ''; foreach ($this->r_items as $i=>$item) { $str .= "D[$i] = new Array();\n"; $str .= "D[$i][0] = '".$this->hotpot->source->js_value_safe($item['text'], true)."';\n"; $str .= "D[$i][1] = ".($item['key']+1).";\n"; $str .= "D[$i][2] = ".$item['fixed'].";\n"; } return $str; } /** * expand_Slide * * @return xxx */ function expand_Slide() { // return true if any JMatch drag-and-drop RH items are fixed and therefore need to slide to the LHS $this->set_jmatch_items(); foreach ($this->r_items as $i=>$item) { if ($item['fixed']) { return true; } } return false; } /** * set_jmatch_items */ function set_jmatch_items() { if (count($this->l_items)) { return; } $tags = 'data,matching-exercise,pair'; $i = 0; while (($item = "[$i]['#']") && $this->hotpot->source->xml_value($tags, $item)) { $l_item = $item."['left-item'][0][' $l_text = $this->hotpot->source->xml_value($tags, $l_item."['text'][0][' $l_fixed = $this->hotpot->source->xml_value_int($tags, $l_item."['fixed'][0][' $r_item = $item."['right-item'][0][' $r_text = $this->hotpot->source->xml_value($tags, $r_item."['text'][0][' $r_fixed = $this->hotpot->source->xml_value_int($tags, $r_item."['fixed'][0][' // typically all right-hand items are unique, but there may be duplicates // in which case we want the key of the first item containing this text for ($key=0; $key<$i; $key++) { if (isset($this->r_items[$key]) && $this->r_items[$key]['text']==$r_text) { break; } } if (strlen($r_text)) { $addright = true; } else { $addright = false; } if (strlen($l_text)) { $this->l_items[] = array('key' => $key, 'text' => $l_text, 'fixed' => $l_fixed); $addright = true; // force right item to be added } if ($addright) { $this->r_items[] = array('key' => $key, 'text' => $r_text, 'fixed' => $r_fixed); } $i++; } } /** * <API key> * * @param xxx $items (passed by reference) * @return xxx */ function <API key>(&$items) { // get moveable items $moveable_keys = array(); for ($i=0; $i<count($items); $i++) { if(! $items[$i]['fixed']) { $moveable_keys[] = $i; } } // shuffle moveable items $this-><API key>(); shuffle($moveable_keys); $keys = array(); for ($i=0, $ii=0; $i<count($items); $i++) { if($items[$i]['fixed']) { // fixed items stay where they are $keys[] = $i; } else { // moveable items are inserted in a shuffled order $keys[] = $moveable_keys[$ii++]; } } return $keys; } /** * <API key> */ function <API key>() { static $seeded = false; if (! $seeded) { srand((double) microtime() * 1000000); $seeded = true; } } // JMatch flash card /** * expand_TRows * * @return xxx */ function expand_TRows() { $str = ''; $this->set_jmatch_items(); $i_max = count($this->l_items); for ($i=0; $i<$i_max; $i++) { $str .= '<tr class="FlashcardRow" id="I_'.$i.'"><td id="L_'.$i.'">'.$this->l_items[$i]['text'].'</td><td id="R_'.$i.'">'.$this->r_items[$i]['text'].'</td></tr>'."\n"; } return $str; } // jmix /** * expand_JSJMix6 * * @return xxx */ function expand_JSJMix6() { return $this->expand_template('jmix6.js_'); } /** * expand_JSFJMix6 * * @return xxx */ function expand_JSFJMix6() { return $this->expand_template('fjmix6.js_'); } /** * expand_JSDJMix6 * * @return xxx */ function expand_JSDJMix6() { return $this->expand_template('djmix6.js_'); } /** * expand_Punctuation * * @return xxx */ function expand_Punctuation() { $chars = array(); // RegExp pattern to match HTML entity $pattern = '/&#x([0-9A-F]+);/i'; // entities for all punctutation except '&#;' (because they are used in html entities) $entities = $this-><API key>('!"$%'."'".'()*+,-./:<=>?@[\]^_`{|}~'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,<API key>,main-order,segment', 'data,<API key>,alternate' ); foreach ($punctuation_tags as $tags) { // get next segment (or alternate answer) $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i][' // convert low-ascii punctuation to entities $value = strtr($value, $entities); // extract all hex HTML entities if (preg_match_all($pattern, $value, $matches)) { // loop through hex entities $m_max = count($matches[0]); for ($m=0; $m<$m_max; $m++) { // convert to hex string to number //eval('$hex=0x'.$matches[1][$m].';'); $hex = hexdec($matches[1][$m]); // is this a punctuation character? if ( ($hex>=0x0020 && $hex<=0x00BF) || // ascii punctuation ($hex>=0x2000 && $hex<=0x206F) || // general punctuation ($hex>=0x3000 && $hex<=0x303F) || // CJK punctuation ($hex>=0xFE30 && $hex<=0xFE4F) || // CJK compatability ($hex>=0xFE50 && $hex<=0xFE6F) || // small form variants ($hex>=0xFF00 && $hex<=0xFF40) || // halfwidth and fullwidth forms (1) ($hex>=0xFF5B && $hex<=0xFF65) || // halfwidth and fullwidth forms (2) ($hex>=0xFFE0 && $hex<=0xFFEE) // halfwidth and fullwidth forms (3) ) { // add this character $chars[] = $matches[0][$m]; } } } // end if HTML entity $i++; } // end while next segment (or alternate answer) } // end foreach $tags $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * <API key> * * @return xxx */ function <API key>() { $chars = array(); // unicode punctuation designations (pi="initial quote", ps="open") $pi = '0022|0027|00AB|2018|201B|201C|201F|2039'; $ps = '0028|005B|007B|0F3A|0F3C|169B|201A|201E|2045|207D|208D|2329|23B4|2768|276A|276C|276E|2770|2772|2774|27E6|27E8|27EA|2983|2985|2987|2989|298B|298D|298F|2991|2993|2995|2997|29D8|29DA|29FC|3008|300A|300C|300E|3010|3014|3016|3018|301A|301D|FD3E|FE35|FE37|FE39|FE3B|FE3D|FE3F|FE41|FE43|FE47|FE59|FE5B|FE5D|FF08|FF3B|FF5B|FF5F|FF62'; $pattern = '/(&#x('.$pi.'|'.$ps.');)/i'; // HMTL entities of opening punctuation $entities = $this-><API key>('"'."'".'(<[{'); // xml tags for JMix segments and alternate answers $punctuation_tags = array( 'data,<API key>,main-order,segment', 'data,<API key>,alternate' ); foreach ($punctuation_tags as $tags) { $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i][' $value = strtr($value, $entities); if (preg_match_all($pattern, $value, $matches)) { $chars = array_merge($chars, $matches[0]); } $i++; } } $chars = implode('', array_unique($chars)); return $this->hotpot->source->js_value_safe($chars, true); } /** * <API key> * * @param xxx $str * @return xxx */ function <API key>($str) { $entities = array(); $i_max = strlen($str); for ($i=0; $i<$i_max; $i++) { $entities[$str{$i}] = '&#x'.sprintf('%04X', ord($str{$i})).';'; } return $entities; } /* * <API key> * * Should we force the first letter of the first word to be lowercase? * (all other letters are assumed to have the correct case) * * When generating html files with standard JMix program, the user is prompted: * Should the word Xxxxx begin with a capital letter * even when it isn't at the beginning of a sentence? * * The "force-lowercase" xml tag implements a similar functionality * This tag does not exist in standard Hot Potatoes XML files, * but it can be added manually, for example to a HP config file * * @return xxx */ function <API key>() { $tag = $this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',force-lowercase'; return $this->hotpot->source->xml_value_int($tag); } /** * expand_SegmentArray * * @return xxx */ function expand_SegmentArray($more_values=array()) { $segments = array(); $values = array(); // XML tags to the start of a segment $tags = 'data,<API key>,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i][' if ($i==0 && $this-><API key>()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } foreach ($more_values as $value) { $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key; } else { $segments[] = $i; $values[$i] = $value; } $i++; } $this-><API key>(); $keys = array_keys($segments); shuffle($keys); $str = ''; for ($i=0; $i<count($keys); $i++) { $key = $segments[$keys[$i]]; $str .= "Segments[$i] = new Array();\n"; $str .= "Segments[$i][0] = '".$this->hotpot->source->js_value_safe($values[$key], true)."';\n"; $str .= "Segments[$i][1] = ".($key+1).";\n"; $str .= "Segments[$i][2] = 0;\n"; } return $str; } /** * expand_AnswerArray * * @return xxx */ function expand_AnswerArray() { $segments = array(); $values = array(); $escapedvalues = array(); // XML tags to the start of a segment $tags = 'data,<API key>,main-order,segment'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i][' if ($i==0 && $this-><API key>()) { $value = strtolower(substr($value, 0, 1)).substr($value, 1); } $key = array_search($value, $values); if (is_numeric($key)) { $segments[] = $key+1; } else { $segments[] = $i+1; $values[$i] = $value; $escapedvalues[] = preg_quote($value, '/'); } $i++; } // start the answers array $a = 0; $str = 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; // pattern to match the next part of an alternate answer $pattern = '/^('.implode('|', $escapedvalues).')\s*/i'; // XML tags to the start of an alternate answer $tags = 'data,<API key>,alternate'; $i = 0; while ($value = $this->hotpot->source->xml_value($tags, "[$i][' $segments = array(); while (strlen($value) && preg_match($pattern, $value, $matches)) { $key = array_search($matches[1], $values); if (is_numeric($key)) { $segments[] = $key+1; $value = substr($value, strlen($matches[0])); } else { // invalid alternate sequence - shouldn't happen !! $segments = array(); break; } } if (count($segments)) { $str .= 'Answers['.($a++).'] = new Array('.implode(',', $segments).");\n"; } $i++; } return $str; } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',remaining-words'); } /** * expand_DropTotal * * @return xxx */ function expand_DropTotal() { return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,drop-total'); } // JQuiz /** * expand_JSJQuiz6 * * @return xxx */ function expand_JSJQuiz6() { return $this->expand_template('jquiz6.js_'); } /** * <API key> * * @return xxx */ function <API key>() { // start question list $str = '<ol class="QuizQuestions" id="Questions">'."\n"; $q = 0; $tags = 'data,questions,question-record'; while (($question="[$q]['#']") && $this->hotpot->source->xml_value($tags, $question) && ($answers = $question."['answers'][0]['#']") && $this->hotpot->source->xml_value($tags, $answers)) { // get question $question_text = $this->hotpot->source->xml_value($tags, $question."['question'][0][' $question_type = $this->hotpot->source->xml_value_int($tags, $question."['question-type'][0][' switch ($question_type) { case 1: // MULTICHOICE: $textbox = false; $liststart = '<ol class="MCAnswers">'."\n"; break; case 2: // SHORTANSWER: $textbox = true; $liststart = ''; break; case 3: // HYBRID: $textbox = true; $liststart = '<ol class="MCAnswers" id="Q_'.$q.'_Hybrid_MC" style="display: none;">'."\n"; break; case 4: // MULTISELECT: $textbox = false; $liststart = '<ol class="MSelAnswers">'."\n"; break; default: continue; // unknown question type } $first_answer_tags = $question."['answers'][0]['#']['answer'][0]['#']['text'][0]['#']"; $first_answer_text = $this->hotpot->source->xml_value($tags, $first_answer_tags, '', false); // check we have a question (or at least one answer) if (strlen($question_text) || strlen($first_answer_text)) { // start question $str .= '<li class="QuizQuestion" id="Q_'.$q.'" style="display: none;">'; $str .= '<p class="QuestionText">'.$question_text.'</p>'; if ($textbox) { // get prefix, suffix and maximum size of ShortAnswer box (default = 9) list($prefix, $suffix, $size) = $this-><API key>($tags, $answers, $q); $str .= '<div class="ShortAnswer" id="Q_'.$q.'_SA"><form method="post" action="" onsubmit="return false;"><div>'; $str .= $prefix; if ($size<=25) { // text box $str .= '<input type="text" id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" size="'.$size.'"></input>'; } else { // textarea (29 cols wide) $str .= '<textarea id="Q_'.$q.'_Guess" onfocus="TrackFocus('."'".'Q_'.$q.'_Guess'."'".')" onblur="LeaveGap()" class="ShortAnswerBox" cols="29" rows="'.ceil($size/25).'"></textarea>'; } $str .= $suffix; $str .= '<br /><br />'; $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckShortAnswer($q)"); if ($this->expand_Hint()) { $caption = $this->expand_HintCaption(); $str .= $this->expand_jquiz_button($caption, "ShowHint($q)"); } if ($this->expand_ShowAnswer()) { $caption = $this-><API key>(); $str .= $this->expand_jquiz_button($caption, "ShowAnswers($q)"); } $str .= '</div></form></div>'; } if ($liststart) { $str .= $liststart; $a = 0; $aa = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0][' if (strlen($text)) { if ($question_type==1 || $question_type==3) { // MULTICHOICE or HYBRID: button if ($this->hotpot->source->xml_value_int($tags, $answer."['<API key>'][0][' $str .= '<li id="Q_'.$q.'_'.$aa.'"><button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" id="Q_'.$q.'_'.$aa.'_Btn" onclick="CheckMCAnswer('.$q.','.$aa.',this)">&nbsp;&nbsp;?&nbsp;&nbsp;</button>&nbsp;&nbsp;'.$text.'</li>'."\n"; } } else if ($question_type==4) { // MULTISELECT: checkbox $str .= '<li id="Q_'.$q.'_'.$aa.'"><form method="post" action="" onsubmit="return false;"><div><input type="checkbox" id="Q_'.$q.'_'.$aa.'_Chk" class="MSelCheckbox" />'.$text.'</div></form></li>'."\n"; } $aa++; } $a++; } // finish answer list $str .= '</ol>'; if ($question_type==4) { // MULTISELECT: check button $caption = $this->expand_CheckCaption(); $str .= $this->expand_jquiz_button($caption, "CheckMultiSelAnswer($q)"); } } // finish question $str .= "</li>\n"; } $q++; } // end while $question // finish question list and finish return $str."</ol>\n"; } /** * <API key> * * @param xxx $tags * @param xxx $answers * @param xxx $q * @param xxx $defaultsize (optional, default=9) * @return xxx */ function <API key>($tags, $answers, $q, $defaultsize=9) { $prefix = ''; $suffix = ''; $size = $defaultsize; $a = 0; while (($answer = $answers."['answer'][$a]['#']") && $this->hotpot->source->xml_value($tags, $answer)) { $text = $this->hotpot->source->xml_value($tags, $answer."['text'][0]['#']", '', false); $text = preg_replace('/&[#a-zA-Z0-9]+;/', 'x', $text); $size = max($size, strlen($text)); $a++; } return array($prefix, $suffix, $size); } /** * expand_jquiz_button * * @param xxx $caption * @param xxx $onclick * @return xxx */ function expand_jquiz_button($caption, $onclick) { return '<button class="FuncButton" onfocus="FuncBtnOver(this)" onblur="FuncBtnOut(this)" onmouseover="FuncBtnOver(this)" onmouseout="FuncBtnOut(this)" onmousedown="FuncBtnDown(this)" onmouseup="FuncBtnOut(this)" onclick="'.$onclick.'">'.$caption.'</button>'; } /** * expand_MultiChoice * * @return xxx */ function expand_MultiChoice() { return $this-><API key>(1); } /** * expand_ShortAnswer * * @return xxx */ function expand_ShortAnswer() { return $this-><API key>(2); } /** * expand_MultiSelect * * @return xxx */ function expand_MultiSelect() { return $this-><API key>(4); } /** * <API key> * * @param xxx $type * @return xxx */ function <API key>($type) { // does this JQuiz have any questions of the given $type? $q = 0; $tags = 'data,questions,question-record'; while (($question = "[$q]['#']") && $this->hotpot->source->xml_value($tags, $question)) { $question_type = $this->hotpot->source->xml_value($tags, $question."['question-type'][0][' if ($question_type==$type || ($question_type==3 && ($type==1 || $type==2))) { // 1=MULTICHOICE 2=SHORTANSWER 3=HYBRID return true; } $q++; } return false; } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,completed-so-far'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',continuous-scoring'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,correct-first-time'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,exercise-completed'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',<API key>'); } /** * expand_ShuffleAs * * @return xxx */ function expand_ShuffleAs() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',shuffle-answers'); } /** * expand_DefaultRight * * @return xxx */ function expand_DefaultRight() { return $this->expand_GuessCorrect(); } /** * expand_DefaultWrong * * @return xxx */ function expand_DefaultWrong() { return $this-><API key>(); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,<API key>'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,global,<API key>'); } /** * expand_CorrectList * * @return xxx */ function expand_CorrectList() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',correct-answers'); } /** * expand_HybridTries * * @return xxx */ function expand_HybridTries() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',<API key>'); } /** * expand_PleaseEnter * * @return xxx */ function expand_PleaseEnter() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',enter-a-guess'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_js($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',partly-incorrect'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value($this->hotpot->source->hbs_software.'-config-file,'.$this->hotpot->source->hbs_quiztype.',show-answer-caption'); } /** * <API key> * * @return xxx */ function <API key>() { return $this->hotpot->source->xml_value_bool($this->hotpot->source->hbs_software.'-config-file,global,show-also-correct'); } // Textoys stylesheets (tt3.cs_) /** * expand_isRTL * * @return xxx */ function expand_isRTL() { // this may require some clever detection of RTL languages (e.g. Hebrew) // but for now we just check the RTL setting in Options -> Configure Output return $this->hotpot->source->xml_value_int($this->hotpot->source->hbs_software.'-config-file,global,process-for-rtl'); } /** * expand_isLTR * * @return xxx */ function expand_isLTR() { if ($this->expand_isRTL()) { return false; } else { return true; } } /** * expand_RTLText * * @return xxx */ function expand_RTLText() { return $this->expand_isRTL(); } }
<fieldset class="previsu"> <legend><:previsualisation:></legend> <ul> <li> <ul class='forum'> <li class="forum-fil"> <div class="comment"> <div class="comment-meta"> [<strong class="comment-titre">(#ENV*{titre})</strong>] [<small><:par_auteur:> <span>(#SESSION{session_nom}|safehtml|sinon{[(#SESSION{nom}|typo)]}|sinon{<span class="erreur_message blink">?</span>})</span></small>] </div> <div class="comment-content"> [<div class="comment-texte">(#ENV*{texte}|lignes_longues)</div>] [<div class="comment-notes">(#ENV*{notes}|lignes_longues)</div>] [<p class="#EDIT{hyperlien} hyperlien"><:voir_en_ligne:> : <a href="(#ENV{url_site}|attribut_html)" class="spip_out">[(#ENV*{nom_site}|sinon{[(#ENV{url_site}|couper{80})]})]</a></p>] [<div class="comment-doc"><:medias:info_document:> : (#ENV{ajouter_document}|table_valeur{name})</div>] <B_mots><p class="comment-mots"><:forum:<API key>:> <BOUCLE_mots(MOTS){id_mot IN #ENV**{ajouter_mot}}{par num type}{par type}{par num titre}{par titre}{', '}>#TITRE</BOUCLE_mots></p></B_mots> </div> </div> </li> </ul> [<li class="reponse_formulaire reponse error">(#ENV*{erreur})</li>] </li> </ul> [<p class="boutons"><input type="submit" class="submit" onclick="<API key>=true;" name="<API key>" value="(#ENV*{bouton})" /></p>] </fieldset> <br class="clear" /> <script type="text/javascript">/*<![CDATA[*/ var <API key> = false; if (window.jQuery){ jQuery(function(){ jQuery(window).unload(function() { if (!<API key>) alert('<:forum:<API key>|texte_script:>');<API key>=true;});});} </script>
#ifndef PLSCALARCHANNEL_INC #define PLSCALARCHANNEL_INC // INCLUDES // base #include "plAGChannel.h" #include "plAGApplicator.h" // FORWARDS class plController; class plAnimTimeConvert; class <API key>; class <API key>; // DEFINITIONS // PLSCALARCHANNEL // an animation channel that outputs a scalar value class plScalarChannel : public plAGChannel { protected: float fResult; public: plScalarChannel(); virtual ~plScalarChannel(); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); virtual void Value(float &result, double time, bool peek = false); // combine it (allocates combine object) virtual plAGChannel * MakeCombine(plAGChannel * channelB); // blend it (allocates blend object) virtual plAGChannel * MakeBlend(plAGChannel * channelB, plScalarChannel * channelBias, int blendPriority); // const eval at time zero virtual plAGChannel * MakeZeroState(); // make a timeScale instance virtual plAGChannel * MakeTimeScale(plScalarChannel *timeSource); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarChannel ); GETINTERFACE_ANY( plScalarChannel, plAGChannel ); }; // PLSCALARCONSTANT // A scalar source that just keeps handing out the same value class plScalarConstant : public plScalarChannel { public: plScalarConstant(); plScalarConstant(float value); virtual ~plScalarConstant(); void Set(float value) { fResult = value; } float Get() { return fResult; } // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarConstant ); GETINTERFACE_ANY( plScalarConstant, plScalarChannel ); void Read(hsStream *stream, hsResMgr *mgr); void Write(hsStream *stream, hsResMgr *mgr); }; // PLSCALARTIMESCALE // Adapts the time scale before passing it to the next channel in line. // Use to instance animations while allowing each instance to run at different speeds. class plScalarTimeScale : public plScalarChannel { protected: plScalarChannel *fTimeSource; plScalarChannel *fChannelIn; public: plScalarTimeScale(); plScalarTimeScale(plScalarChannel *channel, plScalarChannel *timeSource); virtual ~plScalarTimeScale(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarTimeScale ); GETINTERFACE_ANY( plScalarTimeScale, plScalarChannel ); }; // PLSCALARBLEND // blends two scalars into one with weighting class plScalarBlend : public plScalarChannel { protected: plScalarChannel * fChannelA; plScalarChannel * fChannelB; plScalarChannel * fChannelBias; public: // xTORs plScalarBlend(); plScalarBlend(plScalarChannel * channelA, plScalarChannel * channelB, plScalarChannel * channelBias); virtual ~plScalarBlend(); // SPECIFICS const plScalarChannel * GetChannelA() const { return fChannelA; } void SetChannelA(plScalarChannel * channel) { fChannelA = channel; } const plScalarChannel * GetChannelB() const { return fChannelB; } void SetChannelB(plScalarChannel * channel) { fChannelB = channel; } const plScalarChannel * GetChannelBias() const { return fChannelBias; } void SetChannelBias(plScalarChannel * channel) { fChannelBias = channel; } virtual bool IsStoppedAt(double time); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); // remove the specified channel from our graph virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarBlend ); GETINTERFACE_ANY( plScalarBlend, plScalarChannel ); }; // <API key> // converts a plController-style animation into a plScalarChannel class <API key> : public plScalarChannel { protected: plController *fController; public: // xTORs <API key>(); <API key>(plController *controller); virtual ~<API key>(); // AG PROTOCOL virtual const float & Value(double time, bool peek = false); virtual const float & Value(double time, bool peek, <API key> *cache); virtual plAGChannel *MakeCacheChannel(plAnimTimeConvert *atc); // PLASMA PROTOCOL // rtti CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plScalarChannel ); // persistence virtual void Write(hsStream *stream, hsResMgr *mgr); virtual void Read(hsStream *s, hsResMgr *mgr); }; // <API key> // Same as plScalarController, but with caching info class <API key> : public plScalarChannel { protected: <API key> *fCache; <API key> *fControllerChannel; public: <API key>(); <API key>(<API key> *channel, <API key> *cache); virtual ~<API key>(); virtual const float & Value(double time, bool peek = false); virtual plAGChannel * Detach(plAGChannel * channel); // PLASMA PROTOCOL CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plScalarChannel ); // Created at runtime only, so no Read/Write }; // PLATCChannel // Channel interface for a plAnimTimeConvert object class plATCChannel : public plScalarChannel { protected: plAnimTimeConvert *fConvert; public: plATCChannel(); plATCChannel(plAnimTimeConvert *convert); virtual ~plATCChannel(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); // PLASMA PROTOCOL CLASSNAME_REGISTER( plATCChannel ); GETINTERFACE_ANY( plATCChannel, plScalarChannel ); }; // PLSCALARSDLCHANNEL // Returns the value of an SDL scalar variable class plScalarSDLChannel : public plScalarChannel { protected: <API key> *fVar; float fLength; public: plScalarSDLChannel(); plScalarSDLChannel(float length); virtual ~plScalarSDLChannel(); virtual bool IsStoppedAt(double time); virtual const float & Value(double time, bool peek = false); void SetVar(<API key> *var) { fVar = var; } // PLASMA PROTOCOL CLASSNAME_REGISTER( plScalarSDLChannel ); GETINTERFACE_ANY( plScalarSDLChannel, plScalarChannel ); }; // Channel Applicator classes class <API key> : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plAGApplicator ); }; class <API key> : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plAGApplicator ); }; class <API key> : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plAGApplicator ); }; class plOmniApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plOmniApplicator ); GETINTERFACE_ANY( plOmniApplicator, plAGApplicator ); }; class plOmniSqApplicator : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( plOmniSqApplicator ); GETINTERFACE_ANY( plOmniSqApplicator, plAGApplicator ); }; class <API key> : public plAGApplicator { protected: virtual void IApply(const plAGModifier *mod, double time); public: CLASSNAME_REGISTER( <API key> ); GETINTERFACE_ANY( <API key>, plAGApplicator ); }; #endif
// Name: wx/os2/frame.h // Purpose: wxFrame class // Created: 10/27/99 // RCS-ID: $Id$ // Licence: wxWindows licence #ifndef _WX_FRAME_H_ #define _WX_FRAME_H_ // Get the default resource ID's for frames #include "wx/os2/wxrsc.h" class WXDLLIMPEXP_CORE wxFrame : public wxFrameBase { public: // construction wxFrame() { Init(); } wxFrame( wxWindow* pParent ,wxWindowID vId ,const wxString& rsTitle ,const wxPoint& rPos = wxDefaultPosition ,const wxSize& rSize = wxDefaultSize ,long lStyle = <API key> ,const wxString& rsName = wxFrameNameStr ) { Init(); Create(pParent, vId, rsTitle, rPos, rSize, lStyle, rsName); } bool Create( wxWindow* pParent ,wxWindowID vId ,const wxString& rsTitle ,const wxPoint& rPos = wxDefaultPosition ,const wxSize& rSize = wxDefaultSize ,long lStyle = <API key> ,const wxString& rsName = wxFrameNameStr ); virtual ~wxFrame(); // implement base class pure virtuals #if wxUSE_MENUS_NATIVE virtual void SetMenuBar(wxMenuBar* pMenubar); #endif virtual bool ShowFullScreen( bool bShow ,long lStyle = wxFULLSCREEN_ALL ); // implementation only from now on virtual void Raise(void); // event handlers void OnSysColourChanged(<API key>& rEvent); // Toolbar #if wxUSE_TOOLBAR virtual wxToolBar* CreateToolBar( long lStyle = -1 ,wxWindowID vId = -1 ,const wxString& rsName = wxToolBarNameStr ); virtual wxToolBar* OnCreateToolBar( long lStyle ,wxWindowID vId ,const wxString& rsName ); virtual void PositionToolBar(void); #endif // wxUSE_TOOLBAR // Status bar #if wxUSE_STATUSBAR virtual wxStatusBar* OnCreateStatusBar( int nNumber = 1 ,long lStyle = wxSTB_DEFAULT_STYLE ,wxWindowID vId = 0 ,const wxString& rsName = wxStatusLineNameStr ); virtual void PositionStatusBar(void); // Hint to tell framework which status bar to use: the default is to use // native one for the platforms which support it (Win32), the generic one // otherwise // TODO: should this go into a wxFrameworkSettings class perhaps? static void UseNativeStatusBar(bool bUseNative) { <API key> = bUseNative; }; static bool UsesNativeStatusBar() { return <API key>; }; #endif // wxUSE_STATUSBAR WXHMENU GetWinMenu() const { return m_hMenu; } // Returns the origin of client area (may be different from (0,0) if the // frame has a toolbar) virtual wxPoint GetClientAreaOrigin() const; // event handlers bool HandlePaint(void); bool HandleSize( int nX ,int nY ,WXUINT uFlag ); bool HandleCommand( WXWORD wId ,WXWORD wCmd ,WXHWND wControl ); bool HandleMenuSelect( WXWORD wItem ,WXWORD wFlags ,WXHMENU hMenu ); // tooltip management #if wxUSE_TOOLTIPS WXHWND GetToolTipCtrl(void) const { return m_hWndToolTip; } void SetToolTipCtrl(WXHWND hHwndTT) { m_hWndToolTip = hHwndTT; } #endif // tooltips void SetClient(WXHWND c_Hwnd); void SetClient(wxWindow* c_Window); wxWindow *GetClient(); friend MRESULT EXPENTRY wxFrameWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); friend MRESULT EXPENTRY wxFrameMainWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); protected: // common part of all ctors void Init(void); virtual WXHICON GetDefaultIcon(void) const; // override base class virtuals virtual void DoGetClientSize( int* pWidth ,int* pHeight ) const; virtual void DoSetClientSize( int nWidth ,int nWeight ); inline virtual bool IsMDIChild(void) const { return FALSE; } #if wxUSE_MENUS_NATIVE // helper void DetachMenuBar(void); // perform MSW-specific action when menubar is changed virtual void AttachMenuBar(wxMenuBar* pMenubar); // a plug in for MDI frame classes which need to do something special when // the menubar is set virtual void InternalSetMenuBar(void); #endif // propagate our state change to all child frames void IconizeChildFrames(bool bIconize); // we add menu bar accel processing bool OS2TranslateMessage(WXMSG* pMsg); // window proc for the frames MRESULT OS2WindowProc( WXUINT uMessage ,WXWPARAM wParam ,WXLPARAM lParam ); bool m_bIconized; WXHICON m_hDefaultIcon; #if wxUSE_STATUSBAR static bool <API key>; #endif // wxUSE_STATUSBAR // Data to save/restore when calling ShowFullScreen long m_lFsStyle; // Passed to ShowFullScreen wxRect m_vFsOldSize; long m_lFsOldWindowStyle; int <API key>; // 0 for no status bar int <API key>; int m_nFsToolBarHeight; bool m_bFsIsMaximized; bool m_bFsIsShowing; bool m_bWasMinimized; bool m_bIsShown; private: #if wxUSE_TOOLTIPS WXHWND m_hWndToolTip; #endif // tooltips // Handles to child windows of the Frame, and the frame itself, // that we don't have child objects for (m_hWnd in wxWindow is the // handle of the Frame's client window! WXHWND m_hTitleBar; WXHWND m_hHScroll; WXHWND m_hVScroll; // Swp structures for various client data // DW: Better off in attached RefData? SWP m_vSwpTitleBar; SWP m_vSwpMenuBar; SWP m_vSwpHScroll; SWP m_vSwpVScroll; SWP m_vSwpStatusBar; SWP m_vSwpToolBar; DECLARE_EVENT_TABLE() <API key>(wxFrame) }; MRESULT EXPENTRY wxFrameWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); MRESULT EXPENTRY wxFrameMainWndProc(HWND hWnd,ULONG ulMsg, MPARAM wParam, MPARAM lParam); #endif // _WX_FRAME_H_
using System; using System.Collections.Generic; using Antlr4.Runtime; using Rubberduck.Parsing.Symbols; using Rubberduck.UI; using Rubberduck.VBEditor; namespace Rubberduck.Inspections { public class <API key> : <API key> { private readonly IEnumerable<<API key>> _quickFixes; public <API key>(IInspection inspection, Declaration target, ParserRuleContext context, QualifiedModuleName qualifiedName) : base(inspection, string.Format(inspection.Description, target.IdentifierName), qualifiedName, context) { _quickFixes = new[] { new <API key>(context, QualifiedSelection), }; } public override IEnumerable<<API key>> QuickFixes { get { return _quickFixes; } } } <summary> A code inspection quickfix that removes an unused identifier declaration. </summary> public class <API key> : <API key> { public <API key>(ParserRuleContext context, QualifiedSelection selection) : base(context, selection, RubberduckUI.<API key>) { } public override void Fix() { var module = Selection.QualifiedName.Component.CodeModule; var selection = Selection.Selection; var originalCodeLines = module.get_Lines(selection.StartLine, selection.LineCount) .Replace("\r\n", " ") .Replace("_", string.Empty); var originalInstruction = Context.GetText(); module.DeleteLines(selection.StartLine, selection.LineCount); var newInstruction = string.Empty; var newCodeLines = string.IsNullOrEmpty(newInstruction) ? string.Empty : originalCodeLines.Replace(originalInstruction, newInstruction); if (!string.IsNullOrEmpty(newCodeLines)) { module.InsertLines(selection.StartLine, newCodeLines); } } } }
package org.hsqldb.sample; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.hsqldb.jdbc.jdbcDataSource; public class Testdb { Connection conn; //our connnection to the db - presist for life of program // we dont want this garbage collected until we are done public Testdb(String db_file_name_prefix) throws Exception { // note more general exception // connect to the database. This will load the db files and start the // database if it is not alread running. // db_file_name_prefix is used to open or create files that hold the state // of the db. // It can contain directory names relative to the // current working directory jdbcDataSource dataSource = new jdbcDataSource(); dataSource.setDatabase("jdbc:hsqldb:" + db_file_name_prefix); Connection c = dataSource.getConnection("sa", ""); } public void shutdown() throws SQLException { Statement st = conn.createStatement(); // db writes out to files and performs clean shuts down // otherwise there will be an unclean shutdown // when program ends st.execute("SHUTDOWN"); conn.close(); // if there are no other open connection } //use for SQL command SELECT public synchronized void query(String expression) throws SQLException { Statement st = null; ResultSet rs = null; st = conn.createStatement(); // statement objects can be reused with // repeated calls to execute but we // choose to make a new one each time rs = st.executeQuery(expression); // run the query // do something with the result set. dump(rs); st.close(); // NOTE!! if you close a statement the associated ResultSet is // closed too // so you should copy the contents to some other object. // the result set is invalidated also if you recycle an Statement // and try to execute some other query before the result set has been // completely examined. } //use for SQL commands CREATE, DROP, INSERT and UPDATE public synchronized void update(String expression) throws SQLException { Statement st = null; st = conn.createStatement(); // statements int i = st.executeUpdate(expression); // run the query if (i == -1) { System.out.println("db error : " + expression); } st.close(); } // void update() public static void dump(ResultSet rs) throws SQLException { // the order of the rows in a cursor // are implementation dependent unless you use the SQL ORDER statement ResultSetMetaData meta = rs.getMetaData(); int colmax = meta.getColumnCount(); int i; Object o = null; // the result set is a cursor into the data. You can only // point to one row at a time // assume we are pointing to BEFORE the first row // rs.next() points to next row and returns true // or false if there is no next row, which breaks the loop for (; rs.next(); ) { for (i = 0; i < colmax; ++i) { o = rs.getObject(i + 1); // Is SQL the first column is indexed // with 1 not 0 System.out.print(o.toString() + " "); } System.out.println(" "); } } //void dump( ResultSet rs ) public static void main(String[] args) { Testdb db = null; try { db = new Testdb("db_file"); } catch (Exception ex1) { ex1.printStackTrace(); // could not start db return; // bye bye } try { //make an empty table // by declaring the id column IDENTITY, the db will automatically // generate unique values for new rows- useful for row keys db.update( "CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)"); } catch (SQLException ex2) { //ignore //ex2.printStackTrace(); // second time we run program // should throw execption since table // already there // this will have no effect on the db } try { // add some rows - will create duplicates if run more then once // the id column is automatically generated db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)"); db.update( "INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)"); // do a query db.query("SELECT * FROM sample_table WHERE num_col < 250"); // at end of program db.shutdown(); } catch (SQLException ex3) { ex3.printStackTrace(); } } // main() } // class Testdb
#include "includes.h" #include "libcli/util/ntstatus.h" #include "libcli/util/werror.h" #include "librpc/ndr/libndr.h" #include "librpc/gen_ndr/ndr_dns.h" #include "librpc/gen_ndr/ndr_dnsp.h" #include <ldb.h> #include "dsdb/samdb/samdb.h" #include "dsdb/common/util.h" #include "dns_server/dns_server.h" #undef DBGC_CLASS #define DBGC_CLASS DBGC_DNS uint8_t werr_to_dns_err(WERROR werr) { if (W_ERROR_EQUAL(WERR_OK, werr)) { return DNS_RCODE_OK; } else if (W_ERROR_EQUAL(DNS_ERR(FORMAT_ERROR), werr)) { return DNS_RCODE_FORMERR; } else if (W_ERROR_EQUAL(DNS_ERR(SERVER_FAILURE), werr)) { return DNS_RCODE_SERVFAIL; } else if (W_ERROR_EQUAL(DNS_ERR(NAME_ERROR), werr)) { return DNS_RCODE_NXDOMAIN; } else if (W_ERROR_EQUAL(DNS_ERR(NOT_IMPLEMENTED), werr)) { return DNS_RCODE_NOTIMP; } else if (W_ERROR_EQUAL(DNS_ERR(REFUSED), werr)) { return DNS_RCODE_REFUSED; } else if (W_ERROR_EQUAL(DNS_ERR(YXDOMAIN), werr)) { return DNS_RCODE_YXDOMAIN; } else if (W_ERROR_EQUAL(DNS_ERR(YXRRSET), werr)) { return DNS_RCODE_YXRRSET; } else if (W_ERROR_EQUAL(DNS_ERR(NXRRSET), werr)) { return DNS_RCODE_NXRRSET; } else if (W_ERROR_EQUAL(DNS_ERR(NOTAUTH), werr)) { return DNS_RCODE_NOTAUTH; } else if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) { return DNS_RCODE_NOTZONE; } else if (W_ERROR_EQUAL(DNS_ERR(BADKEY), werr)) { return DNS_RCODE_BADKEY; } DEBUG(5, ("No mapping exists for %s\n", win_errstr(werr))); return DNS_RCODE_SERVFAIL; } bool dns_name_match(const char *zone, const char *name, size_t *host_part_len) { size_t zl = strlen(zone); size_t nl = strlen(name); ssize_t zi, ni; static const size_t fixup = 'a' - 'A'; if (zl > nl) { return false; } for (zi = zl, ni = nl; zi >= 0; zi char zc = zone[zi]; char nc = name[ni]; /* convert to lower case */ if (zc >= 'A' && zc <= 'Z') { zc += fixup; } if (nc >= 'A' && nc <= 'Z') { nc += fixup; } if (zc != nc) { return false; } } if (ni >= 0) { if (name[ni] != '.') { return false; } ni } *host_part_len = ni+1; return true; } /* Names are equal if they match and there's nothing left over */ bool dns_name_equal(const char *name1, const char *name2) { size_t host_part_len; bool ret = dns_name_match(name1, name2, &host_part_len); return ret && (host_part_len == 0); } /* see if two dns records match */ bool dns_records_match(struct <API key> *rec1, struct <API key> *rec2) { bool status; int i; if (rec1->wType != rec2->wType) { return false; } /* see if the data matches */ switch (rec1->wType) { case DNS_TYPE_A: return strcmp(rec1->data.ipv4, rec2->data.ipv4) == 0; case DNS_TYPE_AAAA: return strcmp(rec1->data.ipv6, rec2->data.ipv6) == 0; case DNS_TYPE_CNAME: return dns_name_equal(rec1->data.cname, rec2->data.cname); case DNS_TYPE_TXT: if (rec1->data.txt.count != rec2->data.txt.count) { return false; } status = true; for (i=0; i<rec1->data.txt.count; i++) { status = status && (strcmp(rec1->data.txt.str[i], rec2->data.txt.str[i]) == 0); } return status; case DNS_TYPE_PTR: return strcmp(rec1->data.ptr, rec2->data.ptr) == 0; case DNS_TYPE_NS: return dns_name_equal(rec1->data.ns, rec2->data.ns); case DNS_TYPE_SRV: return rec1->data.srv.wPriority == rec2->data.srv.wPriority && rec1->data.srv.wWeight == rec2->data.srv.wWeight && rec1->data.srv.wPort == rec2->data.srv.wPort && dns_name_equal(rec1->data.srv.nameTarget, rec2->data.srv.nameTarget); case DNS_TYPE_MX: return rec1->data.mx.wPriority == rec2->data.mx.wPriority && dns_name_equal(rec1->data.mx.nameTarget, rec2->data.mx.nameTarget); case DNS_TYPE_HINFO: return strcmp(rec1->data.hinfo.cpu, rec2->data.hinfo.cpu) == 0 && strcmp(rec1->data.hinfo.os, rec2->data.hinfo.os) == 0; case DNS_TYPE_SOA: return dns_name_equal(rec1->data.soa.mname, rec2->data.soa.mname) && dns_name_equal(rec1->data.soa.rname, rec2->data.soa.rname) && rec1->data.soa.serial == rec2->data.soa.serial && rec1->data.soa.refresh == rec2->data.soa.refresh && rec1->data.soa.retry == rec2->data.soa.retry && rec1->data.soa.expire == rec2->data.soa.expire && rec1->data.soa.minimum == rec2->data.soa.minimum; default: break; } return false; } WERROR dns_lookup_records(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct ldb_dn *dn, struct <API key> **records, uint16_t *rec_count) { static const char * const attrs[] = { "dnsRecord", NULL}; struct ldb_message_element *el; uint16_t ri; int ret; struct ldb_message *msg = NULL; struct <API key> *recs; ret = dsdb_search_one(dns->samdb, mem_ctx, &msg, dn, LDB_SCOPE_BASE, attrs, 0, "%s", "(objectClass=dnsNode)"); if (ret != LDB_SUCCESS) { /* TODO: we need to check if there's a glue record we need to * create a referral to */ return DNS_ERR(NAME_ERROR); } el = <API key>(msg, attrs[0]); if (el == NULL) { *records = NULL; *rec_count = 0; return DNS_ERR(NAME_ERROR); } recs = talloc_zero_array(mem_ctx, struct <API key>, el->num_values); if (recs == NULL) { return WERR_NOMEM; } for (ri = 0; ri < el->num_values; ri++) { struct ldb_val *v = &el->values[ri]; enum ndr_err_code ndr_err; ndr_err = <API key>(v, recs, &recs[ri], (ndr_pull_flags_fn_t)<API key>); if (!<API key>(ndr_err)) { DEBUG(0, ("Failed to grab <API key>\n")); return DNS_ERR(SERVER_FAILURE); } } *records = recs; *rec_count = el->num_values; return WERR_OK; } WERROR dns_replace_records(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct ldb_dn *dn, bool needs_add, const struct <API key> *records, uint16_t rec_count) { struct ldb_message_element *el; uint16_t i; int ret; struct ldb_message *msg = NULL; msg = ldb_msg_new(mem_ctx); <API key>(msg); msg->dn = dn; ret = ldb_msg_add_empty(msg, "dnsRecord", <API key>, &el); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } el->values = talloc_zero_array(el, struct ldb_val, rec_count); if (rec_count > 0) { <API key>(el->values); } for (i = 0; i < rec_count; i++) { static const struct <API key> zero; struct ldb_val *v = &el->values[el->num_values]; enum ndr_err_code ndr_err; if (memcmp(&records[i], &zero, sizeof(zero)) == 0) { continue; } ndr_err = <API key>(v, el->values, &records[i], (ndr_push_flags_fn_t)<API key>); if (!<API key>(ndr_err)) { DEBUG(0, ("Failed to grab <API key>\n")); return DNS_ERR(SERVER_FAILURE); } el->num_values++; } if (el->num_values == 0) { if (needs_add) { return WERR_OK; } /* No entries left, delete the dnsNode object */ ret = ldb_delete(dns->samdb, msg->dn); if (ret != LDB_SUCCESS) { DEBUG(0, ("Deleting record failed; %d\n", ret)); return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } if (needs_add) { ret = ldb_msg_add_string(msg, "objectClass", "dnsNode"); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } ret = ldb_add(dns->samdb, msg); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } ret = ldb_modify(dns->samdb, msg); if (ret != LDB_SUCCESS) { return DNS_ERR(SERVER_FAILURE); } return WERR_OK; } bool dns_<API key>(struct dns_server *dns, const char *name) { const struct dns_server_zone *z; size_t host_part_len = 0; if (name == NULL) { return false; } if (strcmp(name, "") == 0) { return true; } for (z = dns->zones; z != NULL; z = z->next) { bool match; match = dns_name_match(z->name, name, &host_part_len); if (match) { break; } } if (z == NULL) { return false; } return true; } WERROR dns_name2dn(struct dns_server *dns, TALLOC_CTX *mem_ctx, const char *name, struct ldb_dn **_dn) { struct ldb_dn *base; struct ldb_dn *dn; const struct dns_server_zone *z; size_t host_part_len = 0; if (name == NULL) { return DNS_ERR(FORMAT_ERROR); } /*TODO: Check if 'name' is a valid DNS name */ if (strcmp(name, "") == 0) { base = <API key>(dns->samdb); dn = ldb_dn_copy(mem_ctx, base); <API key>(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System"); *_dn = dn; return WERR_OK; } for (z = dns->zones; z != NULL; z = z->next) { bool match; match = dns_name_match(z->name, name, &host_part_len); if (match) { break; } } if (z == NULL) { return DNS_ERR(NAME_ERROR); } if (host_part_len == 0) { dn = ldb_dn_copy(mem_ctx, z->dn); <API key>(dn, "DC=@"); *_dn = dn; return WERR_OK; } dn = ldb_dn_copy(mem_ctx, z->dn); <API key>(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name); *_dn = dn; return WERR_OK; } WERROR <API key>(struct dns_server *dns, TALLOC_CTX *mem_ctx, struct dns_res_rec **options) { struct dns_res_rec *o; o = talloc_zero(mem_ctx, struct dns_res_rec); if (o == NULL) { return WERR_NOMEM; } o->name = '\0'; o->rr_type = DNS_QTYPE_OPT; /* This is ugly, but RFC2671 wants the payload size in this field */ o->rr_class = (enum dns_qclass) dns->max_payload; o->ttl = 0; o->length = 0; *options = o; return WERR_OK; }
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ /** * @file <API key>.c Flat lexicon search. */ /* System headers. */ #include <string.h> #include <assert.h> /* SphinxBase headers. */ #include <sphinxbase/ckd_alloc.h> #include <sphinxbase/listelem_alloc.h> #include <sphinxbase/err.h> /* Local headers. */ #include "ngram_search.h" #include "ps_lattice_internal.h" /* Turn this on to dump channels for debugging */ #define __CHAN_DUMP__ 0 #if __CHAN_DUMP__ #define chan_v_eval(chan) hmm_dump_vit_eval(&(chan)->hmm, stderr) #else #define chan_v_eval(chan) hmm_vit_eval(&(chan)->hmm) #endif static void <API key>(ngram_search_t *ngs) { int n_words, i; /* For all "real words" (not fillers or <s>/</s>) in the dictionary, * * 1) Add the ones which are in the LM to the fwdflat wordlist * 2) And to the expansion list (since we are expanding all) */ ngs->n_expand_words = 0; n_words = ps_search_n_words(ngs); bitvec_clear_all(ngs->expand_word_flag, ps_search_n_words(ngs)); for (i = 0; i < n_words; ++i) { if (!<API key>(ngs->lmset, dict_basewid(ps_search_dict(ngs),i))) continue; ngs->fwdflat_wordlist[ngs->n_expand_words] = i; ngs->expand_word_list[ngs->n_expand_words] = i; bitvec_set(ngs->expand_word_flag, i); ngs->n_expand_words++; } E_INFO("Utterance vocabulary contains %d words\n", ngs->n_expand_words); ngs->expand_word_list[ngs->n_expand_words] = -1; ngs->fwdflat_wordlist[ngs->n_expand_words] = -1; } static void <API key>(ngram_search_t *ngs) { dict_t *dict = ps_search_dict(ngs); int n_words = ps_search_n_words(ngs); int i, w; /* Allocate single-phone words, since they won't have * been allocated for us by fwdtree initialization. */ ngs->n_1ph_words = 0; for (w = 0; w < n_words; w++) { if (<API key>(dict, w)) ++ngs->n_1ph_words; } ngs->single_phone_wid = ckd_calloc(ngs->n_1ph_words, sizeof(*ngs->single_phone_wid)); ngs->rhmm_1ph = ckd_calloc(ngs->n_1ph_words, sizeof(*ngs->rhmm_1ph)); i = 0; for (w = 0; w < n_words; w++) { if (!<API key>(dict, w)) continue; /* DICT2PID location */ ngs->rhmm_1ph[i].ciphone = dict_first_phone(dict, w); ngs->rhmm_1ph[i].ci2phone = bin_mdef_silphone(ps_search_acmod(ngs)->mdef); hmm_init(ngs->hmmctx, &ngs->rhmm_1ph[i].hmm, TRUE, /* ssid */ bin_mdef_pid2ssid(ps_search_acmod(ngs)->mdef, ngs->rhmm_1ph[i].ciphone), /* tmatid */ bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, ngs->rhmm_1ph[i].ciphone)); ngs->rhmm_1ph[i].next = NULL; ngs->word_chan[w] = (chan_t *) &(ngs->rhmm_1ph[i]); ngs->single_phone_wid[i] = w; i++; } } static void <API key>(ngram_search_t *ngs) { int i, w; int n_words = ps_search_n_words(ngs); for (i = w = 0; w < n_words; ++w) { if (!<API key>(ps_search_dict(ngs), w)) continue; hmm_deinit(&ngs->rhmm_1ph[i].hmm); ++i; } ckd_free(ngs->rhmm_1ph); ngs->rhmm_1ph = NULL; ckd_free(ngs->single_phone_wid); } void ngram_fwdflat_init(ngram_search_t *ngs) { int n_words; n_words = ps_search_n_words(ngs); ngs->fwdflat_wordlist = ckd_calloc(n_words + 1, sizeof(*ngs->fwdflat_wordlist)); ngs->expand_word_flag = bitvec_alloc(n_words); ngs->expand_word_list = ckd_calloc(n_words + 1, sizeof(*ngs->expand_word_list)); ngs->frm_wordlist = ckd_calloc(ngs->n_frame_alloc, sizeof(*ngs->frm_wordlist)); ngs->min_ef_width = cmd_ln_int32_r(ps_search_config(ngs), "-fwdflatefwid"); ngs->max_sf_win = cmd_ln_int32_r(ps_search_config(ngs), "-fwdflatsfwin"); E_INFO("fwdflat: min_ef_width = %d, max_sf_win = %d\n", ngs->min_ef_width, ngs->max_sf_win); /* No tree-search; pre-build the expansion list, including all LM words. */ if (!ngs->fwdtree) { /* Build full expansion list from LM words. */ <API key>(ngs); /* Allocate single phone words. */ <API key>(ngs); } } void <API key>(ngram_search_t *ngs) { double n_speech = (double)ngs->n_tot_frame / cmd_ln_int32_r(ps_search_config(ngs), "-frate"); E_INFO("TOTAL fwdflat %.2f CPU %.3f xRT\n", ngs->fwdflat_perf.t_tot_cpu, ngs->fwdflat_perf.t_tot_cpu / n_speech); E_INFO("TOTAL fwdflat %.2f wall %.3f xRT\n", ngs->fwdflat_perf.t_tot_elapsed, ngs->fwdflat_perf.t_tot_elapsed / n_speech); /* Free single-phone words if we allocated them. */ if (!ngs->fwdtree) { <API key>(ngs); } ckd_free(ngs->fwdflat_wordlist); bitvec_free(ngs->expand_word_flag); ckd_free(ngs->expand_word_list); ckd_free(ngs->frm_wordlist); } int <API key>(ngram_search_t *ngs) { /* Reallocate things that depend on the number of words. */ int n_words; ckd_free(ngs->fwdflat_wordlist); ckd_free(ngs->expand_word_list); bitvec_free(ngs->expand_word_flag); n_words = ps_search_n_words(ngs); ngs->fwdflat_wordlist = ckd_calloc(n_words + 1, sizeof(*ngs->fwdflat_wordlist)); ngs->expand_word_flag = bitvec_alloc(n_words); ngs->expand_word_list = ckd_calloc(n_words + 1, sizeof(*ngs->expand_word_list)); /* No tree-search; take care of the expansion list and single phone words. */ if (!ngs->fwdtree) { /* Free single-phone words. */ <API key>(ngs); /* Reallocate word_chan. */ ckd_free(ngs->word_chan); ngs->word_chan = ckd_calloc(dict_size(ps_search_dict(ngs)), sizeof(*ngs->word_chan)); /* Rebuild full expansion list from LM words. */ <API key>(ngs); /* Allocate single phone words. */ <API key>(ngs); } /* Otherwise there is nothing to do since the wordlist is * generated anew every utterance. */ return 0; } /** * Find all active words in backpointer table and sort by frame. */ static void <API key>(ngram_search_t *ngs) { int32 i, f, sf, ef, wid, nwd; bptbl_t *bp; ps_latnode_t *node, *prevnode, *nextnode; /* No tree-search, use statically allocated wordlist. */ if (!ngs->fwdtree) return; memset(ngs->frm_wordlist, 0, ngs->n_frame_alloc * sizeof(*ngs->frm_wordlist)); /* Scan the backpointer table for all active words and record * their exit frames. */ for (i = 0, bp = ngs->bp_table; i < ngs->bpidx; i++, bp++) { sf = (bp->bp < 0) ? 0 : ngs->bp_table[bp->bp].frame + 1; ef = bp->frame; wid = bp->wid; /* Anything that can be transitioned to in the LM can go in * the word list. */ if (!<API key>(ngs->lmset, dict_basewid(ps_search_dict(ngs), wid))) continue; /* Look for it in the wordlist. */ for (node = ngs->frm_wordlist[sf]; node && (node->wid != wid); node = node->next); /* Update last end frame. */ if (node) node->lef = ef; else { /* New node; link to head of list */ node = listelem_malloc(ngs->latnode_alloc); node->wid = wid; node->fef = node->lef = ef; node->next = ngs->frm_wordlist[sf]; ngs->frm_wordlist[sf] = node; } } /* Eliminate "unlikely" words, for which there are too few end points */ for (f = 0; f < ngs->n_frame; f++) { prevnode = NULL; for (node = ngs->frm_wordlist[f]; node; node = nextnode) { nextnode = node->next; /* Word has too few endpoints */ if ((node->lef - node->fef < ngs->min_ef_width) || /* Word is </s> and doesn't actually end in last frame */ ((node->wid == <API key>(ngs)) && (node->lef < ngs->n_frame - 1))) { if (!prevnode) ngs->frm_wordlist[f] = nextnode; else prevnode->next = nextnode; listelem_free(ngs->latnode_alloc, node); } else prevnode = node; } } /* Form overall wordlist for 2nd pass */ nwd = 0; bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); for (f = 0; f < ngs->n_frame; f++) { for (node = ngs->frm_wordlist[f]; node; node = node->next) { if (!bitvec_is_set(ngs->word_active, node->wid)) { bitvec_set(ngs->word_active, node->wid); ngs->fwdflat_wordlist[nwd++] = node->wid; } } } ngs->fwdflat_wordlist[nwd] = -1; E_INFO("Utterance vocabulary contains %d words\n", nwd); } /** * Build HMM network for one utterance of fwdflat search. */ static void build_fwdflat_chan(ngram_search_t *ngs) { int32 i, wid, p; root_chan_t *rhmm; chan_t *hmm, *prevhmm; dict_t *dict; dict2pid_t *d2p; dict = ps_search_dict(ngs); d2p = ps_search_dict2pid(ngs); /* Build word HMMs for each word in the lattice. */ for (i = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { wid = ngs->fwdflat_wordlist[i]; /* Single-phone words are permanently allocated */ if (<API key>(dict, wid)) continue; assert(ngs->word_chan[wid] == NULL); /* Multiplex root HMM for first phone (one root per word, flat * lexicon). diphone is irrelevant here, for the time being, * at least. */ rhmm = listelem_malloc(ngs->root_chan_alloc); rhmm->ci2phone = dict_second_phone(dict, wid); rhmm->ciphone = dict_first_phone(dict, wid); rhmm->next = NULL; hmm_init(ngs->hmmctx, &rhmm->hmm, TRUE, bin_mdef_pid2ssid(ps_search_acmod(ngs)->mdef, rhmm->ciphone), bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, rhmm->ciphone)); /* HMMs for word-internal phones */ prevhmm = NULL; for (p = 1; p < dict_pronlen(dict, wid) - 1; p++) { hmm = listelem_malloc(ngs->chan_alloc); hmm->ciphone = dict_pron(dict, wid, p); hmm->info.rc_id = (p == dict_pronlen(dict, wid) - 1) ? 0 : -1; hmm->next = NULL; hmm_init(ngs->hmmctx, &hmm->hmm, FALSE, dict2pid_internal(d2p,wid,p), bin_mdef_pid2tmatid(ps_search_acmod(ngs)->mdef, hmm->ciphone)); if (prevhmm) prevhmm->next = hmm; else rhmm->next = hmm; prevhmm = hmm; } /* Right-context phones */ <API key>(ngs, wid); /* Link in just allocated right-context phones */ if (prevhmm) prevhmm->next = ngs->word_chan[wid]; else rhmm->next = ngs->word_chan[wid]; ngs->word_chan[wid] = (chan_t *) rhmm; } } void ngram_fwdflat_start(ngram_search_t *ngs) { root_chan_t *rhmm; int i; ptmr_reset(&ngs->fwdflat_perf); ptmr_start(&ngs->fwdflat_perf); <API key>(ngs); build_fwdflat_chan(ngs); ngs->bpidx = 0; ngs->bss_head = 0; for (i = 0; i < ps_search_n_words(ngs); i++) ngs->word_lat_idx[i] = NO_BP; /* Reset the permanently allocated single-phone words, since they * may have junk left over in them from previous searches. */ for (i = 0; i < ngs->n_1ph_words; i++) { int32 w = ngs->single_phone_wid[i]; rhmm = (root_chan_t *) ngs->word_chan[w]; hmm_clear(&rhmm->hmm); } /* Start search with <s>; word_chan[<s>] is permanently allocated */ rhmm = (root_chan_t *) ngs->word_chan[ps_search_start_wid(ngs)]; hmm_enter(&rhmm->hmm, 0, NO_BP, 0); ngs->active_word_list[0][0] = ps_search_start_wid(ngs); ngs->n_active_word[0] = 1; ngs->best_score = 0; ngs->renormalized = FALSE; for (i = 0; i < ps_search_n_words(ngs); i++) ngs->last_ltrans[i].sf = -1; if (!ngs->fwdtree) ngs->n_frame = 0; ngs->st.n_fwdflat_chan = 0; ngs->st.n_fwdflat_words = 0; ngs->st.<API key> = 0; ngs->st.n_senone_active_utt = 0; } static void <API key>(ngram_search_t *ngs, int frame_idx) { int32 i, nw, w; int32 *awl; root_chan_t *rhmm; chan_t *hmm; acmod_clear_active(ps_search_acmod(ngs)); nw = ngs->n_active_word[frame_idx & 0x1]; awl = ngs->active_word_list[frame_idx & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *)ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == frame_idx) { acmod_activate_hmm(ps_search_acmod(ngs), &rhmm->hmm); } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == frame_idx) { acmod_activate_hmm(ps_search_acmod(ngs), &hmm->hmm); } } } } static void fwdflat_eval_chan(ngram_search_t *ngs, int frame_idx) { int32 i, w, nw, bestscore; int32 *awl; root_chan_t *rhmm; chan_t *hmm; nw = ngs->n_active_word[frame_idx & 0x1]; awl = ngs->active_word_list[frame_idx & 0x1]; bestscore = WORST_SCORE; ngs->st.n_fwdflat_words += nw; /* Scan all active words. */ for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == frame_idx) { int32 score = chan_v_eval(rhmm); if ((score BETTER_THAN bestscore) && (w != <API key>(ngs))) bestscore = score; ngs->st.n_fwdflat_chan++; } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == frame_idx) { int32 score = chan_v_eval(hmm); if (score BETTER_THAN bestscore) bestscore = score; ngs->st.n_fwdflat_chan++; } } } ngs->best_score = bestscore; } static void fwdflat_prune_chan(ngram_search_t *ngs, int frame_idx) { int32 i, nw, cf, nf, w, pip, newscore, thresh, wordthresh; int32 *awl; root_chan_t *rhmm; chan_t *hmm, *nexthmm; cf = frame_idx; nf = cf + 1; nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); thresh = ngs->best_score + ngs->fwdflatbeam; wordthresh = ngs->best_score + ngs->fwdflatwbeam; pip = ngs->pip; E_DEBUG(3,("frame %d thresh %d wordthresh %d\n", frame_idx, thresh, wordthresh)); /* Scan all active words. */ for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; /* Propagate active root channels */ if (hmm_frame(&rhmm->hmm) == cf && hmm_bestscore(&rhmm->hmm) BETTER_THAN thresh) { hmm_frame(&rhmm->hmm) = nf; bitvec_set(ngs->word_active, w); /* Transitions out of root channel */ newscore = hmm_out_score(&rhmm->hmm); if (rhmm->next) { assert(!<API key>(ps_search_dict(ngs), w)); newscore += pip; if (newscore BETTER_THAN thresh) { hmm = rhmm->next; /* Enter all right context phones */ if (hmm->info.rc_id >= 0) { for (; hmm; hmm = hmm->next) { if ((hmm_frame(&hmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&hmm->hmm))) { hmm_enter(&hmm->hmm, newscore, hmm_out_history(&rhmm->hmm), nf); } } } /* Just a normal word internal phone */ else { if ((hmm_frame(&hmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&hmm->hmm))) { hmm_enter(&hmm->hmm, newscore, hmm_out_history(&rhmm->hmm), nf); } } } } else { assert(<API key>(ps_search_dict(ngs), w)); /* Word exit for single-phone words (where did their * whmms come from?) (either from * <API key>, or from * <API key>(), that's where) */ if (newscore BETTER_THAN wordthresh) { <API key>(ngs, cf, w, newscore, hmm_out_history(&rhmm->hmm), 0); } } } /* Transitions out of non-root channels. */ for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) >= cf) { /* Propagate forward HMMs inside the beam. */ if (hmm_bestscore(&hmm->hmm) BETTER_THAN thresh) { hmm_frame(&hmm->hmm) = nf; bitvec_set(ngs->word_active, w); newscore = hmm_out_score(&hmm->hmm); /* Word-internal phones */ if (hmm->info.rc_id < 0) { newscore += pip; if (newscore BETTER_THAN thresh) { nexthmm = hmm->next; /* Enter all right-context phones. */ if (nexthmm->info.rc_id >= 0) { for (; nexthmm; nexthmm = nexthmm->next) { if ((hmm_frame(&nexthmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&nexthmm->hmm))) { hmm_enter(&nexthmm->hmm, newscore, hmm_out_history(&hmm->hmm), nf); } } } /* Enter single word-internal phone. */ else { if ((hmm_frame(&nexthmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&nexthmm->hmm))) { hmm_enter(&nexthmm->hmm, newscore, hmm_out_history(&hmm->hmm), nf); } } } } /* Right-context phones - apply word beam and exit. */ else { if (newscore BETTER_THAN wordthresh) { <API key>(ngs, cf, w, newscore, hmm_out_history(&hmm->hmm), hmm->info.rc_id); } } } /* Zero out inactive HMMs. */ else if (hmm_frame(&hmm->hmm) != nf) { hmm_clear_scores(&hmm->hmm); } } } } } static void get_expand_wordlist(ngram_search_t *ngs, int32 frm, int32 win) { int32 f, sf, ef; ps_latnode_t *node; if (!ngs->fwdtree) { ngs->st.<API key> += ngs->n_expand_words; return; } sf = frm - win; if (sf < 0) sf = 0; ef = frm + win; if (ef > ngs->n_frame) ef = ngs->n_frame; bitvec_clear_all(ngs->expand_word_flag, ps_search_n_words(ngs)); ngs->n_expand_words = 0; for (f = sf; f < ef; f++) { for (node = ngs->frm_wordlist[f]; node; node = node->next) { if (!bitvec_is_set(ngs->expand_word_flag, node->wid)) { ngs->expand_word_list[ngs->n_expand_words++] = node->wid; bitvec_set(ngs->expand_word_flag, node->wid); } } } ngs->expand_word_list[ngs->n_expand_words] = -1; ngs->st.<API key> += ngs->n_expand_words; } static void <API key>(ngram_search_t *ngs, int frame_idx) { int32 cf, nf, b, thresh, pip, i, nw, w, newscore; int32 best_silrc_score = 0, best_silrc_bp = 0; /* FIXME: good defaults? */ bptbl_t *bp; int32 *rcss; root_chan_t *rhmm; int32 *awl; float32 lwf; dict_t *dict = ps_search_dict(ngs); dict2pid_t *d2p = ps_search_dict2pid(ngs); cf = frame_idx; nf = cf + 1; thresh = ngs->best_score + ngs->fwdflatbeam; pip = ngs->pip; best_silrc_score = WORST_SCORE; lwf = ngs-><API key>; /* Search for all words starting within a window of this frame. * These are the successors for words exiting now. */ get_expand_wordlist(ngs, cf, ngs->max_sf_win); /* Scan words exited in current frame */ for (b = ngs->bp_table_idx[cf]; b < ngs->bpidx; b++) { xwdssid_t *rssid; int32 silscore; bp = ngs->bp_table + b; ngs->word_lat_idx[bp->wid] = NO_BP; if (bp->wid == <API key>(ngs)) continue; /* DICT2PID location */ /* Get the mapping from right context phone ID to index in the * right context table and the bscore_stack. */ rcss = ngs->bscore_stack + bp->s_idx; if (bp->last2_phone == -1) rssid = NULL; else rssid = dict2pid_rssid(d2p, bp->last_phone, bp->last2_phone); /* Transition to all successor words. */ for (i = 0; ngs->expand_word_list[i] >= 0; i++) { int32 n_used; w = ngs->expand_word_list[i]; /* Get the exit score we recorded in save_bwd_ptr(), or * something approximating it. */ if (rssid) newscore = rcss[rssid->cimap[dict_first_phone(dict, w)]]; else newscore = bp->score; if (newscore == WORST_SCORE) continue; /* FIXME: Floating point... */ newscore += lwf * (ngram_tg_score(ngs->lmset, dict_basewid(dict, w), bp->real_wid, bp->prev_real_wid, &n_used) >> SENSCR_SHIFT); newscore += pip; /* Enter the next word */ if (newscore BETTER_THAN thresh) { rhmm = (root_chan_t *) ngs->word_chan[w]; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, b, nf); /* DICT2PID: This is where mpx ssids get introduced. */ /* Look up the ssid to use when entering this mpx triphone. */ hmm_mpx_ssid(&rhmm->hmm, 0) = dict2pid_ldiph_lc(d2p, rhmm->ciphone, rhmm->ci2phone, dict_last_phone(dict, bp->wid)); assert(IS_S3SSID(hmm_mpx_ssid(&rhmm->hmm, 0))); E_DEBUG(6,("ssid %d(%d,%d) = %d\n", rhmm->ciphone, dict_last_phone(dict, bp->wid), rhmm->ci2phone, hmm_mpx_ssid(&rhmm->hmm, 0))); bitvec_set(ngs->word_active, w); } } } /* Get the best exit into silence. */ if (rssid) silscore = rcss[rssid->cimap[ps_search_acmod(ngs)->mdef->sil]]; else silscore = bp->score; if (silscore BETTER_THAN best_silrc_score) { best_silrc_score = silscore; best_silrc_bp = b; } } /* Transition to <sil> */ newscore = best_silrc_score + ngs->silpen + pip; if ((newscore BETTER_THAN thresh) && (newscore BETTER_THAN WORST_SCORE)) { w = <API key>(ngs); rhmm = (root_chan_t *) ngs->word_chan[w]; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, best_silrc_bp, nf); bitvec_set(ngs->word_active, w); } } /* Transition to noise words */ newscore = best_silrc_score + ngs->fillpen + pip; if ((newscore BETTER_THAN thresh) && (newscore BETTER_THAN WORST_SCORE)) { for (w = dict_filler_start(dict); w <= dict_filler_end(dict); w++) { if (w == <API key>(ngs)) continue; rhmm = (root_chan_t *) ngs->word_chan[w]; /* Noise words that aren't a single phone will have NULL here. */ if (rhmm == NULL) continue; if ((hmm_frame(&rhmm->hmm) < cf) || (newscore BETTER_THAN hmm_in_score(&rhmm->hmm))) { hmm_enter(&rhmm->hmm, newscore, best_silrc_bp, nf); bitvec_set(ngs->word_active, w); } } } /* Reset initial channels of words that have become inactive even after word trans. */ nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == cf) { hmm_clear_scores(&rhmm->hmm); } } } static void <API key>(ngram_search_t *ngs, int frame_idx, int32 norm) { root_chan_t *rhmm; chan_t *hmm; int32 i, nw, cf, w, *awl; cf = frame_idx; /* Renormalize individual word channels */ nw = ngs->n_active_word[cf & 0x1]; awl = ngs->active_word_list[cf & 0x1]; for (i = 0; i < nw; i++) { w = *(awl++); rhmm = (root_chan_t *) ngs->word_chan[w]; if (hmm_frame(&rhmm->hmm) == cf) { hmm_normalize(&rhmm->hmm, norm); } for (hmm = rhmm->next; hmm; hmm = hmm->next) { if (hmm_frame(&hmm->hmm) == cf) { hmm_normalize(&hmm->hmm, norm); } } } ngs->renormalized = TRUE; } int <API key>(ngram_search_t *ngs, int frame_idx) { int16 const *senscr; int32 nf, i, j; int32 *nawl; /* Activate our HMMs for the current frame if need be. */ if (!ps_search_acmod(ngs)->compallsen) <API key>(ngs, frame_idx); /* Compute GMM scores for the current frame. */ senscr = acmod_score(ps_search_acmod(ngs), &frame_idx); ngs->st.n_senone_active_utt += ps_search_acmod(ngs)->n_senone_active; /* Mark backpointer table for current frame. */ <API key>(ngs, frame_idx); /* If the best score is equal to or worse than WORST_SCORE, * recognition has failed, don't bother to keep trying. */ if (ngs->best_score == WORST_SCORE || ngs->best_score WORSE_THAN WORST_SCORE) return 0; /* Renormalize if necessary */ if (ngs->best_score + (2 * ngs->beam) WORSE_THAN WORST_SCORE) { E_INFO("Renormalizing Scores at frame %d, best score %d\n", frame_idx, ngs->best_score); <API key>(ngs, frame_idx, ngs->best_score); } ngs->best_score = WORST_SCORE; <API key>(ngs->hmmctx, senscr); /* Evaluate HMMs */ fwdflat_eval_chan(ngs, frame_idx); /* Prune HMMs and do phone transitions. */ fwdflat_prune_chan(ngs, frame_idx); /* Do word transitions. */ <API key>(ngs, frame_idx); /* Create next active word list, skip fillers */ nf = frame_idx + 1; nawl = ngs->active_word_list[nf & 0x1]; for (i = 0, j = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { int32 wid = ngs->fwdflat_wordlist[i]; if (bitvec_is_set(ngs->word_active, wid) && wid < ps_search_start_wid(ngs)) { *(nawl++) = wid; j++; } } /* Add fillers */ for (i = ps_search_start_wid(ngs); i < ps_search_n_words(ngs); i++) { if (bitvec_is_set(ngs->word_active, i)) { *(nawl++) = i; j++; } } if (!ngs->fwdtree) ++ngs->n_frame; ngs->n_active_word[nf & 0x1] = j; /* Return the number of frames processed. */ return 1; } /** * Destroy wordlist from the current utterance. */ static void <API key>(ngram_search_t *ngs) { ps_latnode_t *node, *tnode; int32 f; if (!ngs->fwdtree) return; for (f = 0; f < ngs->n_frame; f++) { for (node = ngs->frm_wordlist[f]; node; node = tnode) { tnode = node->next; listelem_free(ngs->latnode_alloc, node); } } } /** * Free HMM network for one utterance of fwdflat search. */ static void <API key>(ngram_search_t *ngs) { int32 i, wid; for (i = 0; ngs->fwdflat_wordlist[i] >= 0; i++) { root_chan_t *rhmm; chan_t *thmm; wid = ngs->fwdflat_wordlist[i]; if (<API key>(ps_search_dict(ngs),wid)) continue; assert(ngs->word_chan[wid] != NULL); /* The first HMM in ngs->word_chan[wid] was allocated with * ngs->root_chan_alloc, but this will attempt to free it * using ngs->chan_alloc, which will not work. Therefore we * free it manually and move the list forward before handing * it off. */ rhmm = (root_chan_t *)ngs->word_chan[wid]; thmm = rhmm->next; listelem_free(ngs->root_chan_alloc, rhmm); ngs->word_chan[wid] = thmm; <API key>(ngs, wid); } } void <API key>(ngram_search_t *ngs) { int32 cf; <API key>(ngs); <API key>(ngs); bitvec_clear_all(ngs->word_active, ps_search_n_words(ngs)); /* This is the number of frames processed. */ cf = ps_search_acmod(ngs)->output_frame; /* Add a mark in the backpointer table for one past the final frame. */ <API key>(ngs, cf); ptmr_stop(&ngs->fwdflat_perf); /* Print out some statistics. */ if (cf > 0) { double n_speech = (double)(cf + 1) / cmd_ln_int32_r(ps_search_config(ngs), "-frate"); E_INFO("%8d words recognized (%d/fr)\n", ngs->bpidx, (ngs->bpidx + (cf >> 1)) / (cf + 1)); E_INFO("%8d senones evaluated (%d/fr)\n", ngs->st.n_senone_active_utt, (ngs->st.n_senone_active_utt + (cf >> 1)) / (cf + 1)); E_INFO("%8d channels searched (%d/fr)\n", ngs->st.n_fwdflat_chan, ngs->st.n_fwdflat_chan / (cf + 1)); E_INFO("%8d words searched (%d/fr)\n", ngs->st.n_fwdflat_words, ngs->st.n_fwdflat_words / (cf + 1)); E_INFO("%8d word transitions (%d/fr)\n", ngs->st.<API key>, ngs->st.<API key> / (cf + 1)); E_INFO("fwdflat %.2f CPU %.3f xRT\n", ngs->fwdflat_perf.t_cpu, ngs->fwdflat_perf.t_cpu / n_speech); E_INFO("fwdflat %.2f wall %.3f xRT\n", ngs->fwdflat_perf.t_elapsed, ngs->fwdflat_perf.t_elapsed / n_speech); } }
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Votations.NSurvey.DataAccess; using Votations.NSurvey.Data; using Votations.NSurvey.UserProvider; using Votations.NSurvey.WebAdmin.UserControls; namespace Votations.NSurvey.WebAdmin { <summary> Display the user editor </summary> public partial class UsersManager : PageBase { protected System.Web.UI.WebControls.Label MessageLabel; new protected HeaderControl Header; Votations.NSurvey.SQLServerDAL.User UsersData; public int selectedTabIndex = 0; private void Page_Load(object sender, System.EventArgs e) { SetupSecurity(); LocalizePage(); // Get selected tab if (!string.IsNullOrEmpty(Request.Params["tabindex"])) { string[] idx = Request.Params["tabindex"].Split(','); selectedTabIndex = int.Parse(idx[idx.Length - 1]); } if (selectedTabIndex > 0) btnBack.Visible = false; UsersData = new Votations.NSurvey.SQLServerDAL.User(); <API key>(); if (!Page.IsPostBack) { BindFields(); } else BindGrid(); // postback could be import users } private void <API key>() { if (ViewState["UMPREVTAB"] != null && Convert.ToInt32(ViewState["UMPREVTAB"])>0 && selectedTabIndex==0) SwitchToListMode(); ViewState["UMPREVTAB"] = selectedTabIndex; } private void SetupSecurity() { CheckRight(NSurveyRights.AccessUserManager, true); IsSingleUserMode(true); } private void LocalizePage() { UserListTitleLabel.Text = ((PageBase)Page).GetPageResource("UserListTitle"); <API key>.Text = ((PageBase)Page).GetPageResource("<API key>"); } public bool IsAdmin(int userId) { return UsersData.IsAdministrator(userId); } public void OnUserEdit(Object sender, CommandEventArgs e) { <API key>.UserId = int.Parse(e.CommandArgument.ToString()); <API key>.BindFields(); phUsersList.Visible = false; btnBack.Visible = true; } public void EditBackButton(object sender, CommandEventArgs e) { SwitchToListMode(); } private void SwitchToListMode() { <API key>.UserId = -1; <API key>.BindFields(); phUsersList.Visible = true; BindGrid(); btnBack.Visible = false; } <summary> Get the current DB data and fill the fields with them </summary> private void BindFields() { // Header.SurveyId = SurveyId; ((Wap)Master).HeaderControl.SurveyId = getSurveyId(); BindGrid(); btnApplyfilter.Text = GetPageResource("UsersTabApplyFilter"); } private void BindGrid() { int ?isAdmin = chkAdmin.Checked ? 1: (int?)null; gvUsers.DataSource = UsersData.<API key>(txtUserName.Text, txtFirstName.Text, txtLastName.Text, txtEmail.Text, isAdmin); gvUsers.DataBind(); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); GridViewRow pagerRow = (GridViewRow)gvUsers.BottomPagerRow; if (pagerRow != null && pagerRow.Visible == false) pagerRow.Visible = true; } public void <API key>(Object sender, EventArgs e) { BindGrid(); } public void <API key>(Object sender, <API key> e) { gvUsers.PageIndex = e.NewPageIndex; } public void OnApplyFilter(Object sender, EventArgs e) { BindGrid(); } <summary> Triggered by the type option user control in case anything was changed we will need to rebind to display the updates to the user </summary> private void <API key>(object sender, EventArgs e) { BindFields(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // CODEGEN: This call is required by the ASP.NET Web Form Designer. InitializeComponent(); base.OnInit(e); } <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private IUserProvider _userProvider = UserFactory.Create(); } }
define(["ng", "lodash"], function(ng, _){ "use strict"; var DashboardVM = function DashboardVM($scope, $rootScope){ var _self = this; this.toggleHStretch = function(isOn){ _self.setOptions(options); }; this.updateOptions = function(options){ ng.extend(_self, options); }; this.resetOptions = function(){ _self.updateOptions(_self.attr); }; this.setAttr = function(attr){ _self.attr=attr; _self.updateOptions(attr); }; this.remove = function(target){ // _.remove(_self.items, {name: target}); delete _self.items[target]; console.debug("remove _self.items", _self.items); }; this.items = $scope.dashboardItems; // this.items = [ // name: "survival1", // title: "survival1", // content: "moving around" // name: "hcl1", // title: "hcl1", // content: "moving around" // name: "ttest1", // title: "ttest1", // content: "moving around" // name: "limma1", // title: "limma1", // content: "moving around" // name: "deseq1", // title: "deseq1", // content: "moving around" // name: "nmf", // title: "nmf", // content: "moving around" // name: "kmeans1", // title: "kmeans1", // content: "moving around" $scope.$on("ui:dashboard:addItem", function($event, data){ var exists = _.find(_self.items, {name: data.name}); if(exists){ $rootScope.$broadcast("ui:analysisLog.append", "info", "Cannot add analysis '" + data.name + "' to the dashboard. It is already there."); }else{ _self.items.$add(data); } }); $scope.$on("ui:dashboard:removeItem", function($event, data){ console.debug("on ui:dashboard:removeItem", $event, data); _self.remove(data.name); }); }; DashboardVM.$inject=["$scope", "$rootScope"]; DashboardVM.$name="<API key>"; return DashboardVM; });
<?php namespace SMW\Tests\SPARQLStore; use SMW\SPARQLStore\SPARQLStore; use SMW\DIWikiPage; use SMW\SemanticData; use SMWExporter as Exporter; use SMWTurtleSerializer as TurtleSerializer; use Title; class SPARQLStoreTest extends \<API key> { public function testCanConstruct() { $this->assertInstanceOf( '\SMW\SPARQLStore\SPARQLStore', new SPARQLStore() ); // Legacy $this->assertInstanceOf( '\SMW\SPARQLStore\SPARQLStore', new \SMWSPARQLStore() ); } public function <API key>() { $subject = DIWikiPage::newFromTitle( Title::newFromText( __METHOD__ ) ); $semanticData = $this->getMockBuilder( '\SMW\SemanticData' ) -><API key>() ->getMock(); $baseStore = $this->getMockBuilder( '\SMWStore' ) -><API key>() -><API key>(); $baseStore->expects( $this->once() ) ->method( 'getSemanticData' ) ->with( $this->equalTo( $subject ) ) ->will( $this->returnValue( $semanticData ) ); $instance = new SPARQLStore( $baseStore ); $this->assertInstanceOf( '\SMW\SemanticData', $instance->getSemanticData( $subject ) ); } public function <API key>() { $title = Title::newFromText( '<API key>' ); $expResource = Exporter::<API key>( DIWikiPage::newFromTitle( $title ) ); $resourceUri = TurtleSerializer::<API key>( $expResource ); $extraNamespaces = array( $expResource->getNamespaceId() => $expResource->getNamespace() ); $baseStore = $this->getMockBuilder( '\SMWStore' ) -><API key>() -><API key>(); $baseStore->expects( $this->once() ) ->method( 'deleteSubject' ) ->with( $this->equalTo( $title ) ) ->will( $this->returnValue( true ) ); $sparqlDatabase = $this->getMockBuilder( '\SMWSparqlDatabase' ) -><API key>() ->getMock(); $sparqlDatabase->expects( $this->once() ) ->method( '<API key>' ) ->will( $this->returnValue( true ) ); $sparqlDatabase->expects( $this->once() ) ->method( 'delete' ) ->with( $this->equalTo( "{$resourceUri} ?p ?o" ), $this->equalTo( "{$resourceUri} ?p ?o" ), $this->equalTo( $extraNamespaces ) ) ->will( $this->returnValue( true ) ); $instance = new SPARQLStore( $baseStore ); $instance->setSparqlDatabase( $sparqlDatabase ); $instance->deleteSubject( $title ); } public function <API key>() { $semanticData = new SemanticData( new DIWikiPage( 'Foo', NS_MAIN, '' ) ); $listReturnValue = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\FederateResultList' ) -><API key>() ->getMock(); $baseStore = $this->getMockBuilder( '\SMW\Store' ) -><API key>() -><API key>(); $sparqlDatabase = $this->getMockBuilder( '\SMWSparqlDatabase' ) -><API key>() ->getMock(); $sparqlDatabase->expects( $this->atLeastOnce() ) ->method( 'select' ) ->will( $this->returnValue( $listReturnValue ) ); $sparqlDatabase->expects( $this->once() ) ->method( 'insertData' ); $instance = new SPARQLStore( $baseStore ); $instance->setSparqlDatabase( $sparqlDatabase ); $instance->doSparqlDataUpdate( $semanticData ); } }
package org.lwjgl.opengl; import java.awt.<API key>; import java.awt.GraphicsDevice; import java.awt.Canvas; import org.lwjgl.LWJGLException; /** * * @author elias_naur <elias_naur@users.sourceforge.net> * @version $Revision: 3632 $ * $Id: <API key>.java 3632 2011-09-03 18:52:45Z spasi $ */ final class <API key> implements <API key> { public PeerInfo createPeerInfo(Canvas component, PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException { try { return new <API key>(component, pixel_format, attribs, true); } catch (LWJGLException e) { return new <API key>(component, pixel_format, attribs, false); } } /** * Find a proper <API key> from the given GraphicsDevice and PixelFormat. * * @return The <API key> corresponding to a visual that matches the pixel format. */ public <API key> findConfiguration(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException { /* * It seems like the best way is to simply return null */ return null; } }
<?php namespace Mailgun\HttpClient\Plugin; use Http\Client\Common\Plugin; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\UriInterface; /** * Replaces a URI with a new one. Good for debugging. * * @author Tobias Nyholm <tobias.nyholm@gmail.com> */ final class ReplaceUriPlugin implements Plugin { /** * @var UriInterface */ private $uri; /** * @param UriInterface $uri */ public function __construct(UriInterface $uri) { $this->uri = $uri; } /** * {@inheritdoc} */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { $request = $request->withUri($this->uri); return $next($request); } }
// All rights not expressly granted are reserved. // This software is distributed under the terms of the GNU General Public // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. \file TopologyDictionary.h \brief Definition of the ClusterTopology class. \author Luca Barioglio, University and INFN of Torino Short TopologyDictionary descritpion The entries of the dictionaries are the cluster topologies, with all the information which is common to the clusters with the same topology: - number of rows - number of columns - pixel bitmask - position of the Centre Of Gravity (COG) wrt the bottom left corner pixel of the bounding box - error associated to the position of the hit point Rare topologies, i.e. with a frequency below a threshold defined a priori, have not their own entries in the dictionaries, but are grouped together with topologies with similar dimensions. For the groups of rare topollogies a dummy bitmask is used. #ifndef <API key> #define <API key> #include "DataFormatsITSMFT/ClusterPattern.h" #include "Framework/Logger.h" #include <fstream> #include <string> #include <unordered_map> #include <vector> #include "MathUtils/Cartesian.h" #include "DataFormatsITSMFT/CompCluster.h" #include "TH1F.h" namespace o2 { namespace itsmft { class <API key>; class LookUp; class <API key>; Structure containing the most relevant pieces of information of a topology struct GroupStruct { unsigned long mHash; ///< Hashcode float mErrX; ///< Error associated to the hit point in the x direction. float mErrZ; ///< Error associated to the hit point in the z direction. float mErr2X; ///< Squared Error associated to the hit point in the x direction. float mErr2Z; ///< Squared Error associated to the hit point in the z direction. float mXCOG; ///< x position of te COG wrt the boottom left corner of the bounding box float mZCOG; ///< z position of te COG wrt the boottom left corner of the bounding box int mNpixels; ///< Number of fired pixels ClusterPattern mPattern; ///< Bitmask of pixels. For groups the biggest bounding box for the group is taken, with all the bits set to 1. double mFrequency; ///< Frequency of the topology bool mIsGroup; ///< false: common topology; true: group of rare topologies ClassDefNV(GroupStruct, 3); }; class TopologyDictionary { public: Default constructor TopologyDictionary(); Constructor TopologyDictionary(const std::string& fileName); constexpr for the definition of the groups of rare topologies. The attritbution of the group ID is stringly dependent on the following parameters: it must be a power of 2. static constexpr int RowClassSpan = 4; ///< Row span of the classes of rare topologies static constexpr int ColClassSpan = 4; ///< Column span of the classes of rare topologies static constexpr int <API key> = 1 + (ClusterPattern::MaxRowSpan - 1) / RowClassSpan; ///< Maximum number of row classes for the groups of rare topologies static constexpr int <API key> = 1 + (ClusterPattern::MaxColSpan - 1) / ColClassSpan; ///< Maximum number of col classes for the groups of rare topologies static constexpr int NumberOfRareGroups = <API key> * <API key>; ///< Number of entries corresponding to groups of rare topologies (those whos matrix exceed the max number of bytes are empty). Prints the dictionary friend std::ostream& operator<<(std::ostream& os, const TopologyDictionary& dictionary); Prints the dictionary in a binary file void writeBinaryFile(const std::string& outputFile); Reads the dictionary from a binary file int readBinaryFile(const std::string& fileName); int readFromFile(const std::string& fileName); Returns the x position of the COG for the n_th element inline float getXCOG(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mXCOG; } Returns the error on the x position of the COG for the n_th element inline float getErrX(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErrX; } Returns the z position of the COG for the n_th element inline float getZCOG(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mZCOG; } Returns the error on the z position of the COG for the n_th element inline float getErrZ(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErrZ; } Returns the error^2 on the x position of the COG for the n_th element inline float getErr2X(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErr2X; } Returns the error^2 on the z position of the COG for the n_th element inline float getErr2Z(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mErr2Z; } Returns the hash of the n_th element inline unsigned long getHash(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mHash; } Returns the number of fired pixels of the n_th element inline int getNpixels(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mNpixels; } Returns the frequency of the n_th element; inline double getFrequency(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mFrequency; } Returns true if the element corresponds to a group of rare topologies inline bool isGroup(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mIsGroup; } Returns the pattern of the topology inline const ClusterPattern& getPattern(int n) const { assert(n >= 0 || n < (int)mVectorOfIDs.size()); return mVectorOfIDs[n].mPattern; } Fills a hostogram with the distribution of the IDs static void <API key>(const TopologyDictionary& dict, TH1F*& histo, const char* histName); Returns the number of elements in the dicionary; int getSize() const { return (int)mVectorOfIDs.size(); } Returns the local position of a compact cluster math_utils::Point3D<float> <API key>(const CompCluster& cl) const; Returns the local position of a compact cluster static math_utils::Point3D<float> <API key>(const CompCluster& cl, const ClusterPattern& patt, bool isGroup = true); static TopologyDictionary* loadFrom(const std::string& fileName = "", const std::string& objName = "ccdb_object"); friend <API key>; friend LookUp; friend <API key>; private: std::unordered_map<unsigned long, int> mCommonMap; ///< Map of pair <hash, position in mVectorOfIDs> std::unordered_map<int, int> mGroupMap; ///< Map of pair <groudID, position in mVectorOfIDs> int mSmallTopologiesLUT[8 * 255 + 1]; ///< Look-Up Table for the topologies with 1-byte linearised matrix std::vector<GroupStruct> mVectorOfIDs; ///< Vector of topologies and groups ClassDefNV(TopologyDictionary, 4); }; // namespace itsmft } // namespace itsmft } // namespace o2 #endif
# -*- coding: utf-8 -*- import sys import datetime from core.transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT from core.transmissionrpc.utils import Field, format_timedelta from six import integer_types, string_types, text_type, iteritems def get_status_old(code): """Get the torrent status using old status codes""" mapping = { (1 << 0): 'check pending', (1 << 1): 'checking', (1 << 2): 'downloading', (1 << 3): 'seeding', (1 << 4): 'stopped', } return mapping[code] def get_status_new(code): """Get the torrent status using new status codes""" mapping = { 0: 'stopped', 1: 'check pending', 2: 'checking', 3: 'download pending', 4: 'downloading', 5: 'seed pending', 6: 'seeding', } return mapping[code] class Torrent(object): """ Torrent is a class holding the data received from Transmission regarding a bittorrent transfer. All fetched torrent fields are accessible through this class using attributes. This class has a few convenience properties using the torrent data. """ def __init__(self, client, fields): if 'id' not in fields: raise ValueError('Torrent requires an id') self._fields = {} self._update_fields(fields) self._incoming_pending = False self._outgoing_pending = False self._client = client def _get_name_string(self, codec=None): """Get the name""" if codec is None: codec = sys.getdefaultencoding() name = None # try to find name if 'name' in self._fields: name = self._fields['name'].value # if name is unicode, try to decode if isinstance(name, text_type): try: name = name.encode(codec) except UnicodeError: name = None return name def __repr__(self): tid = self._fields['id'].value name = self._get_name_string() if isinstance(name, str): return '<Torrent {0:d} \"{1}\">'.format(tid, name) else: return '<Torrent {0:d}>'.format(tid) def __str__(self): name = self._get_name_string() if isinstance(name, str): return 'Torrent \"{0}\"'.format(name) else: return 'Torrent' def __copy__(self): return Torrent(self._client, self._fields) def __getattr__(self, name): try: return self._fields[name].value except KeyError: raise AttributeError('No attribute {0}'.format(name)) def _rpc_version(self): """Get the Transmission RPC API version.""" if self._client: return self._client.rpc_version return 2 def _dirty_fields(self): """Enumerate changed fields""" outgoing_keys = ['bandwidthPriority', 'downloadLimit', 'downloadLimited', 'peer_limit', 'queuePosition', 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'uploadLimit', 'uploadLimited'] fields = [] for key in outgoing_keys: if key in self._fields and self._fields[key].dirty: fields.append(key) return fields def _push(self): """Push changed fields to the server""" dirty = self._dirty_fields() args = {} for key in dirty: args[key] = self._fields[key].value self._fields[key] = self._fields[key]._replace(dirty=False) if len(args) > 0: self._client.change_torrent(self.id, **args) def _update_fields(self, other): """ Update the torrent data from a Transmission JSON-RPC arguments dictionary """ if isinstance(other, dict): for key, value in iteritems(other): self._fields[key.replace('-', '_')] = Field(value, False) elif isinstance(other, Torrent): for key in list(other._fields.keys()): self._fields[key] = Field(other._fields[key].value, False) else: raise ValueError('Cannot update with supplied data') self._incoming_pending = False def _status(self): """Get the torrent status""" code = self._fields['status'].value if self._rpc_version() >= 14: return get_status_new(code) else: return get_status_old(code) def files(self): """ Get list of files for this torrent. This function returns a dictionary with file information for each file. The file information is has following fields: :: { <file id>: { 'name': <file name>, 'size': <file size in bytes>, 'completed': <bytes completed>, 'priority': <priority ('high'|'normal'|'low')>, 'selected': <selected for download> } } """ result = {} if 'files' in self._fields: files = self._fields['files'].value indices = range(len(files)) priorities = self._fields['priorities'].value wanted = self._fields['wanted'].value for item in zip(indices, files, priorities, wanted): selected = True if item[3] else False priority = PRIORITY[item[2]] result[item[0]] = { 'selected': selected, 'priority': priority, 'size': item[1]['length'], 'name': item[1]['name'], 'completed': item[1]['bytesCompleted']} return result @property def status(self): """ Returns the torrent status. Is either one of 'check pending', 'checking', 'downloading', 'seeding' or 'stopped'. The first two is related to verification. """ return self._status() @property def progress(self): """Get the download progress in percent.""" try: size = self._fields['sizeWhenDone'].value left = self._fields['leftUntilDone'].value return 100.0 * (size - left) / float(size) except ZeroDivisionError: return 0.0 @property def ratio(self): """Get the upload/download ratio.""" return float(self._fields['uploadRatio'].value) @property def eta(self): """Get the "eta" as datetime.timedelta.""" eta = self._fields['eta'].value if eta >= 0: return datetime.timedelta(seconds=eta) else: raise ValueError('eta not valid') @property def date_active(self): """Get the attribute "activityDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['activityDate'].value) @property def date_added(self): """Get the attribute "addedDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['addedDate'].value) @property def date_started(self): """Get the attribute "startDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['startDate'].value) @property def date_done(self): """Get the attribute "doneDate" as datetime.datetime.""" return datetime.datetime.fromtimestamp(self._fields['doneDate'].value) def format_eta(self): """ Returns the attribute *eta* formatted as a string. * If eta is -1 the result is 'not available' * If eta is -2 the result is 'unknown' * Otherwise eta is formatted as <days> <hours>:<minutes>:<seconds>. """ eta = self._fields['eta'].value if eta == -1: return 'not available' elif eta == -2: return 'unknown' else: return format_timedelta(self.eta) def _get_download_limit(self): """ Get the download limit. Can be a number or None. """ if self._fields['downloadLimited'].value: return self._fields['downloadLimit'].value else: return None def _set_download_limit(self, limit): """ Get the download limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['downloadLimited'] = Field(True, True) self._fields['downloadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['downloadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") download_limit = property(_get_download_limit, _set_download_limit, None, "Download limit in Kbps or None. This is a mutator.") def _get_peer_limit(self): """ Get the peer limit. """ return self._fields['peer_limit'].value def _set_peer_limit(self, limit): """ Set the peer limit. """ if isinstance(limit, integer_types): self._fields['peer_limit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") peer_limit = property(_get_peer_limit, _set_peer_limit, None, "Peer limit. This is a mutator.") def _get_priority(self): """ Get the priority as string. Can be one of 'low', 'normal', 'high'. """ return PRIORITY[self._fields['bandwidthPriority'].value] def _set_priority(self, priority): """ Set the priority as string. Can be one of 'low', 'normal', 'high'. """ if isinstance(priority, string_types): self._fields['bandwidthPriority'] = Field(PRIORITY[priority], True) self._push() priority = property(_get_priority, _set_priority, None , "Bandwidth priority as string. Can be one of 'low', 'normal', 'high'. This is a mutator.") def <API key>(self): """ Get the seed idle limit in minutes. """ return self._fields['seedIdleLimit'].value def <API key>(self, limit): """ Set the seed idle limit in minutes. """ if isinstance(limit, integer_types): self._fields['seedIdleLimit'] = Field(limit, True) self._push() else: raise ValueError("Not a valid limit") seed_idle_limit = property(<API key>, <API key>, None , "Torrent seed idle limit in minutes. Also see seed_idle_mode. This is a mutator.") def _get_seed_idle_mode(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return IDLE_LIMIT[self._fields['seedIdleMode'].value] def _set_seed_idle_mode(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedIdleMode'] = Field(IDLE_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_idle_mode = property(_get_seed_idle_mode, _set_seed_idle_mode, None, """ Seed idle mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed idle limit. * single, use torrent seed idle limit. See seed_idle_limit. * unlimited, no seed idle limit. This is a mutator. """ ) def <API key>(self): """ Get the seed ratio limit as float. """ return float(self._fields['seedRatioLimit'].value) def <API key>(self, limit): """ Set the seed ratio limit as float. """ if isinstance(limit, (integer_types, float)) and limit >= 0.0: self._fields['seedRatioLimit'] = Field(float(limit), True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_limit = property(<API key>, <API key>, None , "Torrent seed ratio limit as float. Also see seed_ratio_mode. This is a mutator.") def <API key>(self): """ Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ return RATIO_LIMIT[self._fields['seedRatioMode'].value] def <API key>(self, mode): """ Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. """ if isinstance(mode, str): self._fields['seedRatioMode'] = Field(RATIO_LIMIT[mode], True) self._push() else: raise ValueError("Not a valid limit") seed_ratio_mode = property(<API key>, <API key>, None, """ Seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'. * global, use session seed ratio limit. * single, use torrent seed ratio limit. See seed_ratio_limit. * unlimited, no seed ratio limit. This is a mutator. """ ) def _get_upload_limit(self): """ Get the upload limit. Can be a number or None. """ if self._fields['uploadLimited'].value: return self._fields['uploadLimit'].value else: return None def _set_upload_limit(self, limit): """ Set the upload limit. Can be a number, 'session' or None. """ if isinstance(limit, integer_types): self._fields['uploadLimited'] = Field(True, True) self._fields['uploadLimit'] = Field(limit, True) self._push() elif limit is None: self._fields['uploadLimited'] = Field(False, True) self._push() else: raise ValueError("Not a valid limit") upload_limit = property(_get_upload_limit, _set_upload_limit, None, "Upload limit in Kbps or None. This is a mutator.") def _get_queue_position(self): """Get the queue position for this torrent.""" if self._rpc_version() >= 14: return self._fields['queuePosition'].value else: return 0 def _set_queue_position(self, position): """Set the queue position for this torrent.""" if self._rpc_version() >= 14: if isinstance(position, integer_types): self._fields['queuePosition'] = Field(position, True) self._push() else: raise ValueError("Not a valid position") else: pass queue_position = property(_get_queue_position, _set_queue_position, None, "Queue position") def update(self, timeout=None): """Update the torrent information.""" self._push() torrent = self._client.get_torrent(self.id, timeout=timeout) self._update_fields(torrent) def start(self, bypass_queue=False, timeout=None): """ Start the torrent. """ self._incoming_pending = True self._client.start_torrent(self.id, bypass_queue=bypass_queue, timeout=timeout) def stop(self, timeout=None): """Stop the torrent.""" self._incoming_pending = True self._client.stop_torrent(self.id, timeout=timeout) def move_data(self, location, timeout=None): """Move torrent data to location.""" self._incoming_pending = True self._client.move_torrent_data(self.id, location, timeout=timeout) def locate_data(self, location, timeout=None): """Locate torrent data at location.""" self._incoming_pending = True self._client.locate_torrent_data(self.id, location, timeout=timeout)
package com.secupwn.aimsicd.ui.drawer; import android.support.annotation.DrawableRes; public interface NavDrawerItem { int getId(); String getLabel(); void setLabel(String label); void setIconId(@DrawableRes int icon); int getType(); boolean isEnabled(); boolean <API key>(); }
## This file is part of the libopencm3 project. ## This library is free software: you can redistribute it and/or modify ## (at your option) any later version. ## This library is distributed in the hope that it will be useful, ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LIBNAME = libopencm3_stm32f4 SRCLIBDIR ?= ../.. FP_FLAGS ?= -mfloat-abi=hard -mfpu=fpv4-sp-d16 CC = $(PREFIX)gcc AR = $(PREFIX)ar TGT_CFLAGS = -Os \ -Wall -Wextra -<API key> \ -Wredundant-decls -Wmissing-prototypes -Wstrict-prototypes \ -Wundef -Wshadow \ -I../../../include -fno-common \ -mcpu=cortex-m4 -mthumb $(FP_FLAGS) \ -Wstrict-prototypes \ -ffunction-sections -fdata-sections -MD -DSTM32F4 TGT_CFLAGS += $(DEBUG_FLAGS) TGT_CFLAGS += $(STANDARD_FLAGS) # ARFLAGS = rcsv ARFLAGS = rcs OBJS += adc_common_v1.o adc_common_v1_multi.o adc_common_f47.o OBJS += can.o OBJS += crc_common_all.o OBJS += crypto_common_f24.o crypto.o OBJS += dac_common_all.o OBJS += desig_common_all.o desig_common_v1.o OBJS += dma_common_f24.o OBJS += dma2d_common_f47.o OBJS += dsi_common_f47.o OBJS += exti_common_all.o OBJS += flash.o flash_common_all.o flash_common_f.o flash_common_f24.o OBJS += <API key>.o OBJS += fmc_common_f47.o OBJS += gpio_common_all.o gpio_common_f0234.o OBJS += hash_common_f24.o OBJS += i2c_common_v1.o OBJS += iwdg_common_all.o OBJS += lptimer_common_all.o OBJS += ltdc_common_f47.o OBJS += pwr_common_v1.o pwr.o OBJS += rcc_common_all.o rcc.o OBJS += rng_common_v1.o OBJS += rtc_common_l1f024.o rtc.o OBJS += spi_common_all.o spi_common_v1.o spi_common_v1_frf.o OBJS += timer_common_all.o timer_common_f0234.o timer_common_f24.o OBJS += usart_common_all.o usart_common_f124.o OBJS += usb.o usb_standard.o usb_control.o usb_msc.o OBJS += usb_hid.o OBJS += usb_dwc_common.o usb_f107.o usb_f207.o OBJS += mac.o phy.o mac_stm32fxx7.o phy_ksz80x1.o VPATH += ../../usb:../:../../cm3:../common VPATH += ../../ethernet include ../../Makefile.include
#!/usr/bin/perl # This file is part of Koha. # Koha is free software; you can redistribute it and/or modify it # (at your option) any later version. # Koha is distributed in the hope that it will be useful, but # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output; use C4::Auth; use C4::Koha; use C4::NewsChannels; # GetNewsToDisplay use C4::Suggestions qw/CountSuggestion/; use C4::Tags qw/<API key>/; use Koha::Patron::Modifications; use Koha::Patron::Discharge; use Koha::Reviews; use Koha::ArticleRequests; my $query = new CGI; my ( $template, $loggedinuser, $cookie, $flags ) = <API key>( { template_name => "intranet-main.tt", query => $query, type => "intranet", authnotrequired => 0, flagsrequired => { catalogue => 1, }, } ); my $homebranch; if (C4::Context->userenv) { $homebranch = C4::Context->userenv->{'branch'}; } my $all_koha_news = &GetNewsToDisplay("koha",$homebranch); my $koha_news_count = scalar @$all_koha_news; $template->param( koha_news => $all_koha_news, koha_news_count => $koha_news_count ); my $branch = ( C4::Context->preference("<API key>") || C4::Context->preference("IndependentBranches") ) && !$flags->{'superlibrarian'} ? C4::Context->userenv()->{'branch'} : undef; my $pendingcomments = Koha::Reviews->search({ approved => 0 })->count; my $pendingtags = <API key>(0); my $pendingsuggestions = CountSuggestion("ASKED"); my $<API key> = Koha::Patron::Modifications->pending_count( $branch ); my $<API key> = Koha::Patron::Discharge::count({ pending => 1 }); my $<API key> = Koha::ArticleRequests->count( { status => Koha::ArticleRequest::Status::Pending, $branch ? ( branchcode => $branch ) : (), } ); $template->param( pendingcomments => $pendingcomments, pendingtags => $pendingtags, pendingsuggestions => $pendingsuggestions, <API key> => $<API key>, <API key> => $<API key>, <API key> => $<API key>, ); # warn user if they are using mysql/admin login unless ($loggedinuser) { $template->param(adminWarning => 1); } <API key> $query, $cookie, $template->output;
<?php namespace SendinBlue\Client\Model; use \ArrayAccess; use \SendinBlue\Client\ObjectSerializer; class PostSendFailed implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'postSendFailed'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'code' => 'int', 'message' => 'string', 'unexistingEmails' => 'string[]', 'withoutListEmails' => 'string[]', 'blackListedEmails' => 'string[]' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'code' => 'int64', 'message' => null, 'unexistingEmails' => 'email', 'withoutListEmails' => 'email', 'blackListedEmails' => 'email' ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'code' => 'code', 'message' => 'message', 'unexistingEmails' => 'unexistingEmails', 'withoutListEmails' => 'withoutListEmails', 'blackListedEmails' => 'blackListedEmails' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'code' => 'setCode', 'message' => 'setMessage', 'unexistingEmails' => 'setUnexistingEmails', 'withoutListEmails' => '<API key>', 'blackListedEmails' => '<API key>' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'code' => 'getCode', 'message' => 'getMessage', 'unexistingEmails' => 'getUnexistingEmails', 'withoutListEmails' => '<API key>', 'blackListedEmails' => '<API key>' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['code'] = isset($data['code']) ? $data['code'] : null; $this->container['message'] = isset($data['message']) ? $data['message'] : null; $this->container['unexistingEmails'] = isset($data['unexistingEmails']) ? $data['unexistingEmails'] : null; $this->container['withoutListEmails'] = isset($data['withoutListEmails']) ? $data['withoutListEmails'] : null; $this->container['blackListedEmails'] = isset($data['blackListedEmails']) ? $data['blackListedEmails'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function <API key>() { $invalidProperties = []; if ($this->container['code'] === null) { $invalidProperties[] = "'code' can't be null"; } if ($this->container['message'] === null) { $invalidProperties[] = "'message' can't be null"; } return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this-><API key>()) === 0; } /** * Gets code * * @return int */ public function getCode() { return $this->container['code']; } /** * Sets code * * @param int $code Response code * * @return $this */ public function setCode($code) { $this->container['code'] = $code; return $this; } /** * Gets message * * @return string */ public function getMessage() { return $this->container['message']; } /** * Sets message * * @param string $message Response message * * @return $this */ public function setMessage($message) { $this->container['message'] = $message; return $this; } /** * Gets unexistingEmails * * @return string[] */ public function getUnexistingEmails() { return $this->container['unexistingEmails']; } /** * Sets unexistingEmails * * @param string[] $unexistingEmails unexistingEmails * * @return $this */ public function setUnexistingEmails($unexistingEmails) { $this->container['unexistingEmails'] = $unexistingEmails; return $this; } /** * Gets withoutListEmails * * @return string[] */ public function <API key>() { return $this->container['withoutListEmails']; } /** * Sets withoutListEmails * * @param string[] $withoutListEmails withoutListEmails * * @return $this */ public function <API key>($withoutListEmails) { $this->container['withoutListEmails'] = $withoutListEmails; return $this; } /** * Gets blackListedEmails * * @return string[] */ public function <API key>() { return $this->container['blackListedEmails']; } /** * Sets blackListedEmails * * @param string[] $blackListedEmails blackListedEmails * * @return $this */ public function <API key>($blackListedEmails) { $this->container['blackListedEmails'] = $blackListedEmails; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::<API key>($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::<API key>($this)); } }
package view.rendes; import java.awt.Graphics; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JTextField; public class RoundJTextField extends JTextField { private Shape shape; public RoundJTextField(int size) { super(size); setOpaque(false); // As suggested by @AVD in comment. } protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); super.paintComponent(g); } protected void paintBorder(Graphics g) { g.setColor(getForeground()); g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15); } public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15); } return shape.contains(x, y); } }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>For More Information</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" /> <link rel="up" href="preface.html" title="Preface" /> <link rel="prev" href="preface.html" title="Preface" /> <link rel="next" href="introduction.html" title="Chapter 1. Introduction" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.1</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">For More Information</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td> <th width="60%" align="center">Preface</th> <td width="20%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="moreinfo"></a>For More Information</h2> </div> </div> </div> <div class="toc"> <dl> <dt> <span class="sect2"> <a href="moreinfo.html#contact_us">Contact Us</a> </span> </dt> </dl> </div> <p> Beyond this manual, you may also find the following sources of information useful when building a transactional DB application: </p> <div class="itemizedlist"> <ul type="disc"> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/gsg/CXX/index.html" target="_top"> Getting Started with Berkeley DB for C++ </a> </p> </li> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/gsg_db_rep/CXX/index.html" target="_top"> Berkeley DB Getting Started with Replicated Applications for C++ </a> </p> </li> <li> <p> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/<API key>/index.html" target="_top"> Berkeley DB Programmer's Reference Guide </a> </p> </li> <li> <p> <span> <a class="ulink" href="http://docs.oracle.com/cd/E17076_02/html/api_reference/CXX/frame_main.html" target="_top"> Berkeley DB C++ API Reference Guide </a> </span> </p> </li> </ul> </div> <span> <p> To download the latest <span>Berkeley DB</span> documentation along with white papers and other collateral, visit <a class="ulink" href="http: </p> <p> For the latest version of the Oracle <span>Berkeley DB</span> downloads, visit <a class="ulink" href="http: </p> </span> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="contact_us"></a>Contact Us</h3> </div> </div> </div> <p> You can post your comments and questions at the Oracle Technology (OTN) forum for <span> Oracle Berkeley DB at: <a class="ulink" href="https: or for Oracle Berkeley DB High Availability at: <a class="ulink" href="https: </span> </p> <p> For sales or support information, email to: <a class="ulink" href="mailto:berkeleydb-info_us@oracle.com" target="_top">berkeleydb-info_us@oracle.com</a> You can subscribe to a low-volume email announcement list for the Berkeley DB product family by sending email to: <a class="ulink" href="mailto:bdb-join@oss.oracle.com" target="_top">bdb-join@oss.oracle.com</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="preface.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="preface.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="introduction.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Preface </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> Chapter 1. Introduction</td> </tr> </table> </div> </body> </html>
// File: fig0621.cpp // Computer Systems, Fourth Edition // Figure 6.21 #include <iostream> using namespace std; int numPts; int value; int j; void printBar (int n) { int k; for (k = 1; k <= n; k++) { cout << '*'; } cout << endl; } int main () { cin >> numPts; for (j = 1; j <= numPts; j++) { cin >> value; printBar (value); } return 0; }
// This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // <author>pleoNeX</author> // <email>benito356@gmail.com</email> // <date>02/09/2012 3:53:19</date> using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Ekona; namespace NINOKUNI { public partial class TMAPcontrol : UserControl { TMAP tmap; IPluginHost pluginHost; public TMAPcontrol() { InitializeComponent(); } public TMAPcontrol(sFile cfile, IPluginHost pluginHost) { InitializeComponent(); this.pluginHost = pluginHost; tmap = new TMAP(cfile, pluginHost); <API key>(null, null); } ~TMAPcontrol() { tmap = null; } private void <API key>(object sender, EventArgs e) { picMap.Image = tmap.Get_Map((int)numLayer.Value); } private void btnSave_Click(object sender, EventArgs e) { SaveFileDialog o = new SaveFileDialog(); o.AddExtension = true; o.DefaultExt = ".png"; o.FileName = tmap.FileName + ".png"; o.Filter = "Portable Net Graphic (*.png)|*.png"; if (o.ShowDialog() != DialogResult.OK) return; picMap.Image.Save(o.FileName, System.Drawing.Imaging.ImageFormat.Png); o.Dispose(); o = null; } private void <API key>(object sender, EventArgs e) { picMap.SizeMode = (PictureBoxSizeMode)numPicMode.Value; } } }
package cn.nukkit.redstone; import cn.nukkit.block.Block; import cn.nukkit.block.BlockRedstoneWire; import cn.nukkit.block.BlockSolid; import cn.nukkit.math.Vector3; import java.util.*; public class Redstone { public static final int POWER_NONE = 0; public static final int POWER_WEAKEST = 1; public static final int POWER_STRONGEST = 16; //NOTICE: Here POWER_STRONGEST is 16, not 15. //I set it to 16 in order to calculate the energy in blocks, such as the redstone torch under the cobblestone. //At that time, the cobblestone's energy is 16, not 15. If you put a redstone wire next to it, the redstone wire will got 15 energy. //So, POWER_WEAKEST also means that energy in blocks, not redstone wire it self. So set it to 1. private static final Comparator<UpdateObject> orderIsdn = new Comparator<UpdateObject>() { @Override public int compare(UpdateObject o1, UpdateObject o2) { if (o1.getPopulation() > o2.getPopulation()) { return -1; } else if (o1.getPopulation() < o2.getPopulation()) { return 1; } else { return 0; } } }; public static void active(Block source) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); addToQueue(updateQueue, updating); } } } public static void active(Block source, Map<String, Block> allBlocks) { Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); int currentLevel = source.getPowerLevel() - 1; if (currentLevel <= 0) { return; } addToQueue(updateQueue, source); while (!updateQueue.isEmpty()) { UpdateObject updatingObj = updateQueue.poll(); Block updating = updatingObj.getLocation(); currentLevel = updatingObj.getPopulation(); if (currentLevel > updating.getPowerLevel()) { updating.setPowerLevel(currentLevel); updating.getLevel().setBlock(updating, updating, true, true); if (allBlocks.containsKey(updating.getLocationHash())) { allBlocks.remove(updating.getLocationHash()); } addToQueue(updateQueue, updating); } } } public static void deactive(Block source, int updateLevel) { //Step 1: find blocks which need to update Queue<UpdateObject> updateQueue = new PriorityQueue<>(1, orderIsdn); Queue<UpdateObject> sourceList = new PriorityQueue<>(1, orderIsdn); Map<String, Block> updateMap = new HashMap<>(); Map<String, Block> closedMap = new HashMap<>(); int currentLevel = updateLevel; if (currentLevel <= 0) { return; } addToDeactiveQueue(updateQueue, source, closedMap, sourceList, currentLevel); while (!updateQueue.isEmpty()) { UpdateObject updateObject = updateQueue.poll(); Block updating = updateObject.getLocation(); currentLevel = updateObject.getPopulation(); if (currentLevel >= updating.getPowerLevel()) { updating.setPowerLevel(0); updateMap.put(updating.getLocationHash(), updating); addToDeactiveQueue(updateQueue, updating, closedMap, sourceList, currentLevel); } else { sourceList.add(new UpdateObject(updating.getPowerLevel(), updating)); } } //Step 2: recalculate redstone power while (!sourceList.isEmpty()) { active(sourceList.poll().getLocation(), updateMap); } for (Block block : updateMap.values()) { block.setPowerLevel(0); block.getLevel().setBlock(block, block, true, true); } } private static void addToQueue(Queue<UpdateObject> updateQueue, Block location) { if (location.getPowerLevel() <= 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, location.getSide(side))); } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); if (!(block instanceof BlockSolid)) { for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, block.getSide(side))); } } } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_WEST, Vector3.SIDE_EAST, Vector3.SIDE_SOUTH}) { block = location.getSide(side); if (!(block instanceof BlockSolid)) { Block blockDown; blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { updateQueue.add(new UpdateObject(location.getPowerLevel() - 1, blockDown)); } } } } } private static void addToDeactiveQueue(Queue<UpdateObject> updateQueue, Block location, Map<String, Block> closedMap, Queue<UpdateObject> sourceList, int updateLevel) { if (updateLevel < 0) { return; } for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST, Vector3.SIDE_UP, Vector3.SIDE_DOWN}) { if (location.getSide(side).isPowerSource() || (updateLevel == 0 && location.getSide(side).isPowered())) { sourceList.add(new UpdateObject(location.getPowerLevel(side), location.getSide(side))); } else if (location.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(location.getSide(side).getLocationHash())) { closedMap.put(location.getSide(side).getLocationHash(), location.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, location.getSide(side))); } } } if (location instanceof BlockRedstoneWire) { Block block = location.getSide(Vector3.SIDE_UP); for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { if (block.getSide(side) instanceof BlockRedstoneWire) { if (!closedMap.containsKey(block.getSide(side).getLocationHash())) { closedMap.put(block.getSide(side).getLocationHash(), block.getSide(side)); updateQueue.add(new UpdateObject(updateLevel - 1, block.getSide(side))); } } } Block blockDown; for (int side : new int[]{Vector3.SIDE_NORTH, Vector3.SIDE_SOUTH, Vector3.SIDE_EAST, Vector3.SIDE_WEST}) { block = location.getSide(side); blockDown = block.getSide(Vector3.SIDE_DOWN); if (blockDown instanceof BlockRedstoneWire) { if (!closedMap.containsKey(blockDown.getLocationHash())) { closedMap.put(blockDown.getLocationHash(), blockDown); updateQueue.add(new UpdateObject(updateLevel - 1, blockDown)); } } } } } }
include("dat/factions/spawn/common.lua") include("dat/factions/spawn/mercenary_helper.lua") -- @brief Spawns a small patrol fleet. function spawn_patrol () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnLtMerc("Frontier") elseif r < 0.5 then scom.addPilot( pilots, "Frontier Lancelot", 30 ); elseif r < 0.8 then scom.addPilot( pilots, "Frontier Hyena", 20 ); scom.addPilot( pilots, "Frontier Lancelot", 30 ); else scom.addPilot( pilots, "Frontier Hyena", 20 ); scom.addPilot( pilots, "Frontier Ancestor", 25 ); end return pilots end -- @brief Spawns a medium sized squadron. function spawn_squad () local pilots = {} local r = rnd.rnd() if r < pbm then pilots = spawnMdMerc("Frontier") elseif r < 0.5 then scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Phalanx", 55 ); else scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Lancelot", 30 ); scom.addPilot( pilots, "Frontier Ancestor", 25 ); end return pilots end -- @brief Creation hook. function create ( max ) local weights = {} -- Create weights for spawn table weights[ spawn_patrol ] = 100 weights[ spawn_squad ] = 0.33*max -- Create spawn table base on weights spawn_table = scom.createSpawnTable( weights ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( 0, scom.presence(spawn_data), max ) end -- @brief Spawning hook function spawn ( presence, max ) local pilots -- Over limit if presence > max then return 5 end -- Actually spawn the pilots pilots = scom.spawn( spawn_data, "Frontier" ) -- Calculate spawn data spawn_data = scom.choose( spawn_table ) return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots end
# Numenta Platform for Intelligent Computing (NuPIC) # following terms and conditions apply: # This program is free software: you can redistribute it and/or modify # published by the Free Software Foundation. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. import time import numpy from nupic.bindings.math import GetNTAReal from nupic.research.monitor_mixin.monitor_mixin_base import MonitorMixinBase from nupic.research.monitor_mixin.<API key> import ( <API key>) from sensorimotor.<API key> import ( <API key> as <API key>) # Uncomment the line below to use <API key> # from sensorimotor.<API key> import <API key> from sensorimotor.temporal_pooler import TemporalPooler # Uncomment the line below to use <API key> # from sensorimotor.<API key> import <API key> as TemporalPooler from sensorimotor.<API key> import ( <API key>) class <API key>(<API key>, <API key>): pass class <API key>(<API key>, TemporalPooler): pass """ Experiment runner class for running networks with layer 4 and layer 3. The client is responsible for setting up universes, agents, and worlds. This class just sets up and runs the HTM learning algorithms. """ realDType = GetNTAReal() class <API key>(object): DEFAULT_TM_PARAMS = { # These should be decent for most experiments, shouldn't need to override # these too often. Might want to increase cellsPerColumn for capacity # experiments. "cellsPerColumn": 8, "initialPermanence": 0.5, "connectedPermanence": 0.6, "permanenceIncrement": 0.1, "permanenceDecrement": 0.02, # We will force client to override these "columnDimensions": "Sorry", "minThreshold": "Sorry", "maxNewSynapseCount": "Sorry", "activationThreshold": "Sorry", } DEFAULT_TP_PARAMS = { # Need to check these parameters and find stable values that will be # consistent across most experiments. "synPermInactiveDec": 0, # TODO: Check we can use class default here. "synPermActiveInc": 0.001, # TODO: Check we can use class default here. "synPredictedInc": 0.5, # TODO: Why so high?? "potentialPct": 0.9, # TODO: need to check impact of this for pooling "initConnectedPct": 0.5, # TODO: need to check impact of this for pooling "<API key>": 0.0, # We will force client to override these "<API key>": "Sorry", } def __init__(self, tmOverrides=None, tpOverrides=None, seed=42): # Initialize Layer 4 temporal memory params = dict(self.DEFAULT_TM_PARAMS) params.update(tmOverrides or {}) params["seed"] = seed self._checkParams(params) self.tm = <API key>(mmName="TM", **params) # Initialize Layer 3 temporal pooler params = dict(self.DEFAULT_TP_PARAMS) params["inputDimensions"] = [self.tm.numberOfCells()] params["potentialRadius"] = self.tm.numberOfCells() params["seed"] = seed params.update(tpOverrides or {}) self._checkParams(params) self.tp = <API key>(mmName="TP", **params) def _checkParams(self, params): for k,v in params.iteritems(): if v == "Sorry": raise RuntimeError("Param "+k+" must be specified") def feedTransition(self, sensorPattern, motorPattern, sensorimotorPattern, tmLearn=True, tpLearn=None, sequenceLabel=None): if sensorPattern is None: self.tm.reset() self.tp.reset() else: # Feed the TM self.tm.compute(sensorPattern, activeExternalCells=motorPattern, <API key>=True, learn=tmLearn, sequenceLabel=sequenceLabel) # If requested, feed the TP if tpLearn is not None: tpInputVector, burstingColumns, <API key> = ( self.formatInputForTP()) activeArray = numpy.zeros(self.tp.getNumColumns()) self.tp.compute(tpInputVector, tpLearn, activeArray, burstingColumns, <API key>, sequenceLabel=sequenceLabel) def feedLayers(self, sequences, tmLearn=True, tpLearn=None, verbosity=0, <API key>=None): """ Feed the given sequences to the HTM algorithms. @param tmLearn: (bool) Either False, or True @param tpLearn: (None,bool) Either None, False, or True. If None, temporal pooler will be skipped. @param <API key>: (int) Prints progress every N iterations, where N is the value of this param """ (sensorSequence, motorSequence, <API key>, sequenceLabels) = sequences currentTime = time.time() for i in xrange(len(sensorSequence)): sensorPattern = sensorSequence[i] motorPattern = motorSequence[i] sensorimotorPattern = <API key>[i] sequenceLabel = sequenceLabels[i] self.feedTransition(sensorPattern, motorPattern, sensorimotorPattern, tmLearn=tmLearn, tpLearn=tpLearn, sequenceLabel=sequenceLabel) if (<API key> is not None and i > 0 and i % <API key> == 0): print ("Fed {0} / {1} elements of the sequence " "in {2:0.2f} seconds.".format( i, len(sensorSequence), time.time() - currentTime)) currentTime = time.time() if verbosity >= 2: # Print default TM traces traces = self.tm.mmGetDefaultTraces(verbosity=verbosity) print MonitorMixinBase.mmPrettyPrintTraces(traces, breakOnResets= self.tm.mmGetTraceResets()) if tpLearn is not None: # Print default TP traces traces = self.tp.mmGetDefaultTraces(verbosity=verbosity) print MonitorMixinBase.mmPrettyPrintTraces(traces, breakOnResets= self.tp.mmGetTraceResets()) print @staticmethod def generateSequences(length, agents, numSequences=1, verbosity=0): """ @param length (int) Length of each sequence to generate, one for each agent @param agents (AbstractAgent) Agents acting in their worlds @return (tuple) (sensor sequence, motor sequence, sensorimotor sequence, sequence labels) """ sensorSequence = [] motorSequence = [] <API key> = [] sequenceLabels = [] for _ in xrange(numSequences): for agent in agents: s,m,sm = agent.<API key>(length, verbosity=verbosity) sensorSequence += s motorSequence += m <API key> += sm sequenceLabels += [agent.world.toString()] * length sensorSequence.append(None) motorSequence.append(None) <API key>.append(None) sequenceLabels.append(None) return sensorSequence, motorSequence, <API key>, sequenceLabels def formatInputForTP(self): """ Given an instance of the TM, format the information we need to send to the TP. """ # all currently active cells in layer 4 tpInputVector = numpy.zeros( self.tm.numberOfCells()).astype(realDType) tpInputVector[list(self.tm.activeCellsIndices())] = 1 # bursting columns in layer 4 burstingColumns = numpy.zeros( self.tm.numberOfColumns()).astype(realDType) burstingColumns[list(self.tm.<API key>)] = 1 # correctly predicted cells in layer 4 <API key> = numpy.zeros( self.tm.numberOfCells()).astype(realDType) <API key>[list(self.tm.<API key>())] = 1 return tpInputVector, burstingColumns, <API key> def formatRow(self, x, formatString = "%d", rowSize = 700): """ Utility routine for pretty printing large vectors """ s = '' for c,v in enumerate(x): if c > 0 and c % 7 == 0: s += ' ' if c > 0 and c % rowSize == 0: s += '\n' s += formatString % v s += ' ' return s
#include "resizecontroller.h" #include "formeditoritem.h" #include "layeritem.h" #include <resizehandleitem.h> #include <QCursor> #include <QGraphicsScene> namespace QmlDesigner { class <API key> { public: <API key>(LayerItem *layerItem, FormEditorItem *formEditorItem); <API key>(const <API key> &other); ~<API key>(); QPointer<LayerItem> layerItem; FormEditorItem *formEditorItem = nullptr; QSharedPointer<ResizeHandleItem> topLeftItem; QSharedPointer<ResizeHandleItem> topRightItem; QSharedPointer<ResizeHandleItem> bottomLeftItem; QSharedPointer<ResizeHandleItem> bottomRightItem; QSharedPointer<ResizeHandleItem> topItem; QSharedPointer<ResizeHandleItem> leftItem; QSharedPointer<ResizeHandleItem> rightItem; QSharedPointer<ResizeHandleItem> bottomItem; }; <API key>::<API key>(LayerItem *layerItem, FormEditorItem *formEditorItem) : layerItem(layerItem), formEditorItem(formEditorItem), topLeftItem(nullptr), topRightItem(nullptr), bottomLeftItem(nullptr), bottomRightItem(nullptr), topItem(nullptr), leftItem(nullptr), rightItem(nullptr), bottomItem(nullptr) { } <API key>::<API key>(const <API key> &other) = default; <API key>::~<API key>() { if (layerItem) { QGraphicsScene *scene = layerItem->scene(); scene->removeItem(topLeftItem.data()); scene->removeItem(topRightItem.data()); scene->removeItem(bottomLeftItem.data()); scene->removeItem(bottomRightItem.data()); scene->removeItem(topItem.data()); scene->removeItem(leftItem.data()); scene->removeItem(rightItem.data()); scene->removeItem(bottomItem.data()); } } ResizeController::ResizeController() : m_data(new <API key>(nullptr, nullptr)) { } ResizeController::ResizeController(const QSharedPointer<<API key>> &data) : m_data(data) { } ResizeController::ResizeController(LayerItem *layerItem, FormEditorItem *formEditorItem) : m_data(new <API key>(layerItem, formEditorItem)) { m_data->topLeftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topLeftItem->setZValue(302); m_data->topLeftItem->setCursor(Qt::SizeFDiagCursor); m_data->topRightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topRightItem->setZValue(301); m_data->topRightItem->setCursor(Qt::SizeBDiagCursor); m_data->bottomLeftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomLeftItem->setZValue(301); m_data->bottomLeftItem->setCursor(Qt::SizeBDiagCursor); m_data->bottomRightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomRightItem->setZValue(305); m_data->bottomRightItem->setCursor(Qt::SizeFDiagCursor); m_data->topItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->topItem->setZValue(300); m_data->topItem->setCursor(Qt::SizeVerCursor); m_data->leftItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->leftItem->setZValue(300); m_data->leftItem->setCursor(Qt::SizeHorCursor); m_data->rightItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->rightItem->setZValue(300); m_data->rightItem->setCursor(Qt::SizeHorCursor); m_data->bottomItem = QSharedPointer<ResizeHandleItem>(new ResizeHandleItem(layerItem, *this)); m_data->bottomItem->setZValue(300); m_data->bottomItem->setCursor(Qt::SizeVerCursor); updatePosition(); } ResizeController::ResizeController(const ResizeController &other) = default; ResizeController::ResizeController(const <API key> &resizeController) : m_data(resizeController.m_data.toStrongRef()) { } ResizeController::~ResizeController() = default; ResizeController &ResizeController::operator =(const ResizeController &other) { if (this != &other) m_data = other.m_data; return *this; } bool ResizeController::isValid() const { return m_data->formEditorItem && m_data->formEditorItem->qmlItemNode().isValid(); } void ResizeController::show() { m_data->topLeftItem->show(); m_data->topRightItem->show(); m_data->bottomLeftItem->show(); m_data->bottomRightItem->show(); m_data->topItem->show(); m_data->leftItem->show(); m_data->rightItem->show(); m_data->bottomItem->show(); } void ResizeController::hide() { m_data->topLeftItem->hide(); m_data->topRightItem->hide(); m_data->bottomLeftItem->hide(); m_data->bottomRightItem->hide(); m_data->topItem->hide(); m_data->leftItem->hide(); m_data->rightItem->hide(); m_data->bottomItem->hide(); } static QPointF topCenter(const QRectF &rect) { return {rect.center().x(), rect.top()}; } static QPointF leftCenter(const QRectF &rect) { return {rect.left(), rect.center().y()}; } static QPointF rightCenter(const QRectF &rect) { return {rect.right(), rect.center().y()}; } static QPointF bottomCenter(const QRectF &rect) { return {rect.center().x(), rect.bottom()}; } void ResizeController::updatePosition() { if (isValid()) { QRectF boundingRect = m_data->formEditorItem->qmlItemNode().<API key>(); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.topLeft())); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.topRight())); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.bottomLeft())); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), boundingRect.bottomRight())); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), topCenter(boundingRect))); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), leftCenter(boundingRect))); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), rightCenter(boundingRect))); QPointF <API key>(m_data->formEditorItem->mapToItem(m_data->layerItem.data(), bottomCenter(boundingRect))); m_data->topRightItem->setHandlePosition(<API key>, boundingRect.topRight()); m_data->topLeftItem->setHandlePosition(<API key>, boundingRect.topLeft()); m_data->bottomLeftItem->setHandlePosition(<API key>, boundingRect.bottomLeft()); m_data->bottomRightItem->setHandlePosition(<API key>, boundingRect.bottomRight()); m_data->topItem->setHandlePosition(<API key>, topCenter(boundingRect)); m_data->leftItem->setHandlePosition(<API key>, leftCenter(boundingRect)); m_data->rightItem->setHandlePosition(<API key>, rightCenter(boundingRect)); m_data->bottomItem->setHandlePosition(<API key>, bottomCenter(boundingRect)); } } FormEditorItem* ResizeController::formEditorItem() const { return m_data->formEditorItem; } bool ResizeController::isTopLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->topLeftItem; } bool ResizeController::isTopRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->topRightItem; } bool ResizeController::isBottomLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomLeftItem; } bool ResizeController::isBottomRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomRightItem; } bool ResizeController::isTopHandle(const ResizeHandleItem *handle) const { return handle == m_data->topItem; } bool ResizeController::isLeftHandle(const ResizeHandleItem *handle) const { return handle == m_data->leftItem; } bool ResizeController::isRightHandle(const ResizeHandleItem *handle) const { return handle == m_data->rightItem; } bool ResizeController::isBottomHandle(const ResizeHandleItem *handle) const { return handle == m_data->bottomItem; } <API key> ResizeController::<API key>() const { return <API key>(*this); } <API key>::<API key>() = default; <API key>::<API key>(const <API key> &resizeController) = default; <API key>::<API key>(const ResizeController &resizeController) : m_data(resizeController.m_data.toWeakRef()) { } <API key>::~<API key>() = default; <API key> &<API key>::operator =(const <API key> &other) { if (m_data != other.m_data) m_data = other.m_data; return *this; } ResizeController <API key>::toResizeController() const { return ResizeController(*this); } }
#include "gm.h" #include "SkPathEffect.h" #include "SkPictureRecorder.h" #include "<API key>.h" #include "SkShadowShader.h" #include "SkSurface.h" #ifdef <API key> static sk_sp<SkPicture> make_test_picture(int width, int height) { SkPictureRecorder recorder; // LONG RANGE TODO: eventually add SkBBHFactory (bounding box factory) SkCanvas* canvas = recorder.beginRecording(SkRect::MakeIWH(width, height)); SkASSERT(canvas->getTotalMatrix().isIdentity()); SkPaint paint; paint.setColor(SK_ColorGRAY); // LONG RANGE TODO: tag occluders // LONG RANGE TODO: track number of IDs we need (hopefully less than 256) // and determinate the mapping from z to id // universal receiver, "ground" canvas->drawRect(SkRect::MakeIWH(width, height), paint); // TODO: Maybe add the ID here along with the depth paint.setColor(0xFFEE8888); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(200,150,350,300), paint); paint.setColor(0xFF88EE88); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(150,200,300,350), paint); paint.setColor(0xFF8888EE); canvas->translateZ(80); canvas->drawRect(SkRect::MakeLTRB(100,100,250,250), paint); // TODO: Add an assert that Z order matches painter's order // TODO: think about if the Z-order always matching painting order is too strict return recorder.<API key>(); } namespace skiagm { class ShadowMapsGM : public GM { public: ShadowMapsGM() { this->setBGColor(sk_tool_utils::color_to_565(0xFFCCCCCC)); } void onOnceBeforeDraw() override { // Create a light set consisting of // - bluish directional light pointing more right than down // - reddish directional light pointing more down than right // - soft white ambient light SkLights::Builder builder; builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(0.2f, 0.3f, 0.4f), SkVector3::Make(0.2f, 0.1f, 1.0f))); builder.add(SkLights::Light::MakeDirectional(SkColor3f::Make(0.4f, 0.3f, 0.2f), SkVector3::Make(0.1f, 0.2f, 1.0f))); builder.<API key>(SkColor3f::Make(0.4f, 0.4f, 0.4f)); fLights = builder.finish(); fShadowParams.fShadowRadius = 4.0f; fShadowParams.fBiasingConstant = 0.3f; fShadowParams.fMinVariance = 1024; fShadowParams.fType = SkShadowParams::<API key>; } protected: static constexpr int kWidth = 400; static constexpr int kHeight = 400; SkString onShortName() override { return SkString("shadowmaps"); } SkISize onISize() override { return SkISize::Make(kWidth, kHeight); } void onDraw(SkCanvas* canvas) override { // This picture stores the picture of the scene. // It's used to generate the depth maps. sk_sp<SkPicture> pic(make_test_picture(kWidth, kHeight)); canvas->setLights(fLights); canvas->drawShadowedPicture(pic, nullptr, nullptr, fShadowParams); } private: sk_sp<SkLights> fLights; SkShadowParams fShadowParams; typedef GM INHERITED; }; DEF_GM(return new ShadowMapsGM;) } #endif
// -*- Mode: Go; indent-tabs-mode: t -*- package main import ( "errors" "fmt" "strings" "time" "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" ) var ( shortModelHelp = i18n.G("Get the active model for this device") longModelHelp = i18n.G(` The model command returns the active model assertion information for this device. By default, only the essential model identification information is included in the output, but this can be expanded to include all of an assertion's non-meta headers. The verbose output is presented in a structured, yaml-like format. Similarly, the active serial assertion can be used for the output instead of the model assertion. `) invalidTypeMessage = i18n.G("invalid type for %q header") errNoMainAssertion = errors.New(i18n.G("device not ready yet (no assertions found)")) errNoSerial = errors.New(i18n.G("device not registered yet (no serial assertion found)")) <API key> = errors.New(i18n.G("cannot use --verbose with --assertion")) // this list is a "nice" "human" "readable" "ordering" of headers to print // off, sorted in lexical order with meta headers and primary key headers // removed, and big nasty keys such as device-key-sha3-384 and // device-key at the bottom // it also contains both serial and model assertion headers, but we // follow the same code path for both assertion types and some of the // headers are shared between the two, so it still works out correctly niceOrdering = [...]string{ "architecture", "base", "classic", "display-name", "gadget", "kernel", "revision", "store", "<API key>", "timestamp", "required-snaps", // for uc16 and uc18 models "snaps", // for uc20 models "device-key-sha3-384", "device-key", } ) type cmdModel struct { clientMixin timeMixin colorMixin Serial bool `long:"serial"` Verbose bool `long:"verbose"` Assertion bool `long:"assertion"` } func init() { addCommand("model", shortModelHelp, longModelHelp, func() flags.Commander { return &cmdModel{} }, colorDescs.also(timeDescs).also(map[string]string{ "assertion": i18n.G("Print the raw assertion."), "verbose": i18n.G("Print all specific assertion fields."), "serial": i18n.G( "Print the serial assertion instead of the model assertion."), }), []argDesc{}, ) } func (x *cmdModel) Execute(args []string) error { if x.Verbose && x.Assertion { // can't do a verbose mode for the assertion return <API key> } var mainAssertion asserts.Assertion serialAssertion, serialErr := x.client.<API key>() modelAssertion, modelErr := x.client.<API key>() // if we didn't get a model assertion bail early if modelErr != nil { if client.<API key>(modelErr) { // device is not registered yet - use specific error message return errNoMainAssertion } return modelErr } // if the serial assertion error is anything other than not found, also // bail early // the serial assertion not being found may not be fatal if serialErr != nil && !client.<API key>(serialErr) { return serialErr } if x.Serial { mainAssertion = serialAssertion } else { mainAssertion = modelAssertion } if x.Assertion { // if we are using the serial assertion and we specifically didn't find the // serial assertion, bail with specific error if x.Serial && client.<API key>(serialErr) { return errNoMainAssertion } _, err := Stdout.Write(asserts.Encode(mainAssertion)) return err } termWidth, _ := termSize() termWidth -= 3 if termWidth > 100 { // any wider than this and it gets hard to read termWidth = 100 } esc := x.getEscapes() w := tabWriter() if x.Serial && client.<API key>(serialErr) { // for serial assertion, the primary keys are output (model and // brand-id), but if we didn't find the serial assertion then we still // output the brand-id and model from the model assertion, but also // return a devNotReady error fmt.Fprintf(w, "brand-id:\t%s\n", modelAssertion.HeaderString("brand-id")) fmt.Fprintf(w, "model:\t%s\n", modelAssertion.HeaderString("model")) w.Flush() return errNoSerial } // the rest of this function is the main flow for outputting either the // model or serial assertion in normal or verbose mode // for the `snap model` case with no options, we don't want colons, we want // to be like `snap version` separator := ":" if !x.Verbose && !x.Serial { separator = "" } // ordering of the primary keys for model: brand, model, serial // ordering of primary keys for serial is brand-id, model, serial // output brand/brand-id brandIDHeader := mainAssertion.HeaderString("brand-id") modelHeader := mainAssertion.HeaderString("model") // for the serial header, if there's no serial yet, it's not an error for // model (and we already handled the serial error above) but need to add a // parenthetical about the device not being registered yet var serial string if client.<API key>(serialErr) { if x.Verbose || x.Serial { // verbose and serial are yamlish, so we need to escape the dash serial = esc.dash } else { serial = "-" } serial += " (device not registered yet)" } else { serial = serialAssertion.HeaderString("serial") } // handle brand/brand-id and model/model + display-name differently on just // `snap model` w/o opts if x.Serial || x.Verbose { fmt.Fprintf(w, "brand-id:\t%s\n", brandIDHeader) fmt.Fprintf(w, "model:\t%s\n", modelHeader) } else { // for the model command (not --serial) we want to show a publisher // style display of "brand" instead of just "brand-id" storeAccount, err := x.client.StoreAccount(brandIDHeader) if err != nil { return err } // use the longPublisher helper to format the brand store account // like we do in `snap info` fmt.Fprintf(w, "brand%s\t%s\n", separator, longPublisher(x.getEscapes(), storeAccount)) // for model, if there's a display-name, we show that first with the // real model in parenthesis if displayName := modelAssertion.HeaderString("display-name"); displayName != "" { modelHeader = fmt.Sprintf("%s (%s)", displayName, modelHeader) } fmt.Fprintf(w, "model%s\t%s\n", separator, modelHeader) } // only output the grade if it is non-empty, either it is not in the model // assertion for all non-uc20 model assertions, or it is non-empty and // required for uc20 model assertions grade := modelAssertion.HeaderString("grade") if grade != "" { fmt.Fprintf(w, "grade%s\t%s\n", separator, grade) } storageSafety := modelAssertion.HeaderString("storage-safety") if storageSafety != "" { fmt.Fprintf(w, "storage-safety%s\t%s\n", separator, storageSafety) } // serial is same for all variants fmt.Fprintf(w, "serial%s\t%s\n", separator, serial) // --verbose means output more information if x.Verbose { allHeadersMap := mainAssertion.Headers() for _, headerName := range niceOrdering { invalidTypeErr := fmt.Errorf(invalidTypeMessage, headerName) headerValue, ok := allHeadersMap[headerName] // make sure the header is in the map if !ok { continue } // switch on which header it is to handle some special cases switch headerName { // list of scalars case "required-snaps", "<API key>": headerIfaceList, ok := headerValue.([]interface{}) if !ok { return invalidTypeErr } if len(headerIfaceList) == 0 { continue } fmt.Fprintf(w, "%s:\t\n", headerName) for _, elem := range headerIfaceList { headerStringElem, ok := elem.(string) if !ok { return invalidTypeErr } // note we don't wrap these, since for now this is // specifically just required-snaps and so all of these // will be snap names which are required to be short fmt.Fprintf(w, " - %s\n", headerStringElem) } //timestamp needs to be formatted with fmtTime from the timeMixin case "timestamp": timestamp, ok := headerValue.(string) if !ok { return invalidTypeErr } // parse the time string as RFC3339, which is what the format is // always in for assertions t, err := time.Parse(time.RFC3339, timestamp) if err != nil { return err } fmt.Fprintf(w, "timestamp:\t%s\n", x.fmtTime(t)) // long string key we don't want to rewrap but can safely handle // on "reasonable" width terminals case "device-key-sha3-384": // also flush the writer before continuing so the previous keys // don't try to align with this key w.Flush() headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } switch { case termWidth > 86: fmt.Fprintf(w, "device-key-sha3-384: %s\n", headerString) case termWidth <= 86 && termWidth > 66: fmt.Fprintln(w, "device-key-sha3-384: |") wrapLine(w, []rune(headerString), " ", termWidth) } case "snaps": // also flush the writer before continuing so the previous keys // don't try to align with this key w.Flush() snapsHeader, ok := headerValue.([]interface{}) if !ok { return invalidTypeErr } if len(snapsHeader) == 0 { // unexpected why this is an empty list, but just ignore for // now continue } fmt.Fprintf(w, "snaps:\n") for _, sn := range snapsHeader { snMap, ok := sn.(map[string]interface{}) if !ok { return invalidTypeErr } // iterate over all keys in the map in a stable, visually // appealing ordering // first do snap name, which will always be present since we // parsed a valid assertion name := snMap["name"].(string) fmt.Fprintf(w, " - name:\t%s\n", name) // the rest of these may be absent, but they are all still // simple strings for _, snKey := range []string{"id", "type", "default-channel", "presence"} { snValue, ok := snMap[snKey] if !ok { continue } snStrValue, ok := snValue.(string) if !ok { return invalidTypeErr } if snStrValue != "" { fmt.Fprintf(w, " %s:\t%s\n", snKey, snStrValue) } } // finally handle "modes" which is a list modes, ok := snMap["modes"] if !ok { continue } modesSlice, ok := modes.([]interface{}) if !ok { return invalidTypeErr } if len(modesSlice) == 0 { continue } modeStrSlice := make([]string, 0, len(modesSlice)) for _, mode := range modesSlice { modeStr, ok := mode.(string) if !ok { return invalidTypeErr } modeStrSlice = append(modeStrSlice, modeStr) } modesSliceYamlStr := "[" + strings.Join(modeStrSlice, ", ") + "]" fmt.Fprintf(w, " modes:\t%s\n", modesSliceYamlStr) } // long base64 key we can rewrap safely case "device-key": headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } // the string value here has newlines inserted as part of the // raw assertion, but base64 doesn't care about whitespace, so // it's safe to split by newlines and re-wrap to make it // prettier headerString = strings.Join( strings.Split(headerString, "\n"), "") fmt.Fprintln(w, "device-key: |") wrapLine(w, []rune(headerString), " ", termWidth) // the default is all the rest of short scalar values, which all // should be strings default: headerString, ok := headerValue.(string) if !ok { return invalidTypeErr } fmt.Fprintf(w, "%s:\t%s\n", headerName, headerString) } } } return w.Flush() }
using System.Collections.Generic; using System.Linq; namespace PKHeX.Core { <summary> Editor object that unpacks <see cref="EventWork{T}"/> into flags & work groups, and handles value get/set operations. </summary> <typeparam name="T"></typeparam> public sealed class SplitEventEditor<T> where T : struct { public readonly IList<EventVarGroup> Work; public readonly IList<EventVarGroup> Flag; public readonly IEventVar<T> Block; public SplitEventEditor(IEventVar<T> block, IEnumerable<string> work, IEnumerable<string> flag) { Block = block; // load lines var workLines = work.Where(z => !string.IsNullOrWhiteSpace(z) && z.Length > 5); Work = EventWorkUtil.GetVars(workLines, (index, t, data) => new EventWork<T>(index, t, data)); var flagLines = flag.Where(z => !string.IsNullOrWhiteSpace(z) && z.Length > 5); Flag = EventWorkUtil.GetVars(flagLines, (index, t, data) => new EventFlag(index, t, data)); // initialize lines foreach (var group in Work) { foreach (var item in group.Vars) { item.RawIndex = block.GetWorkRawIndex(item.Type, item.RelativeIndex); ((EventWork<T>)item).Value = block.GetWork(item.RawIndex); } } foreach (var group in Flag) { foreach (var item in group.Vars) { item.RawIndex = block.GetFlagRawIndex(item.Type, item.RelativeIndex); ((EventFlag)item).Flag = block.GetFlag(item.RawIndex); } } } <summary> Writes all of the updated event values back to the block. </summary> public void Save() { foreach (var g in Work) { foreach (var item in g.Vars) { var value = ((EventWork<T>)item).Value; Block.SetWork(item.RawIndex, value); } } foreach (var g in Flag) { foreach (var item in g.Vars) { var value = ((EventFlag)item).Flag; Block.SetFlag(item.RawIndex, value); } } } } }
@import url("https://fonts.googleapis.com/css?family=Ubuntu:400,700"); html { font-family: sans-serif; line-height: 1.15; -ms-text-size-adjust: 100%; -<API key>: 100%; } body { margin: 0; } article, aside, footer, header, nav, section { display: block; } h1 { font-size: 2em; margin: 0.67em 0; } figcaption, figure, main { display: block; } figure { margin: 1em 40px; } hr { -webkit-box-sizing: content-box; box-sizing: content-box; height: 0; overflow: visible; } pre { font-family: monospace, monospace; font-size: 1em; } a { background-color: transparent; -<API key>: objects; } a:active, a:hover { outline-width: 0; } abbr[title] { border-bottom: none; text-decoration: underline; text-decoration: underline dotted; } b, strong { font-weight: inherit; } b, strong { font-weight: bolder; } code, kbd, samp { font-family: monospace, monospace; font-size: 1em; } dfn { font-style: italic; } mark { background-color: #ff0; color: #000; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } audio, video { display: inline-block; } audio:not([controls]) { display: none; height: 0; } img { border-style: none; } svg:not(:root) { overflow: hidden; } button, input, optgroup, select, textarea { font-family: sans-serif; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } button, select { text-transform: none; } button, html [type="button"], [type="reset"], [type="submit"] { -webkit-appearance: button; } button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { border-style: none; padding: 0; } button:-moz-focusring, [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring { outline: 1px dotted ButtonText; } fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } legend { -webkit-box-sizing: border-box; box-sizing: border-box; color: inherit; display: table; max-width: 100%; padding: 0; white-space: normal; } progress { display: inline-block; vertical-align: baseline; } textarea { overflow: auto; } [type="checkbox"], [type="radio"] { -webkit-box-sizing: border-box; box-sizing: border-box; padding: 0; } [type="number"]::-<API key>, [type="number"]::-<API key> { height: auto; } [type="search"] { -webkit-appearance: textfield; outline-offset: -2px; } [type="search"]::-<API key>, [type="search"]::-<API key> { -webkit-appearance: none; } ::-<API key> { -webkit-appearance: button; font: inherit; } details, menu { display: block; } summary { display: list-item; } canvas { display: inline-block; } template { display: none; } [hidden] { display: none; } @media print { *, *::before, *::after, p::first-letter, div::first-letter, blockquote::first-letter, li::first-letter, p::first-line, div::first-line, blockquote::first-line, li::first-line { text-shadow: none !important; -webkit-box-shadow: none !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } abbr[title]::after { content: " (" attr(title) ")"; } pre { white-space: pre-wrap !important; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } .navbar { display: none; } .badge { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table td, .table th { background-color: #fff !important; } .table-bordered th, .table-bordered td { border: 1px solid #ddd !important; } } html { -webkit-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizing: inherit; box-sizing: inherit; } @-ms-viewport { width: device-width; } html { -ms-overflow-style: scrollbar; -<API key>: transparent; } body { font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 1rem; font-weight: normal; line-height: 1.5; color: #333; background-color: #fff; } [tabindex="-1"]:focus { outline: none !important; } h1, h2, h3, h4, h5, h6 { margin-top: 0; margin-bottom: .5rem; } p { margin-top: 0; margin-bottom: 1rem; } abbr[title], abbr[data-original-title] { cursor: help; } address { margin-bottom: 1rem; font-style: normal; line-height: inherit; } ol, ul, dl { margin-top: 0; margin-bottom: 1rem; } ol ol, ul ul, ol ul, ul ol { margin-bottom: 0; } dt { font-weight: bold; } dd { margin-bottom: .5rem; margin-left: 0; } blockquote { margin: 0 0 1rem; } a { color: #E95420; text-decoration: none; } a:focus, a:hover { color: #ac3911; text-decoration: underline; } a:not([href]):not([tabindex]) { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus, a:not([href]):not([tabindex]):hover { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus { outline: 0; } pre { margin-top: 0; margin-bottom: 1rem; overflow: auto; } figure { margin: 0 0 1rem; } img { vertical-align: middle; } [role="button"] { cursor: pointer; } a, area, button, [role="button"], input, label, select, summary, textarea { -ms-touch-action: manipulation; touch-action: manipulation; } table { border-collapse: collapse; background-color: transparent; } caption { padding-top: 0.75rem; padding-bottom: 0.75rem; color: #777; text-align: left; caption-side: bottom; } th { text-align: left; } label { display: inline-block; margin-bottom: .5rem; } button:focus { outline: 1px dotted; outline: 5px auto -<API key>; } input, button, select, textarea { line-height: inherit; } input[type="radio"]:disabled, input[type="checkbox"]:disabled { cursor: not-allowed; } input[type="date"], input[type="time"], input[type="datetime-local"], input[type="month"] { -webkit-appearance: listbox; } textarea { resize: vertical; } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: .5rem; font-size: 1.5rem; line-height: inherit; } input[type="search"] { -webkit-appearance: none; } output { display: inline-block; } [hidden] { display: none !important; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { margin-bottom: 0.5rem; font-family: inherit; font-weight: 500; line-height: 1.1; color: inherit; } h1, .h1 { font-size: 2.5rem; } h2, .h2 { font-size: 2rem; } h3, .h3 { font-size: 1.75rem; } h4, .h4 { font-size: 1.5rem; } h5, .h5 { font-size: 1.25rem; } h6, .h6 { font-size: 1rem; } .lead { font-size: 1.25rem; font-weight: 300; } .display-1 { font-size: 6rem; font-weight: 300; line-height: 1.1; } .display-2 { font-size: 5.5rem; font-weight: 300; line-height: 1.1; } .display-3 { font-size: 4.5rem; font-weight: 300; line-height: 1.1; } .display-4 { font-size: 3.5rem; font-weight: 300; line-height: 1.1; } hr { margin-top: 1rem; margin-bottom: 1rem; border: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); } small, .small { font-size: 80%; font-weight: normal; } mark, .mark { padding: 0.2em; background-color: #fcf8e3; } .list-unstyled { padding-left: 0; list-style: none; } .list-inline { padding-left: 0; list-style: none; } .list-inline-item { display: inline-block; } .list-inline-item:not(:last-child) { margin-right: 5px; } .initialism { font-size: 90%; text-transform: uppercase; } .blockquote { padding: 0.5rem 1rem; margin-bottom: 1rem; font-size: 1.25rem; border-left: 0.25rem solid #AEA79F; } .blockquote-footer { display: block; font-size: 80%; color: #777; } .blockquote-footer::before { content: "\2014 \00A0"; } .blockquote-reverse { padding-right: 1rem; padding-left: 0; text-align: right; border-right: 0.25rem solid #AEA79F; border-left: 0; } .blockquote-reverse .blockquote-footer::before { content: ""; } .blockquote-reverse .blockquote-footer::after { content: "\00A0 \2014"; } .img-fluid { max-width: 100%; height: auto; } .img-thumbnail { padding: 0.25rem; background-color: #fff; border: 1px solid #ddd; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; max-width: 100%; height: auto; } .figure { display: inline-block; } .figure-img { margin-bottom: 0.5rem; line-height: 1; } .figure-caption { font-size: 90%; color: #777; } code, kbd, pre, samp { font-family: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } code { padding: 0.2rem 0.4rem; font-size: 90%; color: #bd4147; background-color: #eee; border-radius: 0.25rem; } a > code { padding: 0; color: inherit; background-color: inherit; } kbd { padding: 0.2rem 0.4rem; font-size: 90%; color: #fff; background-color: #222; border-radius: 0.2rem; } kbd kbd { padding: 0; font-size: 100%; font-weight: bold; } pre { display: block; margin-top: 0; margin-bottom: 1rem; font-size: 90%; color: #222; } pre code { padding: 0; font-size: inherit; color: inherit; background-color: transparent; border-radius: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .container { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 576px) { .container { width: 540px; max-width: 100%; } } @media (min-width: 768px) { .container { width: 720px; max-width: 100%; } } @media (min-width: 992px) { .container { width: 960px; max-width: 100%; } } @media (min-width: 1200px) { .container { width: 1140px; max-width: 100%; } } .container-fluid { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } .row { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } @media (min-width: 576px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 768px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 992px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 1200px) { .row { margin-right: -15px; margin-left: -15px; } } .no-gutters { margin-right: 0; margin-left: 0; } .no-gutters > .col, .no-gutters > [class*="col-"] { padding-right: 0; padding-left: 0; } .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } .col { -webkit-flex-basis: 0; -<API key>: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-0 { right: auto; } .pull-1 { right: 8.33333333%; } .pull-2 { right: 16.66666667%; } .pull-3 { right: 25%; } .pull-4 { right: 33.33333333%; } .pull-5 { right: 41.66666667%; } .pull-6 { right: 50%; } .pull-7 { right: 58.33333333%; } .pull-8 { right: 66.66666667%; } .pull-9 { right: 75%; } .pull-10 { right: 83.33333333%; } .pull-11 { right: 91.66666667%; } .pull-12 { right: 100%; } .push-0 { left: auto; } .push-1 { left: 8.33333333%; } .push-2 { left: 16.66666667%; } .push-3 { left: 25%; } .push-4 { left: 33.33333333%; } .push-5 { left: 41.66666667%; } .push-6 { left: 50%; } .push-7 { left: 58.33333333%; } .push-8 { left: 66.66666667%; } .push-9 { left: 75%; } .push-10 { left: 83.33333333%; } .push-11 { left: 91.66666667%; } .push-12 { left: 100%; } .offset-1 { margin-left: 8.33333333%; } .offset-2 { margin-left: 16.66666667%; } .offset-3 { margin-left: 25%; } .offset-4 { margin-left: 33.33333333%; } .offset-5 { margin-left: 41.66666667%; } .offset-6 { margin-left: 50%; } .offset-7 { margin-left: 58.33333333%; } .offset-8 { margin-left: 66.66666667%; } .offset-9 { margin-left: 75%; } .offset-10 { margin-left: 83.33333333%; } .offset-11 { margin-left: 91.66666667%; } @media (min-width: 576px) { .col-sm { -webkit-flex-basis: 0; -<API key>: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-sm-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-sm-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-sm-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-sm-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-sm-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-sm-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-sm-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-sm-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-sm-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-sm-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-sm-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-sm-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-sm-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-sm-0 { right: auto; } .pull-sm-1 { right: 8.33333333%; } .pull-sm-2 { right: 16.66666667%; } .pull-sm-3 { right: 25%; } .pull-sm-4 { right: 33.33333333%; } .pull-sm-5 { right: 41.66666667%; } .pull-sm-6 { right: 50%; } .pull-sm-7 { right: 58.33333333%; } .pull-sm-8 { right: 66.66666667%; } .pull-sm-9 { right: 75%; } .pull-sm-10 { right: 83.33333333%; } .pull-sm-11 { right: 91.66666667%; } .pull-sm-12 { right: 100%; } .push-sm-0 { left: auto; } .push-sm-1 { left: 8.33333333%; } .push-sm-2 { left: 16.66666667%; } .push-sm-3 { left: 25%; } .push-sm-4 { left: 33.33333333%; } .push-sm-5 { left: 41.66666667%; } .push-sm-6 { left: 50%; } .push-sm-7 { left: 58.33333333%; } .push-sm-8 { left: 66.66666667%; } .push-sm-9 { left: 75%; } .push-sm-10 { left: 83.33333333%; } .push-sm-11 { left: 91.66666667%; } .push-sm-12 { left: 100%; } .offset-sm-0 { margin-left: 0%; } .offset-sm-1 { margin-left: 8.33333333%; } .offset-sm-2 { margin-left: 16.66666667%; } .offset-sm-3 { margin-left: 25%; } .offset-sm-4 { margin-left: 33.33333333%; } .offset-sm-5 { margin-left: 41.66666667%; } .offset-sm-6 { margin-left: 50%; } .offset-sm-7 { margin-left: 58.33333333%; } .offset-sm-8 { margin-left: 66.66666667%; } .offset-sm-9 { margin-left: 75%; } .offset-sm-10 { margin-left: 83.33333333%; } .offset-sm-11 { margin-left: 91.66666667%; } } @media (min-width: 768px) { .col-md { -webkit-flex-basis: 0; -<API key>: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-md-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-md-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-md-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-md-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-md-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-md-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-md-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-md-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-md-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-md-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-md-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-md-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-md-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-md-0 { right: auto; } .pull-md-1 { right: 8.33333333%; } .pull-md-2 { right: 16.66666667%; } .pull-md-3 { right: 25%; } .pull-md-4 { right: 33.33333333%; } .pull-md-5 { right: 41.66666667%; } .pull-md-6 { right: 50%; } .pull-md-7 { right: 58.33333333%; } .pull-md-8 { right: 66.66666667%; } .pull-md-9 { right: 75%; } .pull-md-10 { right: 83.33333333%; } .pull-md-11 { right: 91.66666667%; } .pull-md-12 { right: 100%; } .push-md-0 { left: auto; } .push-md-1 { left: 8.33333333%; } .push-md-2 { left: 16.66666667%; } .push-md-3 { left: 25%; } .push-md-4 { left: 33.33333333%; } .push-md-5 { left: 41.66666667%; } .push-md-6 { left: 50%; } .push-md-7 { left: 58.33333333%; } .push-md-8 { left: 66.66666667%; } .push-md-9 { left: 75%; } .push-md-10 { left: 83.33333333%; } .push-md-11 { left: 91.66666667%; } .push-md-12 { left: 100%; } .offset-md-0 { margin-left: 0%; } .offset-md-1 { margin-left: 8.33333333%; } .offset-md-2 { margin-left: 16.66666667%; } .offset-md-3 { margin-left: 25%; } .offset-md-4 { margin-left: 33.33333333%; } .offset-md-5 { margin-left: 41.66666667%; } .offset-md-6 { margin-left: 50%; } .offset-md-7 { margin-left: 58.33333333%; } .offset-md-8 { margin-left: 66.66666667%; } .offset-md-9 { margin-left: 75%; } .offset-md-10 { margin-left: 83.33333333%; } .offset-md-11 { margin-left: 91.66666667%; } } @media (min-width: 992px) { .col-lg { -webkit-flex-basis: 0; -<API key>: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-lg-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-lg-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-lg-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-lg-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-lg-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-lg-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-lg-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-lg-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-lg-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-lg-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-lg-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-lg-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-lg-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-lg-0 { right: auto; } .pull-lg-1 { right: 8.33333333%; } .pull-lg-2 { right: 16.66666667%; } .pull-lg-3 { right: 25%; } .pull-lg-4 { right: 33.33333333%; } .pull-lg-5 { right: 41.66666667%; } .pull-lg-6 { right: 50%; } .pull-lg-7 { right: 58.33333333%; } .pull-lg-8 { right: 66.66666667%; } .pull-lg-9 { right: 75%; } .pull-lg-10 { right: 83.33333333%; } .pull-lg-11 { right: 91.66666667%; } .pull-lg-12 { right: 100%; } .push-lg-0 { left: auto; } .push-lg-1 { left: 8.33333333%; } .push-lg-2 { left: 16.66666667%; } .push-lg-3 { left: 25%; } .push-lg-4 { left: 33.33333333%; } .push-lg-5 { left: 41.66666667%; } .push-lg-6 { left: 50%; } .push-lg-7 { left: 58.33333333%; } .push-lg-8 { left: 66.66666667%; } .push-lg-9 { left: 75%; } .push-lg-10 { left: 83.33333333%; } .push-lg-11 { left: 91.66666667%; } .push-lg-12 { left: 100%; } .offset-lg-0 { margin-left: 0%; } .offset-lg-1 { margin-left: 8.33333333%; } .offset-lg-2 { margin-left: 16.66666667%; } .offset-lg-3 { margin-left: 25%; } .offset-lg-4 { margin-left: 33.33333333%; } .offset-lg-5 { margin-left: 41.66666667%; } .offset-lg-6 { margin-left: 50%; } .offset-lg-7 { margin-left: 58.33333333%; } .offset-lg-8 { margin-left: 66.66666667%; } .offset-lg-9 { margin-left: 75%; } .offset-lg-10 { margin-left: 83.33333333%; } .offset-lg-11 { margin-left: 91.66666667%; } } @media (min-width: 1200px) { .col-xl { -webkit-flex-basis: 0; -<API key>: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-xl-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-xl-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.33333333%; -ms-flex: 0 0 8.33333333%; flex: 0 0 8.33333333%; max-width: 8.33333333%; } .col-xl-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.66666667%; -ms-flex: 0 0 16.66666667%; flex: 0 0 16.66666667%; max-width: 16.66666667%; } .col-xl-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-xl-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.33333333%; -ms-flex: 0 0 33.33333333%; flex: 0 0 33.33333333%; max-width: 33.33333333%; } .col-xl-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.66666667%; -ms-flex: 0 0 41.66666667%; flex: 0 0 41.66666667%; max-width: 41.66666667%; } .col-xl-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-xl-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.33333333%; -ms-flex: 0 0 58.33333333%; flex: 0 0 58.33333333%; max-width: 58.33333333%; } .col-xl-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.66666667%; -ms-flex: 0 0 66.66666667%; flex: 0 0 66.66666667%; max-width: 66.66666667%; } .col-xl-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-xl-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.33333333%; -ms-flex: 0 0 83.33333333%; flex: 0 0 83.33333333%; max-width: 83.33333333%; } .col-xl-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.66666667%; -ms-flex: 0 0 91.66666667%; flex: 0 0 91.66666667%; max-width: 91.66666667%; } .col-xl-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-xl-0 { right: auto; } .pull-xl-1 { right: 8.33333333%; } .pull-xl-2 { right: 16.66666667%; } .pull-xl-3 { right: 25%; } .pull-xl-4 { right: 33.33333333%; } .pull-xl-5 { right: 41.66666667%; } .pull-xl-6 { right: 50%; } .pull-xl-7 { right: 58.33333333%; } .pull-xl-8 { right: 66.66666667%; } .pull-xl-9 { right: 75%; } .pull-xl-10 { right: 83.33333333%; } .pull-xl-11 { right: 91.66666667%; } .pull-xl-12 { right: 100%; } .push-xl-0 { left: auto; } .push-xl-1 { left: 8.33333333%; } .push-xl-2 { left: 16.66666667%; } .push-xl-3 { left: 25%; } .push-xl-4 { left: 33.33333333%; } .push-xl-5 { left: 41.66666667%; } .push-xl-6 { left: 50%; } .push-xl-7 { left: 58.33333333%; } .push-xl-8 { left: 66.66666667%; } .push-xl-9 { left: 75%; } .push-xl-10 { left: 83.33333333%; } .push-xl-11 { left: 91.66666667%; } .push-xl-12 { left: 100%; } .offset-xl-0 { margin-left: 0%; } .offset-xl-1 { margin-left: 8.33333333%; } .offset-xl-2 { margin-left: 16.66666667%; } .offset-xl-3 { margin-left: 25%; } .offset-xl-4 { margin-left: 33.33333333%; } .offset-xl-5 { margin-left: 41.66666667%; } .offset-xl-6 { margin-left: 50%; } .offset-xl-7 { margin-left: 58.33333333%; } .offset-xl-8 { margin-left: 66.66666667%; } .offset-xl-9 { margin-left: 75%; } .offset-xl-10 { margin-left: 83.33333333%; } .offset-xl-11 { margin-left: 91.66666667%; } } .table { width: 100%; max-width: 100%; margin-bottom: 1rem; } .table th, .table td { padding: 0.75rem; vertical-align: top; border-top: 1px solid #AEA79F; } .table thead th { vertical-align: bottom; border-bottom: 2px solid #AEA79F; } .table tbody + tbody { border-top: 2px solid #AEA79F; } .table .table { background-color: #fff; } .table-sm th, .table-sm td { padding: 0.3rem; } .table-bordered { border: 1px solid #AEA79F; } .table-bordered th, .table-bordered td { border: 1px solid #AEA79F; } .table-bordered thead th, .table-bordered thead td { border-bottom-width: 2px; } .table-striped tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); } .table-hover tbody tr:hover { background-color: rgba(0, 0, 0, 0.075); } .table-active, .table-active > th, .table-active > td { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover > td, .table-hover .table-active:hover > th { background-color: rgba(0, 0, 0, 0.075); } .table-success, .table-success > th, .table-success > td { background-color: #dff0d8; } .table-hover .table-success:hover { background-color: #d0e9c6; } .table-hover .table-success:hover > td, .table-hover .table-success:hover > th { background-color: #d0e9c6; } .table-info, .table-info > th, .table-info > td { background-color: #d9edf7; } .table-hover .table-info:hover { background-color: #c4e3f3; } .table-hover .table-info:hover > td, .table-hover .table-info:hover > th { background-color: #c4e3f3; } .table-warning, .table-warning > th, .table-warning > td { background-color: #fcf8e3; } .table-hover .table-warning:hover { background-color: #faf2cc; } .table-hover .table-warning:hover > td, .table-hover .table-warning:hover > th { background-color: #faf2cc; } .table-danger, .table-danger > th, .table-danger > td { background-color: #f2dede; } .table-hover .table-danger:hover { background-color: #ebcccc; } .table-hover .table-danger:hover > td, .table-hover .table-danger:hover > th { background-color: #ebcccc; } .thead-inverse th { color: #fff; background-color: #222; } .thead-default th { color: #333; background-color: #AEA79F; } .table-inverse { color: #fff; background-color: #222; } .table-inverse th, .table-inverse td, .table-inverse thead th { border-color: #fff; } .table-inverse.table-bordered { border: 0; } .table-responsive { display: block; width: 100%; overflow-x: auto; -ms-overflow-style: -<API key>; } .table-responsive.table-bordered { border: 0; } .form-control { display: block; width: 100%; padding: 0.5rem 0.75rem; font-size: 1rem; line-height: 1.25; color: #333; background-color: #fff; background-image: none; -<API key>: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -webkit-transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; -o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; } .form-control::-ms-expand { background-color: transparent; border: 0; } .form-control:focus { color: #333; background-color: #fff; border-color: #f4ad94; outline: none; } .form-control::-<API key> { color: #777; opacity: 1; } .form-control::-moz-placeholder { color: #777; opacity: 1; } .form-control:-<API key> { color: #777; opacity: 1; } .form-control::placeholder { color: #777; opacity: 1; } .form-control:disabled, .form-control[readonly] { background-color: #eee; opacity: 1; } .form-control:disabled { cursor: not-allowed; } select.form-control:not([size]):not([multiple]) { height: calc(2.25rem + 2px); } select.form-control:focus::-ms-value { color: #333; background-color: #fff; } .form-control-file, .form-control-range { display: block; } .col-form-label { padding-top: calc(0.5rem - 1px * 2); padding-bottom: calc(0.5rem - 1px * 2); margin-bottom: 0; } .col-form-label-lg { padding-top: calc(0.75rem - 1px * 2); padding-bottom: calc(0.75rem - 1px * 2); font-size: 1.25rem; } .col-form-label-sm { padding-top: calc(0.25rem - 1px * 2); padding-bottom: calc(0.25rem - 1px * 2); font-size: 0.875rem; } .col-form-legend { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; font-size: 1rem; } .form-control-static { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; line-height: 1.25; border: solid transparent; border-width: 1px 0; } .form-control-static.form-control-sm, .input-group-sm > .form-control-static.form-control, .input-group-sm > .form-control-static.input-group-addon, .input-group-sm > .input-group-btn > .form-control-static.btn, .form-control-static.form-control-lg, .input-group-lg > .form-control-static.form-control, .input-group-lg > .form-control-static.input-group-addon, .input-group-lg > .input-group-btn > .form-control-static.btn { padding-right: 0; padding-left: 0; } .form-control-sm, .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } select.form-control-sm:not([size]):not([multiple]), .input-group-sm > select.form-control:not([size]):not([multiple]), .input-group-sm > select.input-group-addon:not([size]):not([multiple]), .input-group-sm > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 1.8125rem; } .form-control-lg, .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } select.form-control-lg:not([size]):not([multiple]), .input-group-lg > select.form-control:not([size]):not([multiple]), .input-group-lg > select.input-group-addon:not([size]):not([multiple]), .input-group-lg > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 3.16666667rem; } .form-group { margin-bottom: 1rem; } .form-text { display: block; margin-top: 0.25rem; } .form-check { position: relative; display: block; margin-bottom: 0.5rem; } .form-check.disabled .form-check-label { color: #777; cursor: not-allowed; } .form-check-label { padding-left: 1.25rem; margin-bottom: 0; cursor: pointer; } .form-check-input { position: absolute; margin-top: 0.25rem; margin-left: -1.25rem; } .form-check-input:only-child { position: static; } .form-check-inline { display: inline-block; } .form-check-inline .form-check-label { vertical-align: middle; } .form-check-inline + .form-check-inline { margin-left: 0.75rem; } .<API key> { margin-top: 0.25rem; } .<API key>, .<API key>, .form-control-danger { padding-right: 2.25rem; background-repeat: no-repeat; background-position: center right 0.5625rem; -<API key>: 1.125rem 1.125rem; background-size: 1.125rem 1.125rem; } .has-success .<API key>, .has-success .form-control-label, .has-success .col-form-label, .has-success .form-check-label, .has-success .custom-control { color: #38B44A; } .has-success .form-control { border-color: #38B44A; } .has-success .input-group-addon { color: #38B44A; border-color: #38B44A; background-color: #caeecf; } .has-success .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .has-warning .<API key>, .has-warning .form-control-label, .has-warning .col-form-label, .has-warning .form-check-label, .has-warning .custom-control { color: #EFB73E; } .has-warning .form-control { border-color: #EFB73E; } .has-warning .input-group-addon { color: #EFB73E; border-color: #EFB73E; background-color: #fffdfa; } .has-warning .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .has-danger .<API key>, .has-danger .form-control-label, .has-danger .col-form-label, .has-danger .form-check-label, .has-danger .custom-control { color: #DF382C; } .has-danger .form-control { border-color: #DF382C; } .has-danger .input-group-addon { color: #DF382C; border-color: #DF382C; background-color: #fadfdd; } .has-danger .form-control-danger { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .form-inline { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .form-inline .form-check { width: 100%; } @media (min-width: 576px) { .form-inline label { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; margin-bottom: 0; } .form-inline .form-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; margin-bottom: 0; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-inline .form-control-static { display: inline-block; } .form-inline .input-group { width: auto; } .form-inline .form-control-label { margin-bottom: 0; vertical-align: middle; } .form-inline .form-check { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; width: auto; margin-top: 0; margin-bottom: 0; } .form-inline .form-check-label { padding-left: 0; } .form-inline .form-check-input { position: relative; margin-top: 0; margin-right: 0.25rem; margin-left: 0; } .form-inline .custom-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; } .form-inline .<API key> { position: static; display: inline-block; margin-right: 0.25rem; vertical-align: text-bottom; } .form-inline .has-feedback .<API key> { top: 0; } } .btn { display: inline-block; font-weight: normal; line-height: 1.25; text-align: center; white-space: nowrap; vertical-align: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; border: 1px solid transparent; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .btn:focus, .btn:hover { text-decoration: none; } .btn:focus, .btn.focus { outline: 0; -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.25); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.25); } .btn.disabled, .btn:disabled { cursor: not-allowed; opacity: .65; } .btn:active, .btn.active { background-image: none; } a.btn.disabled, fieldset[disabled] a.btn { pointer-events: none; } .btn-primary { color: #fff; background-color: #E95420; border-color: #E95420; } .btn-primary:hover { color: #fff; background-color: #c34113; border-color: #b93e12; } .btn-primary:focus, .btn-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); } .btn-primary.disabled, .btn-primary:disabled { background-color: #E95420; border-color: #E95420; } .btn-primary:active, .btn-primary.active, .show > .btn-primary.dropdown-toggle { color: #fff; background-color: #c34113; background-image: none; border-color: #b93e12; } .btn-secondary { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .btn-secondary:hover { color: #fff; background-color: #978e83; border-color: #92897e; } .btn-secondary:focus, .btn-secondary.focus { -webkit-box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); } .btn-secondary.disabled, .btn-secondary:disabled { background-color: #AEA79F; border-color: #AEA79F; } .btn-secondary:active, .btn-secondary.active, .show > .btn-secondary.dropdown-toggle { color: #fff; background-color: #978e83; background-image: none; border-color: #92897e; } .btn-info { color: #fff; background-color: #772953; border-color: #772953; } .btn-info:hover { color: #fff; background-color: #511c39; border-color: #491933; } .btn-info:focus, .btn-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); } .btn-info.disabled, .btn-info:disabled { background-color: #772953; border-color: #772953; } .btn-info:active, .btn-info.active, .show > .btn-info.dropdown-toggle { color: #fff; background-color: #511c39; background-image: none; border-color: #491933; } .btn-success { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-success:hover { color: #fff; background-color: #2c8d3a; border-color: #298537; } .btn-success:focus, .btn-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); } .btn-success.disabled, .btn-success:disabled { background-color: #38B44A; border-color: #38B44A; } .btn-success:active, .btn-success.active, .show > .btn-success.dropdown-toggle { color: #fff; background-color: #2c8d3a; background-image: none; border-color: #298537; } .btn-warning { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-warning:hover { color: #fff; background-color: #e7a413; border-color: #dd9d12; } .btn-warning:focus, .btn-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); } .btn-warning.disabled, .btn-warning:disabled { background-color: #EFB73E; border-color: #EFB73E; } .btn-warning:active, .btn-warning.active, .show > .btn-warning.dropdown-toggle { color: #fff; background-color: #e7a413; background-image: none; border-color: #dd9d12; } .btn-danger { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-danger:hover { color: #fff; background-color: #bc271c; border-color: #b3251b; } .btn-danger:focus, .btn-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); } .btn-danger.disabled, .btn-danger:disabled { background-color: #DF382C; border-color: #DF382C; } .btn-danger:active, .btn-danger.active, .show > .btn-danger.dropdown-toggle { color: #fff; background-color: #bc271c; background-image: none; border-color: #b3251b; } .btn-outline-primary { color: #E95420; background-image: none; background-color: transparent; border-color: #E95420; } .btn-outline-primary:hover { color: #fff; background-color: #E95420; border-color: #E95420; } .btn-outline-primary:focus, .btn-outline-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); box-shadow: 0 0 0 2px rgba(233, 84, 32, 0.5); } .btn-outline-primary.disabled, .btn-outline-primary:disabled { color: #E95420; background-color: transparent; } .btn-outline-primary:active, .btn-outline-primary.active, .show > .btn-outline-primary.dropdown-toggle { color: #fff; background-color: #E95420; border-color: #E95420; } .<API key> { color: #AEA79F; background-image: none; background-color: transparent; border-color: #AEA79F; } .<API key>:hover { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .<API key>:focus, .<API key>.focus { -webkit-box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); box-shadow: 0 0 0 2px rgba(174, 167, 159, 0.5); } .<API key>.disabled, .<API key>:disabled { color: #AEA79F; background-color: transparent; } .<API key>:active, .<API key>.active, .show > .<API key>.dropdown-toggle { color: #fff; background-color: #AEA79F; border-color: #AEA79F; } .btn-outline-info { color: #772953; background-image: none; background-color: transparent; border-color: #772953; } .btn-outline-info:hover { color: #fff; background-color: #772953; border-color: #772953; } .btn-outline-info:focus, .btn-outline-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); box-shadow: 0 0 0 2px rgba(119, 41, 83, 0.5); } .btn-outline-info.disabled, .btn-outline-info:disabled { color: #772953; background-color: transparent; } .btn-outline-info:active, .btn-outline-info.active, .show > .btn-outline-info.dropdown-toggle { color: #fff; background-color: #772953; border-color: #772953; } .btn-outline-success { color: #38B44A; background-image: none; background-color: transparent; border-color: #38B44A; } .btn-outline-success:hover { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-outline-success:focus, .btn-outline-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); box-shadow: 0 0 0 2px rgba(56, 180, 74, 0.5); } .btn-outline-success.disabled, .btn-outline-success:disabled { color: #38B44A; background-color: transparent; } .btn-outline-success:active, .btn-outline-success.active, .show > .btn-outline-success.dropdown-toggle { color: #fff; background-color: #38B44A; border-color: #38B44A; } .btn-outline-warning { color: #EFB73E; background-image: none; background-color: transparent; border-color: #EFB73E; } .btn-outline-warning:hover { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-outline-warning:focus, .btn-outline-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); box-shadow: 0 0 0 2px rgba(239, 183, 62, 0.5); } .btn-outline-warning.disabled, .btn-outline-warning:disabled { color: #EFB73E; background-color: transparent; } .btn-outline-warning:active, .btn-outline-warning.active, .show > .btn-outline-warning.dropdown-toggle { color: #fff; background-color: #EFB73E; border-color: #EFB73E; } .btn-outline-danger { color: #DF382C; background-image: none; background-color: transparent; border-color: #DF382C; } .btn-outline-danger:hover { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-outline-danger:focus, .btn-outline-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); box-shadow: 0 0 0 2px rgba(223, 56, 44, 0.5); } .btn-outline-danger.disabled, .btn-outline-danger:disabled { color: #DF382C; background-color: transparent; } .btn-outline-danger:active, .btn-outline-danger.active, .show > .btn-outline-danger.dropdown-toggle { color: #fff; background-color: #DF382C; border-color: #DF382C; } .btn-link { font-weight: normal; color: #E95420; border-radius: 0; } .btn-link, .btn-link:active, .btn-link.active, .btn-link:disabled { background-color: transparent; } .btn-link, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover { border-color: transparent; } .btn-link:focus, .btn-link:hover { color: #ac3911; text-decoration: underline; background-color: transparent; } .btn-link:disabled { color: #777; } .btn-link:disabled:focus, .btn-link:disabled:hover { text-decoration: none; } .btn-lg, .btn-group-lg > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .btn-sm, .btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .btn-block { display: block; width: 100%; } .btn-block + .btn-block { margin-top: 0.5rem; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.show { opacity: 1; } .collapse { display: none; } .collapse.show { display: block; } tr.collapse.show { display: table-row; } tbody.collapse.show { display: table-row-group; } .collapsing { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; -o-transition: height 0.35s ease; transition: height 0.35s ease; } .dropup, .dropdown { position: relative; } .dropdown-toggle::after { display: inline-block; width: 0; height: 0; margin-left: 0.3em; vertical-align: middle; content: ""; border-top: 0.3em solid; border-right: 0.3em solid transparent; border-left: 0.3em solid transparent; } .dropdown-toggle:focus { outline: 0; } .dropup .dropdown-toggle::after { border-top: 0; border-bottom: 0.3em solid; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 10rem; padding: 0.5rem 0; margin: 0.125rem 0 0; font-size: 1rem; color: #333; text-align: left; list-style: none; background-color: #fff; -<API key>: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .dropdown-divider { height: 1px; margin: 0.5rem 0; overflow: hidden; background-color: #AEA79F; } .dropdown-item { display: block; width: 100%; padding: 3px 1.5rem; clear: both; font-weight: normal; color: #222; text-align: inherit; white-space: nowrap; background: none; border: 0; } .dropdown-item:focus, .dropdown-item:hover { color: #151515; text-decoration: none; background-color: #eee; } .dropdown-item.active, .dropdown-item:active { color: #fff; text-decoration: none; background-color: #E95420; } .dropdown-item.disabled, .dropdown-item:disabled { color: #777; cursor: not-allowed; background-color: transparent; } .show > .dropdown-menu { display: block; } .show > a { outline: 0; } .dropdown-menu-right { right: 0; left: auto; } .dropdown-menu-left { right: auto; left: 0; } .dropdown-header { display: block; padding: 0.5rem 1.5rem; margin-bottom: 0; font-size: 0.875rem; color: #777; white-space: nowrap; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .dropup .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 0.125rem; } .btn-group, .btn-group-vertical { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; -webkit-box-flex: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover { z-index: 2; } .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn:focus, .btn-group-vertical > .btn:active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group, .btn-group-vertical .btn + .btn, .btn-group-vertical .btn + .btn-group, .btn-group-vertical .btn-group + .btn, .btn-group-vertical .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -<API key>: flex-start; -ms-flex-pack: start; justify-content: flex-start; } .btn-toolbar .input-group { width: auto; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { <API key>: 0; <API key>: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { <API key>: 0; <API key>: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { <API key>: 0; <API key>: 0; } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { <API key>: 0; <API key>: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn + .<API key> { padding-right: 0.75rem; padding-left: 0.75rem; } .btn + .<API key>::after { margin-left: 0; } .btn-sm + .<API key>, .btn-group-sm > .btn + .<API key> { padding-right: 0.375rem; padding-left: 0.375rem; } .btn-lg + .<API key>, .btn-group-lg > .btn + .<API key> { padding-right: 1.125rem; padding-left: 1.125rem; } .btn-group-vertical { display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; } .btn-group-vertical .btn, .btn-group-vertical .btn-group { width: 100%; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { <API key>: 0; <API key>: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { <API key>: 0; <API key>: 0; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { <API key>: 0; <API key>: 0; } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { <API key>: 0; <API key>: 0; } [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; } .input-group { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; width: 100%; } .input-group .form-control { position: relative; z-index: 2; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } .input-group .form-control:focus, .input-group .form-control:active, .input-group .form-control:hover { z-index: 3; } .input-group-addon, .input-group-btn, .input-group .form-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 0.5rem 0.75rem; margin-bottom: 0; font-size: 1rem; font-weight: normal; line-height: 1.25; color: #333; text-align: center; background-color: #eee; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .input-group-addon.form-control-sm, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .input-group-addon.btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .input-group-addon.form-control-lg, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .input-group-addon.btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:not(:last-child), .input-group-addon:not(:last-child), .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group > .btn, .input-group-btn:not(:last-child) > .dropdown-toggle, .input-group-btn:not(:first-child) > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:not(:first-child) > .btn-group:not(:last-child) > .btn { <API key>: 0; <API key>: 0; } .input-group-addon:not(:last-child) { border-right: 0; } .input-group .form-control:not(:first-child), .input-group-addon:not(:first-child), .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group > .btn, .input-group-btn:not(:first-child) > .dropdown-toggle, .input-group-btn:not(:last-child) > .btn:not(:first-child), .input-group-btn:not(:last-child) > .btn-group:not(:first-child) > .btn { <API key>: 0; <API key>: 0; } .form-control + .input-group-addon:not(:first-child) { border-left: 0; } .input-group-btn { position: relative; font-size: 0; white-space: nowrap; } .input-group-btn > .btn { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .input-group-btn > .btn + .btn { margin-left: -1px; } .input-group-btn > .btn:focus, .input-group-btn > .btn:active, .input-group-btn > .btn:hover { z-index: 3; } .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group { margin-right: -1px; } .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group { z-index: 2; margin-left: -1px; } .input-group-btn:not(:first-child) > .btn:focus, .input-group-btn:not(:first-child) > .btn:active, .input-group-btn:not(:first-child) > .btn:hover, .input-group-btn:not(:first-child) > .btn-group:focus, .input-group-btn:not(:first-child) > .btn-group:active, .input-group-btn:not(:first-child) > .btn-group:hover { z-index: 3; } .custom-control { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; min-height: 1.5rem; padding-left: 1.5rem; margin-right: 1rem; cursor: pointer; } .<API key> { position: absolute; z-index: -1; opacity: 0; } .<API key>:checked ~ .<API key> { color: #fff; background-color: #E95420; } .<API key>:focus ~ .<API key> { -webkit-box-shadow: 0 0 0 1px #fff, 0 0 0 3px #E95420; box-shadow: 0 0 0 1px #fff, 0 0 0 3px #E95420; } .<API key>:active ~ .<API key> { color: #fff; background-color: #f9d1c2; } .<API key>:disabled ~ .<API key> { cursor: not-allowed; background-color: #AEA79F; } .<API key>:disabled ~ .<API key> { color: #777; cursor: not-allowed; } .<API key> { position: absolute; top: 0.25rem; left: 0; display: block; width: 1rem; height: 1rem; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #ddd; background-repeat: no-repeat; background-position: center center; -<API key>: 50% 50%; background-size: 50% 50%; } .custom-checkbox .<API key> { border-radius: 0.25rem; } .custom-checkbox .<API key>:checked ~ .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .custom-checkbox .<API key>:indeterminate ~ .<API key> { background-color: #E95420; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .custom-radio .<API key> { border-radius: 50%; } .custom-radio .<API key>:checked ~ .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .<API key> { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; } .<API key> .custom-control { margin-bottom: 0.25rem; } .<API key> .custom-control + .custom-control { margin-left: 0; } .custom-select { display: inline-block; max-width: 100%; height: calc(2.25rem + 2px); padding: 0.375rem 1.75rem 0.375rem 0.75rem; line-height: 1.25; color: #333; vertical-align: middle; background: -<API key>: 8px 10px; background-size: 8px 10px; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -moz-appearance: none; -webkit-appearance: none; } .custom-select:focus { border-color: #f4ad94; outline: none; } .custom-select:focus::-ms-value { color: #333; background-color: #fff; } .custom-select:disabled { color: #777; cursor: not-allowed; background-color: #AEA79F; } .custom-select::-ms-expand { opacity: 0; } .custom-select-sm { padding-top: 0.375rem; padding-bottom: 0.375rem; font-size: 75%; } .custom-file { position: relative; display: inline-block; max-width: 100%; height: 2.5rem; margin-bottom: 0; cursor: pointer; } .custom-file-input { min-width: 14rem; max-width: 100%; height: 2.5rem; margin: 0; filter: alpha(opacity=0); opacity: 0; } .custom-file-control { position: absolute; top: 0; right: 0; left: 0; z-index: 5; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #333; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .custom-file-control:lang(en)::after { content: "Choose file..."; } .custom-file-control::before { position: absolute; top: -1px; right: -1px; bottom: -1px; z-index: 6; display: block; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #333; background-color: #AEA79F; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0 0.25rem 0.25rem 0; } .custom-file-control:lang(en)::before { content: "Browse"; } .nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; margin-bottom: 0; list-style: none; } .nav-link { display: block; padding: 0.5em 1em; } .nav-link:focus, .nav-link:hover { text-decoration: none; } .nav-link.disabled { color: #777; cursor: not-allowed; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs .nav-item { margin-bottom: -1px; } .nav-tabs .nav-link { border: 1px solid transparent; <API key>: 0.25rem; <API key>: 0.25rem; } .nav-tabs .nav-link:focus, .nav-tabs .nav-link:hover { border-color: #AEA79F #AEA79F #ddd; } .nav-tabs .nav-link.disabled { color: #777; background-color: transparent; border-color: transparent; } .nav-tabs .nav-link.active, .nav-tabs .nav-item.show .nav-link { color: #333; background-color: #fff; border-color: #ddd #ddd #fff; } .nav-tabs .dropdown-menu { margin-top: -1px; <API key>: 0; <API key>: 0; } .nav-pills .nav-link { border-radius: 0.25rem; } .nav-pills .nav-link.active, .nav-pills .nav-item.show .nav-link { color: #fff; cursor: default; background-color: #E95420; } .nav-fill .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; text-align: center; } .nav-justified .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 100%; -ms-flex: 1 1 100%; flex: 1 1 100%; text-align: center; } .tab-content > .tab-pane { display: none; } .tab-content > .active { display: block; } .navbar { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; padding: 0.5rem 1rem; } .navbar-brand { display: inline-block; padding-top: .25rem; padding-bottom: .25rem; margin-right: 1rem; font-size: 1.25rem; line-height: inherit; white-space: nowrap; } .navbar-brand:focus, .navbar-brand:hover { text-decoration: none; } .navbar-nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; list-style: none; } .navbar-nav .nav-link { padding-right: 0; padding-left: 0; } .navbar-text { display: inline-block; padding-top: .425rem; padding-bottom: .425rem; } .navbar-toggler { -webkit-align-self: flex-start; -ms-flex-item-align: start; align-self: flex-start; padding: 0.25rem 0.75rem; font-size: 1.25rem; line-height: 1; background: transparent; border: 1px solid transparent; border-radius: 0.25rem; } .navbar-toggler:focus, .navbar-toggler:hover { text-decoration: none; } .navbar-toggler-icon { display: inline-block; width: 1.5em; height: 1.5em; vertical-align: middle; content: ""; background: no-repeat center center; -<API key>: 100% 100%; background-size: 100% 100%; } .navbar-toggler-left { position: absolute; left: 1rem; } .<API key> { position: absolute; right: 1rem; } @media (max-width: 575px) { .navbar-toggleable .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 576px) { .navbar-toggleable { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-nav { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable .navbar-toggler { display: none; } } @media (max-width: 767px) { .<API key> .navbar-nav .dropdown-menu { position: static; float: none; } .<API key> > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 768px) { .<API key> { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-nav { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; } .<API key> .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .<API key> > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .<API key> .navbar-toggler { display: none; } } @media (max-width: 991px) { .<API key> .navbar-nav .dropdown-menu { position: static; float: none; } .<API key> > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 992px) { .<API key> { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-nav { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; } .<API key> .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .<API key> > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .<API key> .navbar-toggler { display: none; } } @media (max-width: 1199px) { .<API key> .navbar-nav .dropdown-menu { position: static; float: none; } .<API key> > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 1200px) { .<API key> { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-nav { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; } .<API key> .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .<API key> > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .<API key> .navbar-toggler { display: none; } } .<API key> { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-nav .dropdown-menu { position: static; float: none; } .<API key> > .container { padding-right: 0; padding-left: 0; } .<API key> .navbar-nav { -webkit-box-orient: horizontal; -<API key>: normal; -<API key>: row; -ms-flex-direction: row; flex-direction: row; } .<API key> .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .<API key> > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .<API key> .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .<API key> .navbar-toggler { display: none; } .navbar-light .navbar-brand, .navbar-light .navbar-toggler { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-brand:focus, .navbar-light .navbar-brand:hover, .navbar-light .navbar-toggler:focus, .navbar-light .navbar-toggler:hover { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-nav .nav-link { color: rgba(0, 0, 0, 0.5); } .navbar-light .navbar-nav .nav-link:focus, .navbar-light .navbar-nav .nav-link:hover { color: rgba(0, 0, 0, 0.7); } .navbar-light .navbar-nav .nav-link.disabled { color: rgba(0, 0, 0, 0.3); } .navbar-light .navbar-nav .open > .nav-link, .navbar-light .navbar-nav .active > .nav-link, .navbar-light .navbar-nav .nav-link.open, .navbar-light .navbar-nav .nav-link.active { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-toggler { border-color: rgba(0, 0, 0, 0.1); } .navbar-light .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http: } .navbar-light .navbar-text { color: rgba(0, 0, 0, 0.5); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-toggler { color: white; } .navbar-inverse .navbar-brand:focus, .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-toggler:focus, .navbar-inverse .navbar-toggler:hover { color: white; } .navbar-inverse .navbar-nav .nav-link { color: rgba(255, 255, 255, 0.75); } .navbar-inverse .navbar-nav .nav-link:focus, .navbar-inverse .navbar-nav .nav-link:hover { color: white; } .navbar-inverse .navbar-nav .nav-link.disabled { color: rgba(255, 255, 255, 0.25); } .navbar-inverse .navbar-nav .open > .nav-link, .navbar-inverse .navbar-nav .active > .nav-link, .navbar-inverse .navbar-nav .nav-link.open, .navbar-inverse .navbar-nav .nav-link.active { color: white; } .navbar-inverse .navbar-toggler { border-color: rgba(255, 255, 255, 0.1); } .navbar-inverse .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http: } .navbar-inverse .navbar-text { color: rgba(255, 255, 255, 0.75); } .card { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); border-radius: 0.25rem; } .card-block { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 1.25rem; } .card-title { margin-bottom: 0.75rem; } .card-subtitle { margin-top: -0.375rem; margin-bottom: 0; } .card-text:last-child { margin-bottom: 0; } .card-link:hover { text-decoration: none; } .card-link + .card-link { margin-left: 1.25rem; } .card > .list-group:first-child .list-group-item:first-child { <API key>: 0.25rem; <API key>: 0.25rem; } .card > .list-group:last-child .list-group-item:last-child { <API key>: 0.25rem; <API key>: 0.25rem; } .card-header { padding: 0.75rem 1.25rem; margin-bottom: 0; background-color: #eee; border-bottom: 1px solid rgba(0, 0, 0, 0.125); } .card-header:first-child { border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0; } .card-footer { padding: 0.75rem 1.25rem; background-color: #eee; border-top: 1px solid rgba(0, 0, 0, 0.125); } .card-footer:last-child { border-radius: 0 0 calc(0.25rem - 1px) calc(0.25rem - 1px); } .card-header-tabs { margin-right: -0.625rem; margin-bottom: -0.75rem; margin-left: -0.625rem; border-bottom: 0; } .card-header-pills { margin-right: -0.625rem; margin-left: -0.625rem; } .card-primary { background-color: #E95420; border-color: #E95420; } .card-primary .card-header, .card-primary .card-footer { background-color: transparent; } .card-success { background-color: #38B44A; border-color: #38B44A; } .card-success .card-header, .card-success .card-footer { background-color: transparent; } .card-info { background-color: #772953; border-color: #772953; } .card-info .card-header, .card-info .card-footer { background-color: transparent; } .card-warning { background-color: #EFB73E; border-color: #EFB73E; } .card-warning .card-header, .card-warning .card-footer { background-color: transparent; } .card-danger { background-color: #DF382C; border-color: #DF382C; } .card-danger .card-header, .card-danger .card-footer { background-color: transparent; } .<API key> { background-color: transparent; border-color: #E95420; } .<API key> { background-color: transparent; border-color: #AEA79F; } .card-outline-info { background-color: transparent; border-color: #772953; } .<API key> { background-color: transparent; border-color: #38B44A; } .<API key> { background-color: transparent; border-color: #EFB73E; } .card-outline-danger { background-color: transparent; border-color: #DF382C; } .card-inverse { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-header, .card-inverse .card-footer { background-color: transparent; border-color: rgba(255, 255, 255, 0.2); } .card-inverse .card-header, .card-inverse .card-footer, .card-inverse .card-title, .card-inverse .card-blockquote { color: #fff; } .card-inverse .card-link, .card-inverse .card-text, .card-inverse .card-subtitle, .card-inverse .card-blockquote .blockquote-footer { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-link:focus, .card-inverse .card-link:hover { color: #fff; } .card-blockquote { padding: 0; margin-bottom: 0; border-left: 0; } .card-img { border-radius: calc(0.25rem - 1px); } .card-img-overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; padding: 1.25rem; } .card-img-top { <API key>: calc(0.25rem - 1px); <API key>: calc(0.25rem - 1px); } .card-img-bottom { <API key>: calc(0.25rem - 1px); <API key>: calc(0.25rem - 1px); } @media (min-width: 576px) { .card-deck { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-deck .card { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; } .card-deck .card:not(:first-child) { margin-left: 15px; } .card-deck .card:not(:last-child) { margin-right: 15px; } } @media (min-width: 576px) { .card-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-group .card { -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; } .card-group .card + .card { margin-left: 0; border-left: 0; } .card-group .card:first-child { <API key>: 0; <API key>: 0; } .card-group .card:first-child .card-img-top { <API key>: 0; } .card-group .card:first-child .card-img-bottom { <API key>: 0; } .card-group .card:last-child { <API key>: 0; <API key>: 0; } .card-group .card:last-child .card-img-top { <API key>: 0; } .card-group .card:last-child .card-img-bottom { <API key>: 0; } .card-group .card:not(:first-child):not(:last-child) { border-radius: 0; } .card-group .card:not(:first-child):not(:last-child) .card-img-top, .card-group .card:not(:first-child):not(:last-child) .card-img-bottom { border-radius: 0; } } @media (min-width: 576px) { .card-columns { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 1.25rem; -moz-column-gap: 1.25rem; column-gap: 1.25rem; } .card-columns .card { display: inline-block; width: 100%; margin-bottom: 0.75rem; } } .breadcrumb { padding: 0.75rem 1rem; margin-bottom: 1rem; list-style: none; background-color: #eee; border-radius: 0.25rem; } .breadcrumb::after { display: block; content: ""; clear: both; } .breadcrumb-item { float: left; } .breadcrumb-item + .breadcrumb-item::before { display: inline-block; padding-right: 0.5rem; padding-left: 0.5rem; color: #777; content: "/"; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: underline; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: none; } .breadcrumb-item.active { color: #777; } .pagination { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; list-style: none; border-radius: 0.25rem; } .page-item:first-child .page-link { margin-left: 0; <API key>: 0.25rem; <API key>: 0.25rem; } .page-item:last-child .page-link { <API key>: 0.25rem; <API key>: 0.25rem; } .page-item.active .page-link { z-index: 2; color: #fff; background-color: #E95420; border-color: #E95420; } .page-item.disabled .page-link { color: #777; pointer-events: none; cursor: not-allowed; background-color: #fff; border-color: #ddd; } .page-link { position: relative; display: block; padding: 0.5rem 0.75rem; margin-left: -1px; line-height: 1.25; color: #E95420; background-color: #fff; border: 1px solid #ddd; } .page-link:focus, .page-link:hover { color: #ac3911; text-decoration: none; background-color: #AEA79F; border-color: #ddd; } .pagination-lg .page-link { padding: 0.75rem 1.5rem; font-size: 1.25rem; } .pagination-lg .page-item:first-child .page-link { <API key>: 0.3rem; <API key>: 0.3rem; } .pagination-lg .page-item:last-child .page-link { <API key>: 0.3rem; <API key>: 0.3rem; } .pagination-sm .page-link { padding: 0.25rem 0.5rem; font-size: 0.875rem; } .pagination-sm .page-item:first-child .page-link { <API key>: 0.2rem; <API key>: 0.2rem; } .pagination-sm .page-item:last-child .page-link { <API key>: 0.2rem; <API key>: 0.2rem; } .badge { display: inline-block; padding: 0.25em 0.4em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: 0.25rem; } .badge:empty { display: none; } .btn .badge { position: relative; top: -1px; } a.badge:focus, a.badge:hover { color: #fff; text-decoration: none; cursor: pointer; } .badge-pill { padding-right: 0.6em; padding-left: 0.6em; border-radius: 10rem; } .badge-default { background-color: #777; } .badge-default[href]:focus, .badge-default[href]:hover { background-color: #5e5e5e; } .badge-primary { background-color: #E95420; } .badge-primary[href]:focus, .badge-primary[href]:hover { background-color: #c34113; } .badge-success { background-color: #38B44A; } .badge-success[href]:focus, .badge-success[href]:hover { background-color: #2c8d3a; } .badge-info { background-color: #772953; } .badge-info[href]:focus, .badge-info[href]:hover { background-color: #511c39; } .badge-warning { background-color: #EFB73E; } .badge-warning[href]:focus, .badge-warning[href]:hover { background-color: #e7a413; } .badge-danger { background-color: #DF382C; } .badge-danger[href]:focus, .badge-danger[href]:hover { background-color: #bc271c; } .jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #eee; border-radius: 0.3rem; } @media (min-width: 576px) { .jumbotron { padding: 4rem 2rem; } } .jumbotron-hr { border-top-color: #d5d5d5; } .jumbotron-fluid { padding-right: 0; padding-left: 0; border-radius: 0; } .alert { padding: 0.75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: 0.25rem; } .alert-heading { color: inherit; } .alert-link { font-weight: bold; } .alert-dismissible .close { position: relative; top: -0.75rem; right: -1.25rem; padding: 0.75rem 1.25rem; color: inherit; } .alert-success { background-color: #dff0d8; border-color: #d0e9c6; color: #3c763d; } .alert-success hr { border-top-color: #c1e2b3; } .alert-success .alert-link { color: #2b542c; } .alert-info { background-color: #d9edf7; border-color: #bcdff1; color: #31708f; } .alert-info hr { border-top-color: #a6d5ec; } .alert-info .alert-link { color: #245269; } .alert-warning { background-color: #fcf8e3; border-color: #faf2cc; color: #8a6d3b; } .alert-warning hr { border-top-color: #f7ecb5; } .alert-warning .alert-link { color: #66512c; } .alert-danger { background-color: #f2dede; border-color: #ebcccc; color: #a94442; } .alert-danger hr { border-top-color: #e4b9b9; } .alert-danger .alert-link { color: #843534; } @-webkit-keyframes <API key> { from { background-position: 1rem 0; } to { background-position: 0 0; } } @-o-keyframes <API key> { from { background-position: 1rem 0; } to { background-position: 0 0; } } @keyframes <API key> { from { background-position: 1rem 0; } to { background-position: 0 0; } } .progress { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; overflow: hidden; font-size: 0.75rem; line-height: 1rem; text-align: center; background-color: #AEA79F; border-radius: 0.25rem; } .progress-bar { height: 1rem; color: #E95420; background-color: #E95420; } .<API key> { background-image: -<API key>(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -<API key>: 1rem 1rem; background-size: 1rem 1rem; } .<API key> { -webkit-animation: <API key> 1s linear infinite; -o-animation: <API key> 1s linear infinite; animation: <API key> 1s linear infinite; } .media { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; } .media-body { -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .list-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; } .<API key> { width: 100%; color: #333; text-align: inherit; } .<API key> .<API key> { color: #222; } .<API key>:focus, .<API key>:hover { color: #333; text-decoration: none; background-color: #eee; } .<API key>:active { color: #333; background-color: #AEA79F; } .list-group-item { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; padding: 0.75rem 1.25rem; margin-bottom: -1px; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); } .list-group-item:first-child { <API key>: 0.25rem; <API key>: 0.25rem; } .list-group-item:last-child { margin-bottom: 0; <API key>: 0.25rem; <API key>: 0.25rem; } .list-group-item:focus, .list-group-item:hover { text-decoration: none; } .list-group-item.disabled, .list-group-item:disabled { color: #777; cursor: not-allowed; background-color: #eee; } .list-group-item.disabled .<API key>, .list-group-item:disabled .<API key> { color: inherit; } .list-group-item.disabled .<API key>, .list-group-item:disabled .<API key> { color: #777; } .list-group-item.active { z-index: 2; color: #fff; background-color: #E95420; border-color: #E95420; } .list-group-item.active .<API key>, .list-group-item.active .<API key> > small, .list-group-item.active .<API key> > .small { color: inherit; } .list-group-item.active .<API key> { color: white; } .list-group-flush .list-group-item { border-right: 0; border-left: 0; border-radius: 0; } .list-group-flush:first-child .list-group-item:first-child { border-top: 0; } .list-group-flush:last-child .list-group-item:last-child { border-bottom: 0; } .<API key> { color: #3c763d; background-color: #dff0d8; } a.<API key>, button.<API key> { color: #3c763d; } a.<API key> .<API key>, button.<API key> .<API key> { color: inherit; } a.<API key>:focus, a.<API key>:hover, button.<API key>:focus, button.<API key>:hover { color: #3c763d; background-color: #d0e9c6; } a.<API key>.active, button.<API key>.active { color: #fff; background-color: #3c763d; border-color: #3c763d; } .<API key> { color: #31708f; background-color: #d9edf7; } a.<API key>, button.<API key> { color: #31708f; } a.<API key> .<API key>, button.<API key> .<API key> { color: inherit; } a.<API key>:focus, a.<API key>:hover, button.<API key>:focus, button.<API key>:hover { color: #31708f; background-color: #c4e3f3; } a.<API key>.active, button.<API key>.active { color: #fff; background-color: #31708f; border-color: #31708f; } .<API key> { color: #8a6d3b; background-color: #fcf8e3; } a.<API key>, button.<API key> { color: #8a6d3b; } a.<API key> .<API key>, button.<API key> .<API key> { color: inherit; } a.<API key>:focus, a.<API key>:hover, button.<API key>:focus, button.<API key>:hover { color: #8a6d3b; background-color: #faf2cc; } a.<API key>.active, button.<API key>.active { color: #fff; background-color: #8a6d3b; border-color: #8a6d3b; } .<API key> { color: #a94442; background-color: #f2dede; } a.<API key>, button.<API key> { color: #a94442; } a.<API key> .<API key>, button.<API key> .<API key> { color: inherit; } a.<API key>:focus, a.<API key>:hover, button.<API key>:focus, button.<API key>:hover { color: #a94442; background-color: #ebcccc; } a.<API key>.active, button.<API key>.active { color: #fff; background-color: #a94442; border-color: #a94442; } .embed-responsive { position: relative; display: block; width: 100%; padding: 0; overflow: hidden; } .embed-responsive::before { display: block; content: ""; } .embed-responsive .<API key>, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .<API key>::before { padding-top: 42.85714286%; } .<API key>::before { padding-top: 56.25%; } .<API key>::before { padding-top: 75%; } .<API key>::before { padding-top: 100%; } .close { float: right; font-size: 1.5rem; font-weight: bold; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; opacity: .5; } .close:focus, .close:hover { color: #000; text-decoration: none; cursor: pointer; opacity: .75; } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .modal-open { overflow: hidden; } .modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1050; display: none; overflow: hidden; outline: 0; } .modal.fade .modal-dialog { -webkit-transition: -webkit-transform 0.3s ease-out; transition: -webkit-transform 0.3s ease-out; -o-transition: -o-transform 0.3s ease-out; transition: transform 0.3s ease-out; transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out, -o-transform 0.3s ease-out; -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); } .modal.show .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } .modal-open .modal { overflow-x: hidden; overflow-y: auto; } .modal-dialog { position: relative; width: auto; margin: 10px; } .modal-content { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -<API key>: normal; -<API key>: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; -<API key>: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; outline: 0; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop.show { opacity: 0.5; } .modal-header { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -<API key>: space-between; -ms-flex-pack: justify; justify-content: space-between; padding: 15px; border-bottom: 1px solid #AEA79F; } .modal-title { margin-bottom: 0; line-height: 1.5; } .modal-body { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 15px; } .modal-footer { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: end; -<API key>: flex-end; -ms-flex-pack: end; justify-content: flex-end; padding: 15px; border-top: 1px solid #AEA79F; } .modal-footer > :not(:first-child) { margin-left: .25rem; } .modal-footer > :not(:last-child) { margin-right: .25rem; } .<API key> { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll; } @media (min-width: 576px) { .modal-dialog { max-width: 500px; margin: 30px auto; } .modal-sm { max-width: 300px; } } @media (min-width: 992px) { .modal-lg { max-width: 800px; } } .tooltip { position: absolute; z-index: 1070; display: block; font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; opacity: 0; } .tooltip.show { opacity: 0.9; } .tooltip.tooltip-top, .tooltip.<API key> { padding: 5px 0; margin-top: -3px; } .tooltip.tooltip-top .tooltip-inner::before, .tooltip.<API key> .tooltip-inner::before { bottom: 0; left: 50%; margin-left: -5px; content: ""; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.tooltip-right, .tooltip.<API key> { padding: 0 5px; margin-left: 3px; } .tooltip.tooltip-right .tooltip-inner::before, .tooltip.<API key> .tooltip-inner::before { top: 50%; left: 0; margin-top: -5px; content: ""; border-width: 5px 5px 5px 0; border-right-color: #000; } .tooltip.tooltip-bottom, .tooltip.<API key> { padding: 5px 0; margin-top: 3px; } .tooltip.tooltip-bottom .tooltip-inner::before, .tooltip.<API key> .tooltip-inner::before { top: 0; left: 50%; margin-left: -5px; content: ""; border-width: 0 5px 5px; border-bottom-color: #000; } .tooltip.tooltip-left, .tooltip.<API key> { padding: 0 5px; margin-left: -3px; } .tooltip.tooltip-left .tooltip-inner::before, .tooltip.<API key> .tooltip-inner::before { top: 50%; right: 0; margin-top: -5px; content: ""; border-width: 5px 0 5px 5px; border-left-color: #000; } .tooltip-inner { max-width: 200px; padding: 3px 8px; color: #fff; text-align: center; background-color: #000; border-radius: 0.25rem; } .tooltip-inner::before { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover { position: absolute; top: 0; left: 0; z-index: 1060; display: block; max-width: 276px; padding: 1px; font-family: "Ubuntu", Tahoma, "Helvetica Neue", Helvetica, Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; background-color: #fff; -<API key>: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; } .popover.popover-top, .popover.<API key> { margin-top: -10px; } .popover.popover-top::before, .popover.popover-top::after, .popover.<API key>::before, .popover.<API key>::after { left: 50%; border-bottom-width: 0; } .popover.popover-top::before, .popover.<API key>::before { bottom: -11px; margin-left: -11px; border-top-color: rgba(0, 0, 0, 0.25); } .popover.popover-top::after, .popover.<API key>::after { bottom: -10px; margin-left: -10px; border-top-color: #fff; } .popover.popover-right, .popover.<API key> { margin-left: 10px; } .popover.popover-right::before, .popover.popover-right::after, .popover.<API key>::before, .popover.<API key>::after { top: 50%; border-left-width: 0; } .popover.popover-right::before, .popover.<API key>::before { left: -11px; margin-top: -11px; border-right-color: rgba(0, 0, 0, 0.25); } .popover.popover-right::after, .popover.<API key>::after { left: -10px; margin-top: -10px; border-right-color: #fff; } .popover.popover-bottom, .popover.<API key> { margin-top: 10px; } .popover.popover-bottom::before, .popover.popover-bottom::after, .popover.<API key>::before, .popover.<API key>::after { left: 50%; border-top-width: 0; } .popover.popover-bottom::before, .popover.<API key>::before { top: -11px; margin-left: -11px; border-bottom-color: rgba(0, 0, 0, 0.25); } .popover.popover-bottom::after, .popover.<API key>::after { top: -10px; margin-left: -10px; border-bottom-color: #f7f7f7; } .popover.popover-bottom .popover-title::before, .popover.<API key> .popover-title::before { position: absolute; top: 0; left: 50%; display: block; width: 20px; margin-left: -10px; content: ""; border-bottom: 1px solid #f7f7f7; } .popover.popover-left, .popover.<API key> { margin-left: -10px; } .popover.popover-left::before, .popover.popover-left::after, .popover.<API key>::before, .popover.<API key>::after { top: 50%; border-right-width: 0; } .popover.popover-left::before, .popover.<API key>::before { right: -11px; margin-top: -11px; border-left-color: rgba(0, 0, 0, 0.25); } .popover.popover-left::after, .popover.<API key>::after { right: -10px; margin-top: -10px; border-left-color: #fff; } .popover-title { padding: 8px 14px; margin-bottom: 0; font-size: 1rem; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; <API key>: calc(0.3rem - 1px); <API key>: calc(0.3rem - 1px); } .popover-title:empty { display: none; } .popover-content { padding: 9px 14px; } .popover::before, .popover::after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover::before { content: ""; border-width: 11px; } .popover::after { content: ""; border-width: 10px; } .carousel { position: relative; } .carousel-inner { position: relative; width: 100%; overflow: hidden; } .carousel-item { position: relative; display: none; width: 100%; } @media (-webkit-transform-3d) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -<API key>: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -<API key>: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } .carousel-item.active, .carousel-item-next, .carousel-item-prev { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .carousel-item-next, .carousel-item-prev { position: absolute; top: 0; } @media (-webkit-transform-3d) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } .<API key>, .<API key> { position: absolute; top: 0; bottom: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; width: 15%; color: #fff; text-align: center; opacity: 0.5; } .<API key>:focus, .<API key>:hover, .<API key>:focus, .<API key>:hover { color: #fff; text-decoration: none; outline: 0; opacity: .9; } .<API key> { left: 0; } .<API key> { right: 0; } .<API key>, .<API key> { display: inline-block; width: 20px; height: 20px; background: transparent no-repeat center center; -<API key>: 100% 100%; background-size: 100% 100%; } .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .<API key> { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http: } .carousel-indicators { position: absolute; right: 0; bottom: 10px; left: 0; z-index: 15; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -<API key>: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; margin-right: 15%; margin-left: 15%; list-style: none; } .carousel-indicators li { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 0 auto; -ms-flex: 1 0 auto; flex: 1 0 auto; max-width: 30px; height: 3px; margin-right: 3px; margin-left: 3px; text-indent: -999px; cursor: pointer; background-color: rgba(255, 255, 255, 0.5); } .carousel-indicators li::before { position: absolute; top: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators li::after { position: absolute; bottom: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators .active { background-color: #fff; } .carousel-caption { position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: #fff; text-align: center; } .align-baseline { vertical-align: baseline !important; } .align-top { vertical-align: top !important; } .align-middle { vertical-align: middle !important; } .align-bottom { vertical-align: bottom !important; } .align-text-bottom { vertical-align: text-bottom !important; } .align-text-top { vertical-align: text-top !important; } .bg-faded { background-color: #f7f7f7; } .bg-primary { background-color: #E95420 !important; } a.bg-primary:focus, a.bg-primary:hover { background-color: #c34113 !important; } .bg-success { background-color: #38B44A !important; } a.bg-success:focus, a.bg-success:hover { background-color: #2c8d3a !important; } .bg-info { background-color: #772953 !important; } a.bg-info:focus, a.bg-info:hover { background-color: #511c39 !important; } .bg-warning { background-color: #EFB73E !important; } a.bg-warning:focus, a.bg-warning:hover { background-color: #e7a413 !important; } .bg-danger { background-color: #DF382C !important; } a.bg-danger:focus, a.bg-danger:hover { background-color: #bc271c !important; } .bg-inverse { background-color: #222 !important; } a.bg-inverse:focus, a.bg-inverse:hover { background-color: #090909 !important; } .border-0 { border: 0 !important; } .border-top-0 { border-top: 0 !important; } .border-right-0 { border-right: 0 !important; } .border-bottom-0 { border-bottom: 0 !important; } .border-left-0 { border-left: 0 !important; } .rounded { border-radius: 0.25rem; } .rounded-top { <API key>: 0.25rem; <API key>: 0.25rem; } .rounded-right { <API key>: 0.25rem; <API key>: 0.25rem; } .rounded-bottom { <API key>: 0.25rem; <API key>: 0.25rem; } .rounded-left { <API key>: 0.25rem; <API key>: 0.25rem; } .rounded-circle { border-radius: 50%; } .rounded-0 { border-radius: 0; } .clearfix::after { display: block; content: ""; clear: both; } .d-none { display: none !important; } .d-inline { display: inline !important; } .d-inline-block { display: inline-block !important; } .d-block { display: block !important; } .d-table { display: table !important; } .d-table-cell { display: table-cell !important; } .d-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } @media (min-width: 576px) { .d-sm-none { display: none !important; } .d-sm-inline { display: inline !important; } .d-sm-inline-block { display: inline-block !important; } .d-sm-block { display: block !important; } .d-sm-table { display: table !important; } .d-sm-table-cell { display: table-cell !important; } .d-sm-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-sm-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 768px) { .d-md-none { display: none !important; } .d-md-inline { display: inline !important; } .d-md-inline-block { display: inline-block !important; } .d-md-block { display: block !important; } .d-md-table { display: table !important; } .d-md-table-cell { display: table-cell !important; } .d-md-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-md-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 992px) { .d-lg-none { display: none !important; } .d-lg-inline { display: inline !important; } .d-lg-inline-block { display: inline-block !important; } .d-lg-block { display: block !important; } .d-lg-table { display: table !important; } .d-lg-table-cell { display: table-cell !important; } .d-lg-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-lg-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 1200px) { .d-xl-none { display: none !important; } .d-xl-inline { display: inline !important; } .d-xl-inline-block { display: inline-block !important; } .d-xl-block { display: block !important; } .d-xl-table { display: table !important; } .d-xl-table-cell { display: table-cell !important; } .d-xl-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-xl-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } .flex-first { -<API key>: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-last { -<API key>: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-unordered { -<API key>: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-row { -webkit-box-orient: horizontal !important; -<API key>: normal !important; -<API key>: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-column { -webkit-box-orient: vertical !important; -<API key>: normal !important; -<API key>: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-row-reverse { -webkit-box-orient: horizontal !important; -<API key>: reverse !important; -<API key>: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-column-reverse { -webkit-box-orient: vertical !important; -<API key>: reverse !important; -<API key>: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .<API key> { -webkit-box-pack: start !important; -<API key>: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-end { -webkit-box-pack: end !important; -<API key>: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .<API key> { -webkit-box-pack: center !important; -<API key>: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .<API key> { -webkit-box-pack: justify !important; -<API key>: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .<API key> { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-start { -<API key>: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-end { -<API key>: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .<API key> { -<API key>: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .<API key> { -<API key>: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .<API key> { -<API key>: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } @media (min-width: 576px) { .flex-sm-first { -<API key>: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-sm-last { -<API key>: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-sm-unordered { -<API key>: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-sm-row { -webkit-box-orient: horizontal !important; -<API key>: normal !important; -<API key>: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-sm-column { -webkit-box-orient: vertical !important; -<API key>: normal !important; -<API key>: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-sm-row-reverse { -webkit-box-orient: horizontal !important; -<API key>: reverse !important; -<API key>: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .<API key> { -webkit-box-orient: vertical !important; -<API key>: reverse !important; -<API key>: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-sm-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-sm-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .<API key> { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .<API key> { -webkit-box-pack: start !important; -<API key>: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .<API key> { -webkit-box-pack: end !important; -<API key>: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .<API key> { -webkit-box-pack: center !important; -<API key>: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .<API key> { -webkit-box-pack: justify !important; -<API key>: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .<API key> { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-sm-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .<API key> { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .<API key> { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .<API key> { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .<API key> { -<API key>: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .<API key> { -<API key>: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .<API key> { -<API key>: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .<API key> { -<API key>: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .<API key> { -<API key>: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-sm-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-sm-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-sm-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .<API key> { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .<API key> { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .<API key> { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 768px) { .flex-md-first { -<API key>: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-md-last { -<API key>: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-md-unordered { -<API key>: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-md-row { -webkit-box-orient: horizontal !important; -<API key>: normal !important; -<API key>: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-md-column { -webkit-box-orient: vertical !important; -<API key>: normal !important; -<API key>: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-md-row-reverse { -webkit-box-orient: horizontal !important; -<API key>: reverse !important; -<API key>: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .<API key> { -webkit-box-orient: vertical !important; -<API key>: reverse !important; -<API key>: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-md-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-md-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .<API key> { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .<API key> { -webkit-box-pack: start !important; -<API key>: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .<API key> { -webkit-box-pack: end !important; -<API key>: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .<API key> { -webkit-box-pack: center !important; -<API key>: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .<API key> { -webkit-box-pack: justify !important; -<API key>: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .<API key> { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-md-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .<API key> { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .<API key> { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .<API key> { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .<API key> { -<API key>: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .<API key> { -<API key>: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .<API key> { -<API key>: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .<API key> { -<API key>: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .<API key> { -<API key>: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-md-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-md-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-md-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .<API key> { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .<API key> { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .<API key> { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 992px) { .flex-lg-first { -<API key>: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-lg-last { -<API key>: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-lg-unordered { -<API key>: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-lg-row { -webkit-box-orient: horizontal !important; -<API key>: normal !important; -<API key>: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-lg-column { -webkit-box-orient: vertical !important; -<API key>: normal !important; -<API key>: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-lg-row-reverse { -webkit-box-orient: horizontal !important; -<API key>: reverse !important; -<API key>: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .<API key> { -webkit-box-orient: vertical !important; -<API key>: reverse !important; -<API key>: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-lg-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-lg-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .<API key> { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .<API key> { -webkit-box-pack: start !important; -<API key>: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .<API key> { -webkit-box-pack: end !important; -<API key>: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .<API key> { -webkit-box-pack: center !important; -<API key>: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .<API key> { -webkit-box-pack: justify !important; -<API key>: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .<API key> { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-lg-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .<API key> { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .<API key> { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .<API key> { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .<API key> { -<API key>: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .<API key> { -<API key>: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .<API key> { -<API key>: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .<API key> { -<API key>: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .<API key> { -<API key>: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-lg-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-lg-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-lg-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .<API key> { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .<API key> { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .<API key> { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 1200px) { .flex-xl-first { -<API key>: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-xl-last { -<API key>: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-xl-unordered { -<API key>: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-xl-row { -webkit-box-orient: horizontal !important; -<API key>: normal !important; -<API key>: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-xl-column { -webkit-box-orient: vertical !important; -<API key>: normal !important; -<API key>: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-xl-row-reverse { -webkit-box-orient: horizontal !important; -<API key>: reverse !important; -<API key>: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .<API key> { -webkit-box-orient: vertical !important; -<API key>: reverse !important; -<API key>: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-xl-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-xl-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .<API key> { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .<API key> { -webkit-box-pack: start !important; -<API key>: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .<API key> { -webkit-box-pack: end !important; -<API key>: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .<API key> { -webkit-box-pack: center !important; -<API key>: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .<API key> { -webkit-box-pack: justify !important; -<API key>: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .<API key> { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-xl-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .<API key> { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .<API key> { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .<API key> { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .<API key> { -<API key>: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .<API key> { -<API key>: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .<API key> { -<API key>: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .<API key> { -<API key>: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .<API key> { -<API key>: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .<API key> { -<API key>: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-xl-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-xl-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-xl-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .<API key> { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .<API key> { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .<API key> { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } .float-left { float: left !important; } .float-right { float: right !important; } .float-none { float: none !important; } @media (min-width: 576px) { .float-sm-left { float: left !important; } .float-sm-right { float: right !important; } .float-sm-none { float: none !important; } } @media (min-width: 768px) { .float-md-left { float: left !important; } .float-md-right { float: right !important; } .float-md-none { float: none !important; } } @media (min-width: 992px) { .float-lg-left { float: left !important; } .float-lg-right { float: right !important; } .float-lg-none { float: none !important; } } @media (min-width: 1200px) { .float-xl-left { float: left !important; } .float-xl-right { float: right !important; } .float-xl-none { float: none !important; } } .fixed-top { position: fixed; top: 0; right: 0; left: 0; z-index: 1030; } .fixed-bottom { position: fixed; right: 0; bottom: 0; left: 0; z-index: 1030; } .sticky-top { position: -webkit-sticky; position: sticky; top: 0; z-index: 1030; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .sr-only-focusable:active, .sr-only-focusable:focus { position: static; width: auto; height: auto; margin: 0; overflow: visible; clip: auto; } .w-25 { width: 25% !important; } .w-50 { width: 50% !important; } .w-75 { width: 75% !important; } .w-100 { width: 100% !important; } .h-25 { height: 25% !important; } .h-50 { height: 50% !important; } .h-75 { height: 75% !important; } .h-100 { height: 100% !important; } .mw-100 { max-width: 100% !important; } .mh-100 { max-height: 100% !important; } .m-0 { margin: 0 0 !important; } .mt-0 { margin-top: 0 !important; } .mr-0 { margin-right: 0 !important; } .mb-0 { margin-bottom: 0 !important; } .ml-0 { margin-left: 0 !important; } .mx-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-1 { margin: 0.25rem 0.25rem !important; } .mt-1 { margin-top: 0.25rem !important; } .mr-1 { margin-right: 0.25rem !important; } .mb-1 { margin-bottom: 0.25rem !important; } .ml-1 { margin-left: 0.25rem !important; } .mx-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-2 { margin: 0.5rem 0.5rem !important; } .mt-2 { margin-top: 0.5rem !important; } .mr-2 { margin-right: 0.5rem !important; } .mb-2 { margin-bottom: 0.5rem !important; } .ml-2 { margin-left: 0.5rem !important; } .mx-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-3 { margin: 1rem 1rem !important; } .mt-3 { margin-top: 1rem !important; } .mr-3 { margin-right: 1rem !important; } .mb-3 { margin-bottom: 1rem !important; } .ml-3 { margin-left: 1rem !important; } .mx-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-4 { margin: 1.5rem 1.5rem !important; } .mt-4 { margin-top: 1.5rem !important; } .mr-4 { margin-right: 1.5rem !important; } .mb-4 { margin-bottom: 1.5rem !important; } .ml-4 { margin-left: 1.5rem !important; } .mx-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-5 { margin: 3rem 3rem !important; } .mt-5 { margin-top: 3rem !important; } .mr-5 { margin-right: 3rem !important; } .mb-5 { margin-bottom: 3rem !important; } .ml-5 { margin-left: 3rem !important; } .mx-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-0 { padding: 0 0 !important; } .pt-0 { padding-top: 0 !important; } .pr-0 { padding-right: 0 !important; } .pb-0 { padding-bottom: 0 !important; } .pl-0 { padding-left: 0 !important; } .px-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-1 { padding: 0.25rem 0.25rem !important; } .pt-1 { padding-top: 0.25rem !important; } .pr-1 { padding-right: 0.25rem !important; } .pb-1 { padding-bottom: 0.25rem !important; } .pl-1 { padding-left: 0.25rem !important; } .px-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-2 { padding: 0.5rem 0.5rem !important; } .pt-2 { padding-top: 0.5rem !important; } .pr-2 { padding-right: 0.5rem !important; } .pb-2 { padding-bottom: 0.5rem !important; } .pl-2 { padding-left: 0.5rem !important; } .px-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-3 { padding: 1rem 1rem !important; } .pt-3 { padding-top: 1rem !important; } .pr-3 { padding-right: 1rem !important; } .pb-3 { padding-bottom: 1rem !important; } .pl-3 { padding-left: 1rem !important; } .px-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-4 { padding: 1.5rem 1.5rem !important; } .pt-4 { padding-top: 1.5rem !important; } .pr-4 { padding-right: 1.5rem !important; } .pb-4 { padding-bottom: 1.5rem !important; } .pl-4 { padding-left: 1.5rem !important; } .px-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-5 { padding: 3rem 3rem !important; } .pt-5 { padding-top: 3rem !important; } .pr-5 { padding-right: 3rem !important; } .pb-5 { padding-bottom: 3rem !important; } .pl-5 { padding-left: 3rem !important; } .px-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-auto { margin: auto !important; } .mt-auto { margin-top: auto !important; } .mr-auto { margin-right: auto !important; } .mb-auto { margin-bottom: auto !important; } .ml-auto { margin-left: auto !important; } .mx-auto { margin-right: auto !important; margin-left: auto !important; } .my-auto { margin-top: auto !important; margin-bottom: auto !important; } @media (min-width: 576px) { .m-sm-0 { margin: 0 0 !important; } .mt-sm-0 { margin-top: 0 !important; } .mr-sm-0 { margin-right: 0 !important; } .mb-sm-0 { margin-bottom: 0 !important; } .ml-sm-0 { margin-left: 0 !important; } .mx-sm-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-sm-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-sm-1 { margin: 0.25rem 0.25rem !important; } .mt-sm-1 { margin-top: 0.25rem !important; } .mr-sm-1 { margin-right: 0.25rem !important; } .mb-sm-1 { margin-bottom: 0.25rem !important; } .ml-sm-1 { margin-left: 0.25rem !important; } .mx-sm-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-sm-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-sm-2 { margin: 0.5rem 0.5rem !important; } .mt-sm-2 { margin-top: 0.5rem !important; } .mr-sm-2 { margin-right: 0.5rem !important; } .mb-sm-2 { margin-bottom: 0.5rem !important; } .ml-sm-2 { margin-left: 0.5rem !important; } .mx-sm-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-sm-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-sm-3 { margin: 1rem 1rem !important; } .mt-sm-3 { margin-top: 1rem !important; } .mr-sm-3 { margin-right: 1rem !important; } .mb-sm-3 { margin-bottom: 1rem !important; } .ml-sm-3 { margin-left: 1rem !important; } .mx-sm-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-sm-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-sm-4 { margin: 1.5rem 1.5rem !important; } .mt-sm-4 { margin-top: 1.5rem !important; } .mr-sm-4 { margin-right: 1.5rem !important; } .mb-sm-4 { margin-bottom: 1.5rem !important; } .ml-sm-4 { margin-left: 1.5rem !important; } .mx-sm-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-sm-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-sm-5 { margin: 3rem 3rem !important; } .mt-sm-5 { margin-top: 3rem !important; } .mr-sm-5 { margin-right: 3rem !important; } .mb-sm-5 { margin-bottom: 3rem !important; } .ml-sm-5 { margin-left: 3rem !important; } .mx-sm-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-sm-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-sm-0 { padding: 0 0 !important; } .pt-sm-0 { padding-top: 0 !important; } .pr-sm-0 { padding-right: 0 !important; } .pb-sm-0 { padding-bottom: 0 !important; } .pl-sm-0 { padding-left: 0 !important; } .px-sm-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-sm-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-sm-1 { padding: 0.25rem 0.25rem !important; } .pt-sm-1 { padding-top: 0.25rem !important; } .pr-sm-1 { padding-right: 0.25rem !important; } .pb-sm-1 { padding-bottom: 0.25rem !important; } .pl-sm-1 { padding-left: 0.25rem !important; } .px-sm-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-sm-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-sm-2 { padding: 0.5rem 0.5rem !important; } .pt-sm-2 { padding-top: 0.5rem !important; } .pr-sm-2 { padding-right: 0.5rem !important; } .pb-sm-2 { padding-bottom: 0.5rem !important; } .pl-sm-2 { padding-left: 0.5rem !important; } .px-sm-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-sm-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-sm-3 { padding: 1rem 1rem !important; } .pt-sm-3 { padding-top: 1rem !important; } .pr-sm-3 { padding-right: 1rem !important; } .pb-sm-3 { padding-bottom: 1rem !important; } .pl-sm-3 { padding-left: 1rem !important; } .px-sm-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-sm-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-sm-4 { padding: 1.5rem 1.5rem !important; } .pt-sm-4 { padding-top: 1.5rem !important; } .pr-sm-4 { padding-right: 1.5rem !important; } .pb-sm-4 { padding-bottom: 1.5rem !important; } .pl-sm-4 { padding-left: 1.5rem !important; } .px-sm-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-sm-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-sm-5 { padding: 3rem 3rem !important; } .pt-sm-5 { padding-top: 3rem !important; } .pr-sm-5 { padding-right: 3rem !important; } .pb-sm-5 { padding-bottom: 3rem !important; } .pl-sm-5 { padding-left: 3rem !important; } .px-sm-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-sm-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-sm-auto { margin: auto !important; } .mt-sm-auto { margin-top: auto !important; } .mr-sm-auto { margin-right: auto !important; } .mb-sm-auto { margin-bottom: auto !important; } .ml-sm-auto { margin-left: auto !important; } .mx-sm-auto { margin-right: auto !important; margin-left: auto !important; } .my-sm-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 768px) { .m-md-0 { margin: 0 0 !important; } .mt-md-0 { margin-top: 0 !important; } .mr-md-0 { margin-right: 0 !important; } .mb-md-0 { margin-bottom: 0 !important; } .ml-md-0 { margin-left: 0 !important; } .mx-md-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-md-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-md-1 { margin: 0.25rem 0.25rem !important; } .mt-md-1 { margin-top: 0.25rem !important; } .mr-md-1 { margin-right: 0.25rem !important; } .mb-md-1 { margin-bottom: 0.25rem !important; } .ml-md-1 { margin-left: 0.25rem !important; } .mx-md-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-md-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-md-2 { margin: 0.5rem 0.5rem !important; } .mt-md-2 { margin-top: 0.5rem !important; } .mr-md-2 { margin-right: 0.5rem !important; } .mb-md-2 { margin-bottom: 0.5rem !important; } .ml-md-2 { margin-left: 0.5rem !important; } .mx-md-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-md-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-md-3 { margin: 1rem 1rem !important; } .mt-md-3 { margin-top: 1rem !important; } .mr-md-3 { margin-right: 1rem !important; } .mb-md-3 { margin-bottom: 1rem !important; } .ml-md-3 { margin-left: 1rem !important; } .mx-md-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-md-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-md-4 { margin: 1.5rem 1.5rem !important; } .mt-md-4 { margin-top: 1.5rem !important; } .mr-md-4 { margin-right: 1.5rem !important; } .mb-md-4 { margin-bottom: 1.5rem !important; } .ml-md-4 { margin-left: 1.5rem !important; } .mx-md-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-md-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-md-5 { margin: 3rem 3rem !important; } .mt-md-5 { margin-top: 3rem !important; } .mr-md-5 { margin-right: 3rem !important; } .mb-md-5 { margin-bottom: 3rem !important; } .ml-md-5 { margin-left: 3rem !important; } .mx-md-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-md-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-md-0 { padding: 0 0 !important; } .pt-md-0 { padding-top: 0 !important; } .pr-md-0 { padding-right: 0 !important; } .pb-md-0 { padding-bottom: 0 !important; } .pl-md-0 { padding-left: 0 !important; } .px-md-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-md-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-md-1 { padding: 0.25rem 0.25rem !important; } .pt-md-1 { padding-top: 0.25rem !important; } .pr-md-1 { padding-right: 0.25rem !important; } .pb-md-1 { padding-bottom: 0.25rem !important; } .pl-md-1 { padding-left: 0.25rem !important; } .px-md-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-md-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-md-2 { padding: 0.5rem 0.5rem !important; } .pt-md-2 { padding-top: 0.5rem !important; } .pr-md-2 { padding-right: 0.5rem !important; } .pb-md-2 { padding-bottom: 0.5rem !important; } .pl-md-2 { padding-left: 0.5rem !important; } .px-md-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-md-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-md-3 { padding: 1rem 1rem !important; } .pt-md-3 { padding-top: 1rem !important; } .pr-md-3 { padding-right: 1rem !important; } .pb-md-3 { padding-bottom: 1rem !important; } .pl-md-3 { padding-left: 1rem !important; } .px-md-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-md-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-md-4 { padding: 1.5rem 1.5rem !important; } .pt-md-4 { padding-top: 1.5rem !important; } .pr-md-4 { padding-right: 1.5rem !important; } .pb-md-4 { padding-bottom: 1.5rem !important; } .pl-md-4 { padding-left: 1.5rem !important; } .px-md-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-md-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-md-5 { padding: 3rem 3rem !important; } .pt-md-5 { padding-top: 3rem !important; } .pr-md-5 { padding-right: 3rem !important; } .pb-md-5 { padding-bottom: 3rem !important; } .pl-md-5 { padding-left: 3rem !important; } .px-md-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-md-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-md-auto { margin: auto !important; } .mt-md-auto { margin-top: auto !important; } .mr-md-auto { margin-right: auto !important; } .mb-md-auto { margin-bottom: auto !important; } .ml-md-auto { margin-left: auto !important; } .mx-md-auto { margin-right: auto !important; margin-left: auto !important; } .my-md-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 992px) { .m-lg-0 { margin: 0 0 !important; } .mt-lg-0 { margin-top: 0 !important; } .mr-lg-0 { margin-right: 0 !important; } .mb-lg-0 { margin-bottom: 0 !important; } .ml-lg-0 { margin-left: 0 !important; } .mx-lg-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-lg-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-lg-1 { margin: 0.25rem 0.25rem !important; } .mt-lg-1 { margin-top: 0.25rem !important; } .mr-lg-1 { margin-right: 0.25rem !important; } .mb-lg-1 { margin-bottom: 0.25rem !important; } .ml-lg-1 { margin-left: 0.25rem !important; } .mx-lg-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-lg-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-lg-2 { margin: 0.5rem 0.5rem !important; } .mt-lg-2 { margin-top: 0.5rem !important; } .mr-lg-2 { margin-right: 0.5rem !important; } .mb-lg-2 { margin-bottom: 0.5rem !important; } .ml-lg-2 { margin-left: 0.5rem !important; } .mx-lg-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-lg-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-lg-3 { margin: 1rem 1rem !important; } .mt-lg-3 { margin-top: 1rem !important; } .mr-lg-3 { margin-right: 1rem !important; } .mb-lg-3 { margin-bottom: 1rem !important; } .ml-lg-3 { margin-left: 1rem !important; } .mx-lg-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-lg-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-lg-4 { margin: 1.5rem 1.5rem !important; } .mt-lg-4 { margin-top: 1.5rem !important; } .mr-lg-4 { margin-right: 1.5rem !important; } .mb-lg-4 { margin-bottom: 1.5rem !important; } .ml-lg-4 { margin-left: 1.5rem !important; } .mx-lg-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-lg-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-lg-5 { margin: 3rem 3rem !important; } .mt-lg-5 { margin-top: 3rem !important; } .mr-lg-5 { margin-right: 3rem !important; } .mb-lg-5 { margin-bottom: 3rem !important; } .ml-lg-5 { margin-left: 3rem !important; } .mx-lg-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-lg-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-lg-0 { padding: 0 0 !important; } .pt-lg-0 { padding-top: 0 !important; } .pr-lg-0 { padding-right: 0 !important; } .pb-lg-0 { padding-bottom: 0 !important; } .pl-lg-0 { padding-left: 0 !important; } .px-lg-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-lg-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-lg-1 { padding: 0.25rem 0.25rem !important; } .pt-lg-1 { padding-top: 0.25rem !important; } .pr-lg-1 { padding-right: 0.25rem !important; } .pb-lg-1 { padding-bottom: 0.25rem !important; } .pl-lg-1 { padding-left: 0.25rem !important; } .px-lg-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-lg-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-lg-2 { padding: 0.5rem 0.5rem !important; } .pt-lg-2 { padding-top: 0.5rem !important; } .pr-lg-2 { padding-right: 0.5rem !important; } .pb-lg-2 { padding-bottom: 0.5rem !important; } .pl-lg-2 { padding-left: 0.5rem !important; } .px-lg-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-lg-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-lg-3 { padding: 1rem 1rem !important; } .pt-lg-3 { padding-top: 1rem !important; } .pr-lg-3 { padding-right: 1rem !important; } .pb-lg-3 { padding-bottom: 1rem !important; } .pl-lg-3 { padding-left: 1rem !important; } .px-lg-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-lg-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-lg-4 { padding: 1.5rem 1.5rem !important; } .pt-lg-4 { padding-top: 1.5rem !important; } .pr-lg-4 { padding-right: 1.5rem !important; } .pb-lg-4 { padding-bottom: 1.5rem !important; } .pl-lg-4 { padding-left: 1.5rem !important; } .px-lg-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-lg-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-lg-5 { padding: 3rem 3rem !important; } .pt-lg-5 { padding-top: 3rem !important; } .pr-lg-5 { padding-right: 3rem !important; } .pb-lg-5 { padding-bottom: 3rem !important; } .pl-lg-5 { padding-left: 3rem !important; } .px-lg-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-lg-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-lg-auto { margin: auto !important; } .mt-lg-auto { margin-top: auto !important; } .mr-lg-auto { margin-right: auto !important; } .mb-lg-auto { margin-bottom: auto !important; } .ml-lg-auto { margin-left: auto !important; } .mx-lg-auto { margin-right: auto !important; margin-left: auto !important; } .my-lg-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 1200px) { .m-xl-0 { margin: 0 0 !important; } .mt-xl-0 { margin-top: 0 !important; } .mr-xl-0 { margin-right: 0 !important; } .mb-xl-0 { margin-bottom: 0 !important; } .ml-xl-0 { margin-left: 0 !important; } .mx-xl-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-xl-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-xl-1 { margin: 0.25rem 0.25rem !important; } .mt-xl-1 { margin-top: 0.25rem !important; } .mr-xl-1 { margin-right: 0.25rem !important; } .mb-xl-1 { margin-bottom: 0.25rem !important; } .ml-xl-1 { margin-left: 0.25rem !important; } .mx-xl-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-xl-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-xl-2 { margin: 0.5rem 0.5rem !important; } .mt-xl-2 { margin-top: 0.5rem !important; } .mr-xl-2 { margin-right: 0.5rem !important; } .mb-xl-2 { margin-bottom: 0.5rem !important; } .ml-xl-2 { margin-left: 0.5rem !important; } .mx-xl-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-xl-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-xl-3 { margin: 1rem 1rem !important; } .mt-xl-3 { margin-top: 1rem !important; } .mr-xl-3 { margin-right: 1rem !important; } .mb-xl-3 { margin-bottom: 1rem !important; } .ml-xl-3 { margin-left: 1rem !important; } .mx-xl-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-xl-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-xl-4 { margin: 1.5rem 1.5rem !important; } .mt-xl-4 { margin-top: 1.5rem !important; } .mr-xl-4 { margin-right: 1.5rem !important; } .mb-xl-4 { margin-bottom: 1.5rem !important; } .ml-xl-4 { margin-left: 1.5rem !important; } .mx-xl-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-xl-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-xl-5 { margin: 3rem 3rem !important; } .mt-xl-5 { margin-top: 3rem !important; } .mr-xl-5 { margin-right: 3rem !important; } .mb-xl-5 { margin-bottom: 3rem !important; } .ml-xl-5 { margin-left: 3rem !important; } .mx-xl-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-xl-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-xl-0 { padding: 0 0 !important; } .pt-xl-0 { padding-top: 0 !important; } .pr-xl-0 { padding-right: 0 !important; } .pb-xl-0 { padding-bottom: 0 !important; } .pl-xl-0 { padding-left: 0 !important; } .px-xl-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-xl-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-xl-1 { padding: 0.25rem 0.25rem !important; } .pt-xl-1 { padding-top: 0.25rem !important; } .pr-xl-1 { padding-right: 0.25rem !important; } .pb-xl-1 { padding-bottom: 0.25rem !important; } .pl-xl-1 { padding-left: 0.25rem !important; } .px-xl-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-xl-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-xl-2 { padding: 0.5rem 0.5rem !important; } .pt-xl-2 { padding-top: 0.5rem !important; } .pr-xl-2 { padding-right: 0.5rem !important; } .pb-xl-2 { padding-bottom: 0.5rem !important; } .pl-xl-2 { padding-left: 0.5rem !important; } .px-xl-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-xl-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-xl-3 { padding: 1rem 1rem !important; } .pt-xl-3 { padding-top: 1rem !important; } .pr-xl-3 { padding-right: 1rem !important; } .pb-xl-3 { padding-bottom: 1rem !important; } .pl-xl-3 { padding-left: 1rem !important; } .px-xl-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-xl-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-xl-4 { padding: 1.5rem 1.5rem !important; } .pt-xl-4 { padding-top: 1.5rem !important; } .pr-xl-4 { padding-right: 1.5rem !important; } .pb-xl-4 { padding-bottom: 1.5rem !important; } .pl-xl-4 { padding-left: 1.5rem !important; } .px-xl-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-xl-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-xl-5 { padding: 3rem 3rem !important; } .pt-xl-5 { padding-top: 3rem !important; } .pr-xl-5 { padding-right: 3rem !important; } .pb-xl-5 { padding-bottom: 3rem !important; } .pl-xl-5 { padding-left: 3rem !important; } .px-xl-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-xl-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-xl-auto { margin: auto !important; } .mt-xl-auto { margin-top: auto !important; } .mr-xl-auto { margin-right: auto !important; } .mb-xl-auto { margin-bottom: auto !important; } .ml-xl-auto { margin-left: auto !important; } .mx-xl-auto { margin-right: auto !important; margin-left: auto !important; } .my-xl-auto { margin-top: auto !important; margin-bottom: auto !important; } } .text-justify { text-align: justify !important; } .text-nowrap { white-space: nowrap !important; } .text-truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .text-center { text-align: center !important; } @media (min-width: 576px) { .text-sm-left { text-align: left !important; } .text-sm-right { text-align: right !important; } .text-sm-center { text-align: center !important; } } @media (min-width: 768px) { .text-md-left { text-align: left !important; } .text-md-right { text-align: right !important; } .text-md-center { text-align: center !important; } } @media (min-width: 992px) { .text-lg-left { text-align: left !important; } .text-lg-right { text-align: right !important; } .text-lg-center { text-align: center !important; } } @media (min-width: 1200px) { .text-xl-left { text-align: left !important; } .text-xl-right { text-align: right !important; } .text-xl-center { text-align: center !important; } } .text-lowercase { text-transform: lowercase !important; } .text-uppercase { text-transform: uppercase !important; } .text-capitalize { text-transform: capitalize !important; } .font-weight-normal { font-weight: normal; } .font-weight-bold { font-weight: bold; } .font-italic { font-style: italic; } .text-white { color: #fff !important; } .text-muted { color: #777 !important; } a.text-muted:focus, a.text-muted:hover { color: #5e5e5e !important; } .text-primary { color: #E95420 !important; } a.text-primary:focus, a.text-primary:hover { color: #c34113 !important; } .text-success { color: #38B44A !important; } a.text-success:focus, a.text-success:hover { color: #2c8d3a !important; } .text-info { color: #772953 !important; } a.text-info:focus, a.text-info:hover { color: #511c39 !important; } .text-warning { color: #EFB73E !important; } a.text-warning:focus, a.text-warning:hover { color: #e7a413 !important; } .text-danger { color: #DF382C !important; } a.text-danger:focus, a.text-danger:hover { color: #bc271c !important; } .text-gray-dark { color: #222 !important; } a.text-gray-dark:focus, a.text-gray-dark:hover { color: #090909 !important; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .invisible { visibility: hidden !important; } .hidden-xs-up { display: none !important; } @media (max-width: 575px) { .hidden-xs-down { display: none !important; } } @media (min-width: 576px) { .hidden-sm-up { display: none !important; } } @media (max-width: 767px) { .hidden-sm-down { display: none !important; } } @media (min-width: 768px) { .hidden-md-up { display: none !important; } } @media (max-width: 991px) { .hidden-md-down { display: none !important; } } @media (min-width: 992px) { .hidden-lg-up { display: none !important; } } @media (max-width: 1199px) { .hidden-lg-down { display: none !important; } } @media (min-width: 1200px) { .hidden-xl-up { display: none !important; } } .hidden-xl-down { display: none !important; } .visible-print-block { display: none !important; } @media print { .visible-print-block { display: block !important; } } .<API key> { display: none !important; } @media print { .<API key> { display: inline !important; } } .<API key> { display: none !important; } @media print { .<API key> { display: inline-block !important; } } @media print { .hidden-print { display: none !important; } } .bg-inverse { background-color: #772953 !important; } .thead-inverse th { background-color: #772953; }
package net.minecraft.entity.monster; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.<API key>; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; public abstract class EntityMob extends EntityCreature implements IMob { public EntityMob(World worldIn) { super(worldIn); this.experienceValue = 5; } public SoundCategory getSoundCategory() { return SoundCategory.HOSTILE; } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ public void onLivingUpdate() { this.<API key>(); float f = this.getBrightness(1.0F); if (f > 0.5F) { this.entityAge += 2; } super.onLivingUpdate(); } /** * Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { this.setDead(); } } protected SoundEvent getSwimSound() { return SoundEvents.entity_hostile_swim; } protected SoundEvent getSplashSound() { return SoundEvents.<API key>; } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { return this.<API key>(source) ? false : super.attackEntityFrom(source, amount); } protected SoundEvent getHurtSound() { return SoundEvents.entity_hostile_hurt; } protected SoundEvent getDeathSound() { return SoundEvents.<API key>; } protected SoundEvent getFallSound(int heightIn) { return heightIn > 4 ? SoundEvents.<API key> : SoundEvents.<API key>; } public boolean attackEntityAsMob(Entity entityIn) { float f = (float)this.getEntityAttribute(<API key>.ATTACK_DAMAGE).getAttributeValue(); int i = 0; if (entityIn instanceof EntityLivingBase) { f += EnchantmentHelper.<API key>(this.getHeldItemMainhand(), ((EntityLivingBase)entityIn).<API key>()); i += EnchantmentHelper.<API key>(this); } boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), f); if (flag) { if (i > 0 && entityIn instanceof EntityLivingBase) { ((EntityLivingBase)entityIn).knockBack(this, (float)i * 0.5F, (double)MathHelper.sin(this.rotationYaw * 0.017453292F), (double)(-MathHelper.cos(this.rotationYaw * 0.017453292F))); this.motionX *= 0.6D; this.motionZ *= 0.6D; } int j = EnchantmentHelper.<API key>(this); if (j > 0) { entityIn.setFire(j * 4); } if (entityIn instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer)entityIn; ItemStack itemstack = this.getHeldItemMainhand(); ItemStack itemstack1 = entityplayer.isHandActive() ? entityplayer.getActiveItemStack() : null; if (itemstack != null && itemstack1 != null && itemstack.getItem() instanceof ItemAxe && itemstack1.getItem() == Items.shield) { float f1 = 0.25F + (float)EnchantmentHelper.<API key>(this) * 0.05F; if (this.rand.nextFloat() < f1) { entityplayer.getCooldownTracker().setCooldown(Items.shield, 100); this.worldObj.setEntityState(entityplayer, (byte)30); } } } this.applyEnchantments(this, entityIn); } return flag; } public float getBlockPathWeight(BlockPos pos) { return 0.5F - this.worldObj.getLightBrightness(pos); } /** * Checks to make sure the light is not too bright where the mob is spawning */ protected boolean isValidLightLevel() { BlockPos blockpos = new BlockPos(this.posX, this.<API key>().minY, this.posZ); if (this.worldObj.getLightFor(EnumSkyBlock.SKY, blockpos) > this.rand.nextInt(32)) { return false; } else { int i = this.worldObj.<API key>(blockpos); if (this.worldObj.isThundering()) { int j = this.worldObj.<API key>(); this.worldObj.<API key>(10); i = this.worldObj.<API key>(blockpos); this.worldObj.<API key>(j); } return i <= this.rand.nextInt(8); } } /** * Checks if the entity's current position is a valid location to spawn this entity. */ public boolean getCanSpawnHere() { return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL && this.isValidLightLevel() && super.getCanSpawnHere(); } protected void <API key>() { super.<API key>(); this.getAttributeMap().registerAttribute(<API key>.ATTACK_DAMAGE); } /** * Entity won't drop items or experience points if this returns false */ protected boolean canDropLoot() { return true; } }
#ifndef _VECTORS_H_ #define _VECTORS_H_ #include "xil_types.h" #include "xil_assert.h" #ifdef __cplusplus extern "C" { #endif void FIQInterrupt(void); void IRQInterrupt(void); void <API key>(void); void SErrorInterrupt(void); #ifdef __cplusplus } #endif #endif /* protection macro */
#if defined(__ppc__) || defined(__ppc64__) #include <ffi.h> #include <ffi_common.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <ppc-darwin.h> #include <architecture/ppc/<API key>.h> #if defined(POWERPC_DARWIN) #include <libkern/OSCacheControl.h> // for <API key>() #endif extern void ffi_closure_ASM(void); // The layout of a function descriptor. A C function pointer really // points to one of these. typedef struct aix_fd_struct { void* code_pointer; void* toc; } aix_fd; /*@-exportheader@*/ void ffi_prep_args( extended_cif* inEcif, unsigned *const stack) /*@=exportheader@*/ { /* Copy the ecif to a local var so we can trample the arg. BC note: test this with GP later for possible problems... */ volatile extended_cif* ecif = inEcif; const unsigned bytes = ecif->cif->bytes; const unsigned flags = ecif->cif->flags; /* Cast the stack arg from int* to long*. sizeof(long) == 4 in 32-bit mode and 8 in 64-bit mode. */ unsigned long *const longStack = (unsigned long *const)stack; /* 'stacktop' points at the previous backchain pointer. */ #if defined(__ppc64__) // In ppc-darwin.s, an extra 96 bytes is reserved for the linkage area, // saved registers, and an extra FPR. unsigned long *const stacktop = (unsigned long *)(unsigned long)((char*)longStack + bytes + 96); #elif defined(__ppc__) unsigned long *const stacktop = longStack + (bytes / sizeof(long)); #else #error undefined architecture #endif /* 'fpr_base' points at the space for fpr1, and grows upwards as we use FPR registers. */ double* fpr_base = (double*)(stacktop - ASM_NEEDS_REGISTERS) - <API key>; #if defined(__ppc64__) // 64-bit saves an extra register, and uses an extra FPR. Knock fpr_base // down a couple pegs. fpr_base -= 2; #endif unsigned int fparg_count = 0; /* 'next_arg' grows up as we put parameters in it. */ unsigned long* next_arg = longStack + 6; /* 6 reserved positions. */ int i; double double_tmp; void** p_argv = ecif->avalue; unsigned long gprvalue; ffi_type** ptr = ecif->cif->arg_types; /* Check that everything starts aligned properly. */ FFI_ASSERT(stack == SF_ROUND(stack)); FFI_ASSERT(stacktop == SF_ROUND(stacktop)); FFI_ASSERT(bytes == SF_ROUND(bytes)); /* Deal with return values that are actually pass-by-reference. Rule: Return values are referenced by r3, so r4 is the first parameter. */ if (flags & <API key>) *next_arg++ = (unsigned long)(char*)ecif->rvalue; /* Now for the arguments. */ for (i = ecif->cif->nargs; i > 0; i--, ptr++, p_argv++) { switch ((*ptr)->type) { /* If a floating-point parameter appears before all of the general- purpose registers are filled, the corresponding GPRs that match the size of the floating-point parameter are shadowed for the benefit of vararg and pre-ANSI functions. */ case FFI_TYPE_FLOAT: double_tmp = *(float*)*p_argv; if (fparg_count < <API key>) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg++; fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; case FFI_TYPE_DOUBLE: double_tmp = *(double*)*p_argv; if (fparg_count < <API key>) *fpr_base++ = double_tmp; *(double*)next_arg = double_tmp; next_arg += MODE_CHOICE(2,1); fparg_count++; FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (fparg_count < <API key>) *(long double*)fpr_base = *(long double*)*p_argv; #elif defined(__ppc__) if (fparg_count < <API key> - 1) *(long double*)fpr_base = *(long double*)*p_argv; else if (fparg_count == <API key> - 1) *(double*)fpr_base = *(double*)*p_argv; #else #error undefined architecture #endif *(long double*)next_arg = *(long double*)*p_argv; fparg_count += 2; fpr_base += 2; next_arg += MODE_CHOICE(4,2); FFI_ASSERT(flags & FLAG_FP_ARGUMENTS); break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: #if defined(__ppc64__) gprvalue = *(long long*)*p_argv; goto putgpr; #elif defined(__ppc__) *(long long*)next_arg = *(long long*)*p_argv; next_arg += 2; break; #else #error undefined architecture #endif case FFI_TYPE_POINTER: gprvalue = *(unsigned long*)*p_argv; goto putgpr; case FFI_TYPE_UINT8: gprvalue = *(unsigned char*)*p_argv; goto putgpr; case FFI_TYPE_SINT8: gprvalue = *(signed char*)*p_argv; goto putgpr; case FFI_TYPE_UINT16: gprvalue = *(unsigned short*)*p_argv; goto putgpr; case FFI_TYPE_SINT16: gprvalue = *(signed short*)*p_argv; goto putgpr; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; <API key>(*ptr, (char*)*p_argv, NULL, &fparg_count, (char*)next_arg, &gprSize, (char*)fpr_base, &fprSize); next_arg += gprSize / sizeof(long); fpr_base += fprSize / sizeof(double); #elif defined(__ppc__) char* dest_cpy = (char*)next_arg; /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. Structures with 3 byte in size are padded upwards. */ unsigned size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); if (ecif->cif->abi == FFI_DARWIN) { if (size_al < 3) dest_cpy += 4 - size_al; } memcpy((char*)dest_cpy, (char*)*p_argv, size_al); next_arg += (size_al + 3) / 4; #else #error undefined architecture #endif break; } case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: gprvalue = *(unsigned*)*p_argv; putgpr: *next_arg++ = gprvalue; break; default: break; } } /* Check that we didn't overrun the stack... */ //FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS); //FFI_ASSERT((unsigned *)fpr_base // <= stacktop - ASM_NEEDS_REGISTERS - <API key>); //FFI_ASSERT(flags & <API key> || intarg_count <= 4); } #if defined(__ppc64__) bool <API key>( const ffi_type* inType) { bool containsFP = false; unsigned int i; for (i = 0; inType->elements[i] != NULL && !containsFP; i++) { if (inType->elements[i]->type == FFI_TYPE_FLOAT || inType->elements[i]->type == FFI_TYPE_DOUBLE || inType->elements[i]->type == FFI_TYPE_LONGDOUBLE) containsFP = true; else if (inType->elements[i]->type == FFI_TYPE_STRUCT) containsFP = <API key>(inType->elements[i]); } return containsFP; } #endif // defined(__ppc64__) /* Perform machine dependent cif processing. */ ffi_status <API key>( ffi_cif* cif) { /* All this is for the DARWIN ABI. */ int i; ffi_type** ptr; int intarg_count = 0; int fparg_count = 0; unsigned int flags = 0; unsigned int size_al = 0; /* All the machine-independent calculation of cif->bytes will be wrong. Redo the calculation for DARWIN. */ /* Space for the frame pointer, callee's LR, CR, etc, and for the asm's temp regs. */ unsigned int bytes = (6 + ASM_NEEDS_REGISTERS) * sizeof(long); /* Return value handling. The rules are as follows: - 32-bit (or less) integer values are returned in gpr3; - Structures of size <= 4 bytes also returned in gpr3; - 64-bit integer values and structures between 5 and 8 bytes are returned in gpr3 and gpr4; - Single/double FP values are returned in fpr1; - Long double FP (if not equivalent to double) values are returned in fpr1 and fpr2; - Larger structures values are allocated space and a pointer is passed as the first argument. */ switch (cif->rtype->type) { #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: flags |= <API key>; flags |= FLAG_RETURNS_FP; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_DOUBLE: flags |= FLAG_RETURNS_64BITS; /* Fall through. */ case FFI_TYPE_FLOAT: flags |= FLAG_RETURNS_FP; break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: flags |= FLAG_RETURNS_64BITS; break; case FFI_TYPE_STRUCT: { #if defined(__ppc64__) if (<API key>(cif->rtype, NULL, NULL)) { flags |= <API key>; flags |= <API key>; intarg_count++; } else { flags |= FLAG_RETURNS_STRUCT; if (<API key>(cif->rtype)) flags |= <API key>; } #elif defined(__ppc__) flags |= <API key>; flags |= <API key>; intarg_count++; #else #error undefined architecture #endif break; } case FFI_TYPE_VOID: flags |= <API key>; break; default: /* Returns 32-bit integer, or similar. Nothing to do here. */ break; } /* The first <API key> words of integer arguments, and the first <API key> fp arguments, go in registers; the rest goes on the stack. Structures are passed as a pointer to a copy of the structure. Stuff on the stack needs to keep proper alignment. */ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) { switch ((*ptr)->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: fparg_count++; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if (fparg_count > <API key> && intarg_count % 2 != 0) intarg_count++; break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: fparg_count += 2; /* If this FP arg is going on the stack, it must be 8-byte-aligned. */ if ( #if defined(__ppc64__) fparg_count > <API key> + 1 #elif defined(__ppc__) fparg_count > <API key> #else #error undefined architecture #endif && intarg_count % 2 != 0) intarg_count++; intarg_count += 2; break; #endif // FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: /* 'long long' arguments are passed as two words, but either both words must fit in registers or both go on the stack. If they go on the stack, they must be 8-byte-aligned. */ if (intarg_count == <API key> - 1 || (intarg_count >= <API key> && intarg_count % 2 != 0)) intarg_count++; intarg_count += MODE_CHOICE(2,1); break; case FFI_TYPE_STRUCT: size_al = (*ptr)->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if ((*ptr)->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN((*ptr)->size, 8); #if defined(__ppc64__) // Look for FP struct members. unsigned int j; for (j = 0; (*ptr)->elements[j] != NULL; j++) { if ((*ptr)->elements[j]->type == FFI_TYPE_FLOAT || (*ptr)->elements[j]->type == FFI_TYPE_DOUBLE) { fparg_count++; if (fparg_count > <API key>) intarg_count++; } else if ((*ptr)->elements[j]->type == FFI_TYPE_LONGDOUBLE) { fparg_count += 2; if (fparg_count > <API key> + 1) intarg_count += 2; } else intarg_count++; } #elif defined(__ppc__) intarg_count += (size_al + 3) / 4; #else #error undefined architecture #endif break; default: /* Everything else is passed as a 4/8-byte word in a GPR, either the object itself or a pointer to it. */ intarg_count++; break; } } /* Space for the FPR registers, if needed. */ if (fparg_count != 0) { flags |= FLAG_FP_ARGUMENTS; #if defined(__ppc64__) bytes += (<API key> + 1) * sizeof(double); #elif defined(__ppc__) bytes += <API key> * sizeof(double); #else #error undefined architecture #endif } /* Stack space. */ #if defined(__ppc64__) if ((intarg_count + fparg_count) > <API key>) bytes += (intarg_count + fparg_count) * sizeof(long); #elif defined(__ppc__) if ((intarg_count + 2 * fparg_count) > <API key>) bytes += (intarg_count + 2 * fparg_count) * sizeof(long); #else #error undefined architecture #endif else bytes += <API key> * sizeof(long); /* The stack space allocated needs to be a multiple of 16/32 bytes. */ bytes = SF_ROUND(bytes); cif->flags = flags; cif->bytes = bytes; return FFI_OK; } /*@-declundef@*/ /*@-exportheader@*/ extern void ffi_call_AIX( /*@out@*/ extended_cif*, unsigned, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); extern void ffi_call_DARWIN( /*@out@*/ extended_cif*, unsigned long, unsigned, /*@out@*/ unsigned*, void (*fn)(void), void (*fn2)(extended_cif*, unsigned *const)); /*@=declundef@*/ /*@=exportheader@*/ void ffi_call( /*@dependent@*/ ffi_cif* cif, void (*fn)(void), /*@out@*/ void* rvalue, /*@dependent@*/ void** avalue) { extended_cif ecif; ecif.cif = cif; ecif.avalue = avalue; /* If the return value is a struct and we don't have a return value address then we need to make one. */ if ((rvalue == NULL) && (cif->rtype->type == FFI_TYPE_STRUCT)) { /*@-sysunrecog@*/ ecif.rvalue = alloca(cif->rtype->size); /*@=sysunrecog@*/ } else ecif.rvalue = rvalue; switch (cif->abi) { case FFI_AIX: /*@-usedef@*/ ffi_call_AIX(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; case FFI_DARWIN: /*@-usedef@*/ ffi_call_DARWIN(&ecif, -(long)cif->bytes, cif->flags, ecif.rvalue, fn, ffi_prep_args); /*@=usedef@*/ break; default: FFI_ASSERT(0); break; } } #if !defined(POWERPC_DARWIN) #define MIN_LINE_SIZE 32 static void flush_icache( char* addr) { #ifndef _AIX __asm__ volatile ( "dcbf 0,%0\n" "sync\n" "icbi 0,%0\n" "sync\n" "isync" : : "r" (addr) : "memory"); #endif } static void flush_range( char* addr, int size) { int i; for (i = 0; i < size; i += MIN_LINE_SIZE) flush_icache(addr + i); flush_icache(addr + size - 1); } #endif // !defined(POWERPC_DARWIN) ffi_status ffi_prep_closure( ffi_closure* closure, ffi_cif* cif, void (*fun)(ffi_cif*, void*, void**, void*), void* user_data) { switch (cif->abi) { case FFI_DARWIN: { FFI_ASSERT (cif->abi == FFI_DARWIN); unsigned int* tramp = (unsigned int*)&closure->tramp[0]; #if defined(__ppc64__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0xe98b0018; // ld r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0xe96b0020; // ld r11,32(r11) tramp[7] = 0x4e800420; // bctr *(unsigned long*)&tramp[8] = (unsigned long)ffi_closure_ASM; *(unsigned long*)&tramp[10] = (unsigned long)closure; #elif defined(__ppc__) tramp[0] = 0x7c0802a6; // mflr r0 tramp[1] = 0x429f0005; // bcl 20,31,+0x8 tramp[2] = 0x7d6802a6; // mflr r11 tramp[3] = 0x7c0803a6; // mtlr r0 tramp[4] = 0x818b0018; // lwz r12,24(r11) tramp[5] = 0x7d8903a6; // mtctr r12 tramp[6] = 0x816b001c; // lwz r11,28(r11) tramp[7] = 0x4e800420; // bctr tramp[8] = (unsigned long)ffi_closure_ASM; tramp[9] = (unsigned long)closure; #else #error undefined architecture #endif closure->cif = cif; closure->fun = fun; closure->user_data = user_data; // Flush the icache. Only necessary on Darwin. #if defined(POWERPC_DARWIN) <API key>(closure->tramp, FFI_TRAMPOLINE_SIZE); #else flush_range(closure->tramp, FFI_TRAMPOLINE_SIZE); #endif break; } case FFI_AIX: { FFI_ASSERT (cif->abi == FFI_AIX); <API key>* tramp_aix = (<API key>*)(closure->tramp); aix_fd* fd = (aix_fd*)(void*)ffi_closure_ASM; tramp_aix->code_pointer = fd->code_pointer; tramp_aix->toc = fd->toc; tramp_aix->static_chain = closure; closure->cif = cif; closure->fun = fun; closure->user_data = user_data; break; } default: return FFI_BAD_ABI; } return FFI_OK; } #if defined(__ppc__) typedef double ldbits[2]; typedef union { ldbits lb; long double ld; } ldu; #endif typedef union { float f; double d; } ffi_dblfl; /* The trampoline invokes ffi_closure_ASM, and on entry, r11 holds the address of the closure. After storing the registers that could possibly contain parameters to be passed into the stack frame and setting up space for a return value, ffi_closure_ASM invokes the following helper function to do most of the work. */ int <API key>( ffi_closure* closure, void* rvalue, unsigned long* pgr, ffi_dblfl* pfr) { /* rvalue is the pointer to space for return value in closure assembly pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM. */ #if defined(__ppc__) ldu temp_ld; #endif double temp; unsigned int i; unsigned int nf = 0; /* number of FPRs already used. */ unsigned int ng = 0; /* number of GPRs already used. */ ffi_cif* cif = closure->cif; long avn = cif->nargs; void** avalue = alloca(cif->nargs * sizeof(void*)); ffi_type** arg_types = cif->arg_types; /* Copy the caller's structure return value address so that the closure returns the data directly to the caller. */ #if defined(__ppc64__) if (cif->rtype->type == FFI_TYPE_STRUCT && <API key>(cif->rtype, NULL, NULL)) #elif defined(__ppc__) if (cif->rtype->type == FFI_TYPE_STRUCT) #else #error undefined architecture #endif { rvalue = (void*)*pgr; pgr++; ng++; } /* Grab the addresses of the arguments from the stack frame. */ for (i = 0; i < avn; i++) { switch (arg_types[i]->type) { case FFI_TYPE_SINT8: case FFI_TYPE_UINT8: avalue[i] = (char*)pgr + MODE_CHOICE(3,7); ng++; pgr++; break; case FFI_TYPE_SINT16: case FFI_TYPE_UINT16: avalue[i] = (char*)pgr + MODE_CHOICE(2,6); ng++; pgr++; break; #if defined(__ppc__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT32: case FFI_TYPE_UINT32: avalue[i] = (char*)pgr + MODE_CHOICE(0,4); ng++; pgr++; break; case FFI_TYPE_STRUCT: if (cif->abi == FFI_DARWIN) { #if defined(__ppc64__) unsigned int gprSize = 0; unsigned int fprSize = 0; unsigned int savedFPRSize = fprSize; avalue[i] = alloca(arg_types[i]->size); <API key>(arg_types[i], (const char*)pgr, &gprSize, (const char*)pfr, &fprSize, &nf, avalue[i], NULL); ng += gprSize / sizeof(long); pgr += gprSize / sizeof(long); pfr += (fprSize - savedFPRSize) / sizeof(double); #elif defined(__ppc__) /* Structures that match the basic modes (QI 1 byte, HI 2 bytes, SI 4 bytes) are aligned as if they were those modes. */ unsigned int size_al = size_al = arg_types[i]->size; /* If the first member of the struct is a double, then align the struct to double-word. */ if (arg_types[i]->elements[0]->type == FFI_TYPE_DOUBLE) size_al = ALIGN(arg_types[i]->size, 8); if (size_al < 3) avalue[i] = (void*)pgr + MODE_CHOICE(4,8) - size_al; else avalue[i] = (void*)pgr; ng += (size_al + 3) / sizeof(long); pgr += (size_al + 3) / sizeof(long); #else #error undefined architecture #endif } break; #if defined(__ppc64__) case FFI_TYPE_POINTER: #endif case FFI_TYPE_SINT64: case FFI_TYPE_UINT64: /* Long long ints are passed in 1 or 2 GPRs. */ avalue[i] = pgr; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; case FFI_TYPE_FLOAT: /* A float value consumes a GPR. There are 13 64-bit floating point registers. */ if (nf < <API key>) { temp = pfr->d; pfr->f = (float)temp; avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng++; pgr++; break; case FFI_TYPE_DOUBLE: /* A double value consumes one or two GPRs. There are 13 64bit floating point registers. */ if (nf < <API key>) { avalue[i] = pfr; pfr++; } else avalue[i] = pgr; nf++; ng += MODE_CHOICE(2,1); pgr += MODE_CHOICE(2,1); break; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE case FFI_TYPE_LONGDOUBLE: #if defined(__ppc64__) if (nf < <API key>) { avalue[i] = pfr; pfr += 2; } #elif defined(__ppc__) /* A long double value consumes 2/4 GPRs and 2 FPRs. There are 13 64bit floating point registers. */ if (nf < <API key> - 1) { avalue[i] = pfr; pfr += 2; } /* Here we have the situation where one part of the long double is stored in fpr13 and the other part is already on the stack. We use a union to pass the long double to avalue[i]. */ else if (nf == <API key> - 1) { memcpy (&temp_ld.lb[0], pfr, sizeof(temp_ld.lb[0])); memcpy (&temp_ld.lb[1], pgr + 2, sizeof(temp_ld.lb[1])); avalue[i] = &temp_ld.ld; } #else #error undefined architecture #endif else avalue[i] = pgr; nf += 2; ng += MODE_CHOICE(4,2); pgr += MODE_CHOICE(4,2); break; #endif /* FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE */ default: FFI_ASSERT(0); break; } } (closure->fun)(cif, rvalue, avalue, closure->user_data); /* Tell ffi_closure_ASM to perform return type promotions. */ return cif->rtype->type; } #if defined(__ppc64__) /* <API key> Rebuild a struct's natural layout from buffers of concatenated registers. Return the number of registers used. inGPRs[0-7] == r3, inFPRs[0-7] == f1 ... */ void <API key>( const ffi_type* inType, const char* inGPRs, unsigned int* ioGPRMarker, const char* inFPRs, unsigned int* ioFPRMarker, unsigned int* ioFPRsUsed, char* outStruct, // caller-allocated unsigned int* ioStructMarker) { unsigned int srcGMarker = 0; unsigned int srcFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; unsigned int destMarker = 0; static unsigned int recurseCount = 0; if (ioGPRMarker) srcGMarker = *ioGPRMarker; if (ioFPRMarker) { srcFMarker = *ioFPRMarker; savedFMarker = srcFMarker; } if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioStructMarker) destMarker = *ioStructMarker; size_t i; switch (inType->size) { case 1: case 2: case 4: srcGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: srcFMarker = ALIGN(srcFMarker, 4); srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); if (fprsUsed < <API key>) { *(float*)&outStruct[destMarker] = (float)*(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(float*)&outStruct[destMarker] = (float)*(double*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcFMarker = ALIGN(srcFMarker, 8); destMarker = ALIGN(destMarker, 8); if (fprsUsed < <API key>) { *(double*)&outStruct[destMarker] = *(double*)&inFPRs[srcFMarker]; srcFMarker += 8; fprsUsed++; } else *(double*)&outStruct[destMarker] = *(double*)&inGPRs[srcGMarker]; destMarker += 8; // Skip next GPR srcGMarker += 8; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: destMarker = ALIGN(destMarker, 16); if (fprsUsed < <API key>) { srcFMarker = ALIGN(srcFMarker, 8); srcGMarker = ALIGN(srcGMarker, 8); *(long double*)&outStruct[destMarker] = *(long double*)&inFPRs[srcFMarker]; srcFMarker += 16; fprsUsed += 2; } else { srcFMarker = ALIGN(srcFMarker, 16); srcGMarker = ALIGN(srcGMarker, 16); *(long double*)&outStruct[destMarker] = *(long double*)&inGPRs[srcGMarker]; } destMarker += 16; // Skip next 2 GPRs srcGMarker += 16; srcGMarker = ALIGN(srcGMarker, 8); break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { if (inType->alignment == 1) // chars only { if (inType->size == 1) outStruct[destMarker++] = inGPRs[srcGMarker++]; else if (inType->size == 2) { outStruct[destMarker++] = inGPRs[srcGMarker++]; outStruct[destMarker++] = inGPRs[srcGMarker++]; i++; } else { memcpy(&outStruct[destMarker], &inGPRs[srcGMarker], inType->size); srcGMarker += inType->size; destMarker += inType->size; i += inType->size - 1; } } else // chars and other stuff { outStruct[destMarker++] = inGPRs[srcGMarker++]; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(srcGMarker, 8) - srcGMarker) < 4)) srcGMarker = ALIGN(srcGMarker, inType->alignment); // was 8 } } break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcGMarker = ALIGN(srcGMarker, 2); destMarker = ALIGN(destMarker, 2); *(short*)&outStruct[destMarker] = *(short*)&inGPRs[srcGMarker]; srcGMarker += 2; destMarker += 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcGMarker = ALIGN(srcGMarker, 4); destMarker = ALIGN(destMarker, 4); *(int*)&outStruct[destMarker] = *(int*)&inGPRs[srcGMarker]; srcGMarker += 4; destMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcGMarker = ALIGN(srcGMarker, 8); destMarker = ALIGN(destMarker, 8); *(long long*)&outStruct[destMarker] = *(long long*)&inGPRs[srcGMarker]; srcGMarker += 8; destMarker += 8; break; case FFI_TYPE_STRUCT: recurseCount++; <API key>(inType->elements[i], inGPRs, &srcGMarker, inFPRs, &srcFMarker, &fprsUsed, outStruct, &destMarker); recurseCount break; default: FFI_ASSERT(0); // unknown element type break; } } srcGMarker = ALIGN(srcGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && srcGMarker == 16) { *(long double*)&outStruct[0] = *(long double*)&inGPRs[0]; srcFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioGPRMarker) *ioGPRMarker = ALIGN(srcGMarker, 8); if (ioFPRMarker) *ioFPRMarker = srcFMarker; if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioStructMarker) *ioStructMarker = ALIGN(destMarker, 8); } /* <API key> Copy a struct's elements into buffers that can be sliced into registers. Return the sizes of the output buffers in bytes. Pass NULL buffer pointers to calculate size only. outGPRs[0-7] == r3, outFPRs[0-7] == f1 ... */ void <API key>( const ffi_type* inType, const char* inStruct, unsigned int* ioStructMarker, unsigned int* ioFPRsUsed, char* outGPRs, // caller-allocated unsigned int* ioGPRSize, char* outFPRs, // caller-allocated unsigned int* ioFPRSize) { size_t i; unsigned int srcMarker = 0; unsigned int destGMarker = 0; unsigned int destFMarker = 0; unsigned int savedFMarker = 0; unsigned int fprsUsed = 0; unsigned int savedFPRsUsed = 0; static unsigned int recurseCount = 0; if (ioStructMarker) srcMarker = *ioStructMarker; if (ioFPRsUsed) { fprsUsed = *ioFPRsUsed; savedFPRsUsed = fprsUsed; } if (ioGPRSize) destGMarker = *ioGPRSize; if (ioFPRSize) { destFMarker = *ioFPRSize; savedFMarker = destFMarker; } switch (inType->size) { case 1: case 2: case 4: destGMarker += 8 - inType->size; break; default: break; } for (i = 0; inType->elements[i] != NULL; i++) { switch (inType->elements[i]->type) { // Shadow floating-point types in GPRs for vararg and pre-ANSI // functions. case FFI_TYPE_FLOAT: // Nudge markers to next 4/8-byte boundary srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < <API key>) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = (double)*(float*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = (double)*(float*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (srcMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, 8); } break; case FFI_TYPE_DOUBLE: srcMarker = ALIGN(srcMarker, 8); destFMarker = ALIGN(destFMarker, 8); if (fprsUsed < <API key>) { if (outFPRs != NULL && inStruct != NULL) *(double*)&outFPRs[destFMarker] = *(double*)&inStruct[srcMarker]; destFMarker += 8; fprsUsed++; } if (outGPRs != NULL && inStruct != NULL) *(double*)&outGPRs[destGMarker] = *(double*)&inStruct[srcMarker]; srcMarker += 8; // Skip next GPR destGMarker += 8; destGMarker = ALIGN(destGMarker, 8); break; case FFI_TYPE_LONGDOUBLE: srcMarker = ALIGN(srcMarker, 16); if (fprsUsed < <API key>) { destFMarker = ALIGN(destFMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outFPRs != NULL && inStruct != NULL) *(long double*)&outFPRs[destFMarker] = *(long double*)&inStruct[srcMarker]; if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; destFMarker += 16; fprsUsed += 2; } else { destGMarker = ALIGN(destGMarker, 16); if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[destGMarker] = *(long double*)&inStruct[srcMarker]; } srcMarker += 16; destGMarker += 16; // Skip next 2 GPRs destGMarker = ALIGN(destGMarker, 8); // was 16 break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: if (inType->alignment == 1) // bytes only { if (inType->size == 1) { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; } else if (inType->size == 2) { if (outGPRs != NULL && inStruct != NULL) { outGPRs[destGMarker] = inStruct[srcMarker]; outGPRs[destGMarker + 1] = inStruct[srcMarker + 1]; } srcMarker += 2; destGMarker += 2; i++; } else { if (outGPRs != NULL && inStruct != NULL) { // Avoid memcpy for small chunks. if (inType->size <= sizeof(long)) *(long*)&outGPRs[destGMarker] = *(long*)&inStruct[srcMarker]; else memcpy(&outGPRs[destGMarker], &inStruct[srcMarker], inType->size); } srcMarker += inType->size; destGMarker += inType->size; i += inType->size - 1; } } else // bytes and other stuff { if (outGPRs != NULL && inStruct != NULL) outGPRs[destGMarker] = inStruct[srcMarker]; srcMarker++; destGMarker++; // Skip to next GPR if next element won't fit and we're // not already at a register boundary. if (inType->elements[i + 1] != NULL && (destGMarker % 8)) { if (!FFI_TYPE_1_BYTE(inType->elements[i + 1]->type) && (!FFI_TYPE_2_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 2) && (!FFI_TYPE_4_BYTE(inType->elements[i + 1]->type) || (ALIGN(destGMarker, 8) - destGMarker) < 4)) destGMarker = ALIGN(destGMarker, inType->alignment); // was 8 } } break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: srcMarker = ALIGN(srcMarker, 2); destGMarker = ALIGN(destGMarker, 2); if (outGPRs != NULL && inStruct != NULL) *(short*)&outGPRs[destGMarker] = *(short*)&inStruct[srcMarker]; srcMarker += 2; destGMarker += 2; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: srcMarker = ALIGN(srcMarker, 4); destGMarker = ALIGN(destGMarker, 4); if (outGPRs != NULL && inStruct != NULL) *(int*)&outGPRs[destGMarker] = *(int*)&inStruct[srcMarker]; srcMarker += 4; destGMarker += 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: srcMarker = ALIGN(srcMarker, 8); destGMarker = ALIGN(destGMarker, 8); if (outGPRs != NULL && inStruct != NULL) *(long long*)&outGPRs[destGMarker] = *(long long*)&inStruct[srcMarker]; srcMarker += 8; destGMarker += 8; if (inType->elements[i + 1] == NULL) destGMarker = ALIGN(destGMarker, inType->alignment); break; case FFI_TYPE_STRUCT: recurseCount++; <API key>(inType->elements[i], inStruct, &srcMarker, &fprsUsed, outGPRs, &destGMarker, outFPRs, &destFMarker); recurseCount break; default: FFI_ASSERT(0); break; } } destGMarker = ALIGN(destGMarker, inType->alignment); // Take care of the special case for 16-byte structs, but not for // nested structs. if (recurseCount == 0 && destGMarker == 16) { if (outGPRs != NULL && inStruct != NULL) *(long double*)&outGPRs[0] = *(long double*)&inStruct[0]; destFMarker = savedFMarker; fprsUsed = savedFPRsUsed; } if (ioStructMarker) *ioStructMarker = ALIGN(srcMarker, 8); if (ioFPRsUsed) *ioFPRsUsed = fprsUsed; if (ioGPRSize) *ioGPRSize = ALIGN(destGMarker, 8); if (ioFPRSize) *ioFPRSize = ALIGN(destFMarker, 8); } /* <API key> Determine whether a returned struct needs a pointer in r3 or can fit in registers. */ bool <API key>( const ffi_type* inType, unsigned short* ioGPRCount, unsigned short* ioFPRCount) { // Obvious case first- struct is larger than combined FPR size. if (inType->size > 14 * 8) return true; // Now the struct can physically fit in registers, determine if it // also fits logically. bool needsPtr = false; unsigned short gprsUsed = 0; unsigned short fprsUsed = 0; size_t i; if (ioGPRCount) gprsUsed = *ioGPRCount; if (ioFPRCount) fprsUsed = *ioFPRCount; for (i = 0; inType->elements[i] != NULL && !needsPtr; i++) { switch (inType->elements[i]->type) { case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: gprsUsed++; fprsUsed++; if (fprsUsed > 13) needsPtr = true; break; case FFI_TYPE_LONGDOUBLE: gprsUsed += 2; fprsUsed += 2; if (fprsUsed > 14) needsPtr = true; break; case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: { gprsUsed++; if (gprsUsed > 8) { needsPtr = true; break; } if (inType->elements[i + 1] == NULL) // last byte in the struct break; // Count possible contiguous bytes ahead, up to 8. unsigned short j; for (j = 1; j < 8; j++) { if (inType->elements[i + j] == NULL || !FFI_TYPE_1_BYTE(inType->elements[i + j]->type)) break; } i += j - 1; // allow for i++ before the test condition break; } case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: gprsUsed++; if (gprsUsed > 8) needsPtr = true; break; case FFI_TYPE_STRUCT: needsPtr = <API key>( inType->elements[i], &gprsUsed, &fprsUsed); break; default: FFI_ASSERT(0); break; } } if (ioGPRCount) *ioGPRCount = gprsUsed; if (ioFPRCount) *ioFPRCount = fprsUsed; return needsPtr; } /* ffi64_data_size Calculate the size in bytes of an ffi type. */ unsigned int ffi64_data_size( const ffi_type* inType) { unsigned int size = 0; switch (inType->type) { case FFI_TYPE_UINT8: case FFI_TYPE_SINT8: size = 1; break; case FFI_TYPE_UINT16: case FFI_TYPE_SINT16: size = 2; break; case FFI_TYPE_INT: case FFI_TYPE_UINT32: case FFI_TYPE_SINT32: case FFI_TYPE_FLOAT: size = 4; break; case FFI_TYPE_POINTER: case FFI_TYPE_UINT64: case FFI_TYPE_SINT64: case FFI_TYPE_DOUBLE: size = 8; break; case FFI_TYPE_LONGDOUBLE: size = 16; break; case FFI_TYPE_STRUCT: <API key>( inType, NULL, NULL, NULL, NULL, &size, NULL, NULL); break; case FFI_TYPE_VOID: break; default: FFI_ASSERT(0); break; } return size; } #endif /* defined(__ppc64__) */ #endif /* __ppc__ || __ppc64__ */
#include <ctype.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/utsname.h> #include "request.h" #include "request_context.h" #include "<API key>.h" #include "util.h" #define USER_AGENT_SIZE 256 #define REQUEST_STACK_SIZE 32 static char userAgentG[USER_AGENT_SIZE]; static pthread_mutex_t requestStackMutexG; static Request *requestStackG[REQUEST_STACK_SIZE]; static int requestStackCountG; char defaultHostNameG[<API key>]; typedef struct <API key> { // All x-amz- headers, in normalized form (i.e. NAME: VALUE, no other ws) char *amzHeaders[<API key> + 2]; // + 2 for acl and date // The number of x-amz- headers int amzHeadersCount; // Storage for amzHeaders (the +256 is for x-amz-acl and x-amz-date) char amzHeadersRaw[<API key> + 256 + 1]; // Canonicalized x-amz- headers string_multibuffer(<API key>, <API key> + 256 + 1); // URL-Encoded key char urlEncodedKey[<API key> + 1]; // Canonicalized resource char <API key>[<API key> + 1]; // Cache-Control header (or empty) char cacheControlHeader[128]; // Content-Type header (or empty) char contentTypeHeader[128]; // Content-MD5 header (or empty) char md5Header[128]; // Content-Disposition header (or empty) char <API key>[128]; // Content-Encoding header (or empty) char <API key>[128]; // Expires header (or empty) char expiresHeader[128]; // If-Modified-Since header char <API key>[128]; // If-Unmodified-Since header char <API key>[128]; // If-Match header char ifMatchHeader[128]; // If-None-Match header char ifNoneMatchHeader[128]; // Range header char rangeHeader[128]; // Authorization header char authorizationHeader[128]; } <API key>; // Called whenever we detect that the request headers have been completely // processed; which happens either when we get our first read/write callback, // or the request is finished being procesed. Returns nonzero on success, // zero on failure. static void <API key>(Request *request) { if (request-><API key>) { return; } request-><API key> = 1; // Get the http response code long httpResponseCode; request->httpResponseCode = 0; if (curl_easy_getinfo(request->curl, <API key>, &httpResponseCode) != CURLE_OK) { // Not able to get the HTTP response code - error request->status = <API key>; return; } else { request->httpResponseCode = httpResponseCode; } <API key>(&(request-><API key>), request->curl); // Only make the callback if it was a successful request; otherwise we're // returning information about the error response itself if (request->propertiesCallback && (request->httpResponseCode >= 200) && (request->httpResponseCode <= 299)) { request->status = (*(request->propertiesCallback)) (&(request-><API key>.responseProperties), request->callbackData); } } static size_t curl_header_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; <API key> (&(request-><API key>), (char *) ptr, len); return len; } static size_t curl_read_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; // CURL may call this function before response headers are available, // so don't assume response headers are available and attempt to parse // them. Leave that to curl_write_func, which is guaranteed to be called // only after headers are available. if (request->status != S3StatusOK) { return CURL_READFUNC_ABORT; } // If there is no data callback, or the data callback has already returned // contentLength bytes, return 0; if (!request->toS3Callback || !request-><API key>) { return 0; } // Don't tell the callback that we are willing to accept more data than we // really are if (len > request-><API key>) { len = request-><API key>; } // Otherwise, make the data callback int ret = (*(request->toS3Callback)) (len, (char *) ptr, request->callbackData); if (ret < 0) { request->status = <API key>; return CURL_READFUNC_ABORT; } else { if (ret > request-><API key>) { ret = request-><API key>; } request-><API key> -= ret; return ret; } } static size_t curl_write_func(void *ptr, size_t size, size_t nmemb, void *data) { Request *request = (Request *) data; int len = size * nmemb; <API key>(request); if (request->status != S3StatusOK) { return 0; } // On HTTP error, we expect to parse an HTTP error response if ((request->httpResponseCode < 200) || (request->httpResponseCode > 299)) { request->status = error_parser_add (&(request->errorParser), (char *) ptr, len); } // If there was a callback registered, make it else if (request->fromS3Callback) { request->status = (*(request->fromS3Callback)) (len, (char *) ptr, request->callbackData); } // Else, consider this an error - S3 has sent back data when it was not // expected else { request->status = <API key>; } return ((request->status == S3StatusOK) ? len : 0); } // This function 'normalizes' all x-amz-meta headers provided in // params->requestHeaders, which means it removes all whitespace from // them such that they all look exactly like this: // x-amz-meta-${NAME}: ${VALUE} // It also adds the x-amz-acl, x-amz-copy-source, <API key>, // and <API key> headers if necessary, and always adds the // x-amz-date header. It copies the raw string values into // params->amzHeadersRaw, and creates an array of string pointers representing // these headers in params->amzHeaders (and also sets params->amzHeadersCount // to be the count of the total number of x-amz- headers thus created). static S3Status compose_amz_headers(const RequestParams *params, <API key> *values) { const S3PutProperties *properties = params->putProperties; values->amzHeadersCount = 0; values->amzHeadersRaw[0] = 0; int len = 0; // Append a header to amzHeaders, trimming whitespace from the end. // Does NOT trim whitespace from the beginning. #define headers_append(isNewHeader, format, ...) \ do { \ if (isNewHeader) { \ values->amzHeaders[values->amzHeadersCount++] = \ &(values->amzHeadersRaw[len]); \ } \ len += snprintf(&(values->amzHeadersRaw[len]), \ sizeof(values->amzHeadersRaw) - len, \ format, __VA_ARGS__); \ if (len >= (int) sizeof(values->amzHeadersRaw)) { \ return <API key>; \ } \ while ((len > 0) && (values->amzHeadersRaw[len - 1] == ' ')) { \ len } \ values->amzHeadersRaw[len++] = 0; \ } while (0) #define <API key>(str, l) \ do { \ values->amzHeaders[values->amzHeadersCount++] = \ &(values->amzHeadersRaw[len]); \ if ((len + l) >= (int) sizeof(values->amzHeadersRaw)) { \ return <API key>; \ } \ int todo = l; \ while (todo if ((*(str) >= 'A') && (*(str) <= 'Z')) { \ values->amzHeadersRaw[len++] = 'a' + (*(str) - 'A'); \ } \ else { \ values->amzHeadersRaw[len++] = *(str); \ } \ (str)++; \ } \ } while (0) // Check and copy in the x-amz-meta headers if (properties) { int i; for (i = 0; i < properties->metaDataCount; i++) { const S3NameValue *property = &(properties->metaData[i]); char headerName[<API key> - sizeof(": v")]; int l = snprintf(headerName, sizeof(headerName), <API key> "%s", property->name); char *hn = headerName; <API key>(hn, l); // Copy in the value headers_append(0, ": %s", property->value); } // Add the x-amz-acl header, if necessary const char *cannedAclString; switch (properties->cannedAcl) { case S3CannedAclPrivate: cannedAclString = 0; break; case <API key>: cannedAclString = "public-read"; break; case <API key>: cannedAclString = "public-read-write"; break; default: // <API key> cannedAclString = "authenticated-read"; break; } if (cannedAclString) { headers_append(1, "x-amz-acl: %s", cannedAclString); } // Add the <API key> header, if necessary if (properties-><API key>) { headers_append(1, "<API key>: %s", "AES256"); } } // Add the x-amz-date header time_t now = time(NULL); char date[64]; strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now)); headers_append(1, "x-amz-date: %s", date); if (params->httpRequestType == HttpRequestTypeCOPY) { // Add the x-amz-copy-source header if (params-><API key> && params-><API key>[0] && params->copySourceKey && params->copySourceKey[0]) { headers_append(1, "x-amz-copy-source: /%s/%s", params-><API key>, params->copySourceKey); } // And the <API key> header if (properties) { headers_append(1, "%s", "<API key>: REPLACE"); } } return S3StatusOK; } // Composes the other headers static S3Status <API key>(const RequestParams *params, <API key> *values) { #define do_put_header(fmt, sourceField, destField, badError, tooLongError) \ do { \ if (params->putProperties && \ params->putProperties-> sourceField && \ params->putProperties-> sourceField[0]) { \ /* Skip whitespace at beginning of val */ \ const char *val = params->putProperties-> sourceField; \ while (*val && is_blank(*val)) { \ val++; \ } \ if (!*val) { \ return badError; \ } \ /* Compose header, make sure it all fit */ \ int len = snprintf(values-> destField, \ sizeof(values-> destField), fmt, val); \ if (len >= (int) sizeof(values-> destField)) { \ return tooLongError; \ } \ /* Now remove the whitespace at the end */ \ while (is_blank(values-> destField[len])) { \ len } \ values-> destField[len] = 0; \ } \ else { \ values-> destField[0] = 0; \ } \ } while (0) #define do_get_header(fmt, sourceField, destField, badError, tooLongError) \ do { \ if (params->getConditions && \ params->getConditions-> sourceField && \ params->getConditions-> sourceField[0]) { \ /* Skip whitespace at beginning of val */ \ const char *val = params->getConditions-> sourceField; \ while (*val && is_blank(*val)) { \ val++; \ } \ if (!*val) { \ return badError; \ } \ /* Compose header, make sure it all fit */ \ int len = snprintf(values-> destField, \ sizeof(values-> destField), fmt, val); \ if (len >= (int) sizeof(values-> destField)) { \ return tooLongError; \ } \ /* Now remove the whitespace at the end */ \ while (is_blank(values-> destField[len])) { \ len } \ values-> destField[len] = 0; \ } \ else { \ values-> destField[0] = 0; \ } \ } while (0) // Cache-Control do_put_header("Cache-Control: %s", cacheControl, cacheControlHeader, <API key>, <API key>); // ContentType do_put_header("Content-Type: %s", contentType, contentTypeHeader, <API key>, <API key>); // MD5 do_put_header("Content-MD5: %s", md5, md5Header, S3StatusBadMD5, S3StatusMD5TooLong); // Content-Disposition do_put_header("Content-Disposition: attachment; filename=\"%s\"", <API key>, <API key>, <API key>, <API key>); // ContentEncoding do_put_header("Content-Encoding: %s", contentEncoding, <API key>, <API key>, <API key>); // Expires if (params->putProperties && (params->putProperties->expires >= 0)) { time_t t = (time_t) params->putProperties->expires; strftime(values->expiresHeader, sizeof(values->expiresHeader), "Expires: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values->expiresHeader[0] = 0; } // If-Modified-Since if (params->getConditions && (params->getConditions->ifModifiedSince >= 0)) { time_t t = (time_t) params->getConditions->ifModifiedSince; strftime(values-><API key>, sizeof(values-><API key>), "If-Modified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values-><API key>[0] = 0; } // If-Unmodified-Since header if (params->getConditions && (params->getConditions->ifNotModifiedSince >= 0)) { time_t t = (time_t) params->getConditions->ifNotModifiedSince; strftime(values-><API key>, sizeof(values-><API key>), "If-Unmodified-Since: %a, %d %b %Y %H:%M:%S UTC", gmtime(&t)); } else { values-><API key>[0] = 0; } // If-Match header do_get_header("If-Match: %s", ifMatchETag, ifMatchHeader, <API key>, <API key>); // If-None-Match header do_get_header("If-None-Match: %s", ifNotMatchETag, ifNoneMatchHeader, <API key>, <API key>); // Range header if (params->startByte || params->byteCount) { if (params->byteCount) { snprintf(values->rangeHeader, sizeof(values->rangeHeader), "Range: bytes=%llu-%llu", (unsigned long long) params->startByte, (unsigned long long) (params->startByte + params->byteCount - 1)); } else { snprintf(values->rangeHeader, sizeof(values->rangeHeader), "Range: bytes=%llu-", (unsigned long long) params->startByte); } } else { values->rangeHeader[0] = 0; } return S3StatusOK; } // URL encodes the params->key value into params->urlEncodedKey static S3Status encode_key(const RequestParams *params, <API key> *values) { return (urlEncode(values->urlEncodedKey, params->key, S3_MAX_KEY_SIZE) ? S3StatusOK : S3StatusUriTooLong); } // Simple comparison function for comparing two HTTP header names that are // embedded within an HTTP header line, returning true if header1 comes // before header2 alphabetically, false if not static int headerle(const char *header1, const char *header2) { while (1) { if (*header1 == ':') { return (*header2 != ':'); } else if (*header2 == ':') { return 0; } else if (*header2 < *header1) { return 0; } else if (*header2 > *header1) { return 1; } header1++, header2++; } } // Replace this with merge sort eventually, it's the best stable sort. But // since typically the number of elements being sorted is small, it doesn't // matter that much which sort is used, and gnome sort is the world's simplest // stable sort. Added a slight twist to the standard gnome_sort - don't go // forward +1, go forward to the last highest index considered. This saves // all the string comparisons that would be done "going forward", and thus // only does the necessary string comparisons to move values back into their // sorted position. static void header_gnome_sort(const char **headers, int size) { int i = 0, last_highest = 0; while (i < size) { if ((i == 0) || headerle(headers[i - 1], headers[i])) { i = ++last_highest; } else { const char *tmp = headers[i]; headers[i] = headers[i - 1]; headers[--i] = tmp; } } } // Canonicalizes the x-amz- headers into the <API key> buffer static void <API key>(<API key> *values) { // Make a copy of the headers that will be sorted const char *sortedHeaders[<API key>]; memcpy(sortedHeaders, values->amzHeaders, (values->amzHeadersCount * sizeof(sortedHeaders[0]))); // Now sort these header_gnome_sort(sortedHeaders, values->amzHeadersCount); // Now copy this sorted list into the buffer, all the while: // - folding repeated headers into single lines, and // - folding multiple lines // - removing the space after the colon int lastHeaderLen = 0, i; char *buffer = values-><API key>; for (i = 0; i < values->amzHeadersCount; i++) { const char *header = sortedHeaders[i]; const char *c = header; // If the header names are the same, append the next value if ((i > 0) && !strncmp(header, sortedHeaders[i - 1], lastHeaderLen)) { // Replacing the previous newline with a comma *(buffer - 1) = ','; // Skip the header name and space c += (lastHeaderLen + 1); } // Else this is a new header else { // Copy in everything up to the space in the ": " while (*c != ' ') { *buffer++ = *c++; } // Save the header len since it's a new header lastHeaderLen = c - header; // Skip the space c++; } // Now copy in the value, folding the lines while (*c) { // If c points to a \r\n[whitespace] sequence, then fold // this newline out if ((*c == '\r') && (*(c + 1) == '\n') && is_blank(*(c + 2))) { c += 3; while (is_blank(*c)) { c++; } // Also, what has most recently been copied into buffer amy // have been whitespace, and since we're folding whitespace // out around this newline sequence, back buffer up over // any whitespace it contains while (is_blank(*(buffer - 1))) { buffer } continue; } *buffer++ = *c++; } // Finally, add the newline *buffer++ = '\n'; } // Terminate the buffer *buffer = 0; } // Canonicalizes the resource into params-><API key> static void <API key>(const char *bucketName, const char *subResource, const char *urlEncodedKey, char *buffer) { int len = 0; *buffer = 0; #define append(str) len += sprintf(&(buffer[len]), "%s", str) if (bucketName && bucketName[0]) { buffer[len++] = '/'; append(bucketName); } append("/"); if (urlEncodedKey && urlEncodedKey[0]) { append(urlEncodedKey); } if (subResource && subResource[0]) { append("?"); append(subResource); } } // Convert an HttpRequestType to an HTTP Verb string static const char *<API key>(HttpRequestType requestType) { switch (requestType) { case HttpRequestTypeGET: return "GET"; case HttpRequestTypeHEAD: return "HEAD"; case HttpRequestTypePUT: case HttpRequestTypeCOPY: return "PUT"; default: // <API key> return "DELETE"; } } // Composes the Authorization header for the request static S3Status compose_auth_header(const RequestParams *params, <API key> *values) { // We allow for: // 17 bytes for HTTP-Verb + \n // 129 bytes for Content-MD5 + \n // 129 bytes for Content-Type + \n // 1 byte for empty Date + \n // <API key> & <API key> char signbuf[17 + 129 + 129 + 1 + (sizeof(values-><API key>) - 1) + (sizeof(values-><API key>) - 1) + 1]; int len = 0; #define signbuf_append(format, ...) \ len += snprintf(&(signbuf[len]), sizeof(signbuf) - len, \ format, __VA_ARGS__) signbuf_append ("%s\n", <API key>(params->httpRequestType)); // For MD5 and Content-Type, use the value in the actual header, because // it's already been trimmed signbuf_append("%s\n", values->md5Header[0] ? &(values->md5Header[sizeof("Content-MD5: ") - 1]) : ""); signbuf_append ("%s\n", values->contentTypeHeader[0] ? &(values->contentTypeHeader[sizeof("Content-Type: ") - 1]) : ""); signbuf_append("%s", "\n"); // Date - we always use x-amz-date signbuf_append("%s", values-><API key>); signbuf_append("%s", values-><API key>); // Generate an HMAC-SHA-1 of the signbuf unsigned char hmac[20]; HMAC_SHA1(hmac, (unsigned char *) params->bucketContext.secretAccessKey, strlen(params->bucketContext.secretAccessKey), (unsigned char *) signbuf, len); // Now base-64 encode the results char b64[((20 + 1) * 4) / 3]; int b64Len = base64Encode(hmac, 20, b64); snprintf(values->authorizationHeader, sizeof(values->authorizationHeader), "Authorization: AWS %s:%.*s", params->bucketContext.accessKeyId, b64Len, b64); return S3StatusOK; } // Compose the URI to use for the request given the request parameters static S3Status compose_uri(char *buffer, int bufferSize, const S3BucketContext *bucketContext, const char *urlEncodedKey, const char *subResource, const char *queryParams) { int len = 0; #define uri_append(fmt, ...) \ do { \ len += snprintf(&(buffer[len]), bufferSize - len, fmt, __VA_ARGS__); \ if (len >= bufferSize) { \ return S3StatusUriTooLong; \ } \ } while (0) uri_append("http%s: (bucketContext->protocol == S3ProtocolHTTP) ? "" : "s"); const char *hostName = bucketContext->hostName ? bucketContext->hostName : defaultHostNameG; if (bucketContext->bucketName && bucketContext->bucketName[0]) { if (bucketContext->uriStyle == <API key>) { uri_append("%s.%s", bucketContext->bucketName, hostName); } else { uri_append("%s/%s", hostName, bucketContext->bucketName); } } else { uri_append("%s", hostName); } uri_append("%s", "/"); uri_append("%s", urlEncodedKey); if (subResource && subResource[0]) { uri_append("?%s", subResource); } if (queryParams) { uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?", queryParams); } return S3StatusOK; } // Sets up the curl handle given the completely computed RequestParams static S3Status setup_curl(Request *request, const RequestParams *params, const <API key> *values) { CURLcode status; #define <API key>(opt, val) \ if ((status = curl_easy_setopt \ (request->curl, opt, val)) != CURLE_OK) { \ return <API key>; \ } // Debugging only // <API key>(CURLOPT_VERBOSE, 1); // Set private data to request for the benefit of S3RequestContext <API key>(CURLOPT_PRIVATE, request); // Set header callback and data <API key>(CURLOPT_HEADERDATA, request); <API key>(<API key>, &curl_header_func); // Set read callback, data, and readSize <API key>(<API key>, &curl_read_func); <API key>(CURLOPT_READDATA, request); // Set write callback and data <API key>(<API key>, &curl_write_func); <API key>(CURLOPT_WRITEDATA, request); // Ask curl to parse the Last-Modified header. This is easier than // parsing it ourselves. <API key>(CURLOPT_FILETIME, 1); // Curl docs suggest that this is necessary for multithreaded code. // However, it also points out that DNS timeouts will not be honored // during DNS lookup, which can be worked around by using the c-ares // library, which we do not do yet. <API key>(CURLOPT_NOSIGNAL, 1); // Turn off Curl's built-in progress meter <API key>(CURLOPT_NOPROGRESS, 1); // xxx todo - support setting the proxy for Curl to use (can't use https // for proxies though) // xxx todo - support setting the network interface for Curl to use // I think this is useful - we don't need interactive performance, we need // to complete large operations quickly <API key>(CURLOPT_TCP_NODELAY, 1); // Don't use Curl's 'netrc' feature <API key>(CURLOPT_NETRC, CURL_NETRC_IGNORED); // Don't verify S3's certificate, there are known to be issues with // them sometimes // xxx todo - support an option for verifying the S3 CA (default false) <API key>(<API key>, 0); // Follow any redirection directives that S3 sends <API key>(<API key>, 1); // A safety valve in case S3 goes bananas with redirects <API key>(CURLOPT_MAXREDIRS, 10); // Set the User-Agent; maybe Amazon will track these? <API key>(CURLOPT_USERAGENT, userAgentG); // Set the low speed limit and time; we abort transfers that stay at // less than 1K per second for more than 15 seconds. // xxx todo - make these configurable // xxx todo - allow configurable max send and receive speed <API key>(<API key>, 1024); <API key>(<API key>, 15); // Append standard headers #define <API key>(fieldName) \ if (values-> fieldName [0]) { \ request->headers = curl_slist_append(request->headers, \ values-> fieldName); \ } // Would use <API key>, but it is buggy in libcurl if (params->httpRequestType == HttpRequestTypePUT) { char header[256]; snprintf(header, sizeof(header), "Content-Length: %llu", (unsigned long long) params-><API key>); request->headers = curl_slist_append(request->headers, header); request->headers = curl_slist_append(request->headers, "Transfer-Encoding:"); } else if (params->httpRequestType == HttpRequestTypeCOPY) { request->headers = curl_slist_append(request->headers, "Transfer-Encoding:"); } <API key>(cacheControlHeader); <API key>(contentTypeHeader); <API key>(md5Header); <API key>(<API key>); <API key>(<API key>); <API key>(expiresHeader); <API key>(<API key>); <API key>(<API key>); <API key>(ifMatchHeader); <API key>(ifNoneMatchHeader); <API key>(rangeHeader); <API key>(authorizationHeader); // Append x-amz- headers int i; for (i = 0; i < values->amzHeadersCount; i++) { request->headers = curl_slist_append(request->headers, values->amzHeaders[i]); } // Set the HTTP headers <API key>(CURLOPT_HTTPHEADER, request->headers); // Set URI <API key>(CURLOPT_URL, request->uri); // Set request type. switch (params->httpRequestType) { case HttpRequestTypeHEAD: <API key>(CURLOPT_NOBODY, 1); break; case HttpRequestTypePUT: case HttpRequestTypeCOPY: <API key>(CURLOPT_UPLOAD, 1); break; case <API key>: <API key>(<API key>, "DELETE"); break; default: // HttpRequestTypeGET break; } return S3StatusOK; } static void <API key>(Request *request) { if (request->headers) { curl_slist_free_all(request->headers); } <API key>(&(request->errorParser)); // curl_easy_reset prevents connections from being re-used for some // reason. This makes HTTP Keep-Alive meaningless and is very bad for // performance. But it is necessary to allow curl to work properly. // xxx todo figure out why curl_easy_reset(request->curl); } static S3Status request_get(const RequestParams *params, const <API key> *values, Request **reqReturn) { Request *request = 0; // Try to get one from the request stack. We hold the lock for the // shortest time possible here. pthread_mutex_lock(&requestStackMutexG); if (requestStackCountG) { request = requestStackG[--requestStackCountG]; } <API key>(&requestStackMutexG); // If we got one, deinitialize it for re-use if (request) { <API key>(request); } // Else there wasn't one available in the request stack, so create one else { if (!(request = (Request *) malloc(sizeof(Request)))) { return S3StatusOutOfMemory; } if (!(request->curl = curl_easy_init())) { free(request); return <API key>; } } // Initialize the request request->prev = 0; request->next = 0; // Request status is initialized to no error, will be updated whenever // an error occurs request->status = S3StatusOK; S3Status status; // Start out with no headers request->headers = 0; // Compute the URL if ((status = compose_uri (request->uri, sizeof(request->uri), &(params->bucketContext), values->urlEncodedKey, params->subResource, params->queryParams)) != S3StatusOK) { curl_easy_cleanup(request->curl); free(request); return status; } // Set all of the curl handle options if ((status = setup_curl(request, params, values)) != S3StatusOK) { curl_easy_cleanup(request->curl); free(request); return status; } request->propertiesCallback = params->propertiesCallback; request->toS3Callback = params->toS3Callback; request-><API key> = params-><API key>; request->fromS3Callback = params->fromS3Callback; request->completeCallback = params->completeCallback; request->callbackData = params->callbackData; <API key>(&(request-><API key>)); request-><API key> = 0; <API key>(&(request->errorParser)); *reqReturn = request; return S3StatusOK; } static void request_destroy(Request *request) { <API key>(request); curl_easy_cleanup(request->curl); free(request); } static void request_release(Request *request) { pthread_mutex_lock(&requestStackMutexG); // If the request stack is full, destroy this one if (requestStackCountG == REQUEST_STACK_SIZE) { <API key>(&requestStackMutexG); request_destroy(request); } // Else put this one at the front of the request stack; we do this because // we want the most-recently-used curl handle to be re-used on the next // request, to maximize our chances of re-using a TCP connection before it // times out else { requestStackG[requestStackCountG++] = request; <API key>(&requestStackMutexG); } } S3Status <API key>(const char *userAgentInfo, int flags, const char *defaultHostName) { if (curl_global_init(CURL_GLOBAL_ALL & ~((flags & S3_INIT_WINSOCK) ? 0 : CURL_GLOBAL_WIN32)) != CURLE_OK) { return <API key>; } if (!defaultHostName) { defaultHostName = S3_DEFAULT_HOSTNAME; } if (snprintf(defaultHostNameG, <API key>, "%s", defaultHostName) >= <API key>) { return S3StatusUriTooLong; } pthread_mutex_init(&requestStackMutexG, 0); requestStackCountG = 0; if (!userAgentInfo || !*userAgentInfo) { userAgentInfo = "Unknown"; } char platform[96]; struct utsname utsn; if (uname(&utsn)) { strncpy(platform, "Unknown", sizeof(platform)); // Because strncpy doesn't always zero terminate platform[sizeof(platform) - 1] = 0; } else { snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname, utsn.machine[0] ? " " : "", utsn.machine); } snprintf(userAgentG, sizeof(userAgentG), "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)", userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform); return S3StatusOK; } void <API key>() { <API key>(&requestStackMutexG); while (requestStackCountG request_destroy(requestStackG[requestStackCountG]); } } void request_perform(const RequestParams *params, S3RequestContext *context) { Request *request; S3Status status; #define return_status(status) \ (*(params->completeCallback))(status, 0, params->callbackData); \ return // These will hold the computed values <API key> computed; // Validate the bucket name if (params->bucketContext.bucketName && ((status = <API key> (params->bucketContext.bucketName, params->bucketContext.uriStyle)) != S3StatusOK)) { return_status(status); } // Compose the amz headers if ((status = compose_amz_headers(params, &computed)) != S3StatusOK) { return_status(status); } // Compose standard headers if ((status = <API key> (params, &computed)) != S3StatusOK) { return_status(status); } // URL encode the key if ((status = encode_key(params, &computed)) != S3StatusOK) { return_status(status); } // Compute the canonicalized amz headers <API key>(&computed); // Compute the canonicalized resource <API key>(params->bucketContext.bucketName, params->subResource, computed.urlEncodedKey, computed.<API key>); // Compose Authorization header if ((status = compose_auth_header(params, &computed)) != S3StatusOK) { return_status(status); } // Get an initialized Request structure now if ((status = request_get(params, &computed, &request)) != S3StatusOK) { return_status(status); } // If a RequestContext was provided, add the request to the curl multi if (context) { CURLMcode code = <API key>(context->curlm, request->curl); if (code == CURLM_OK) { if (context->requests) { request->prev = context->requests->prev; request->next = context->requests; context->requests->prev->next = request; context->requests->prev = request; } else { context->requests = request->next = request->prev = request; } } else { if (request->status == S3StatusOK) { request->status = (code == CURLM_OUT_OF_MEMORY) ? S3StatusOutOfMemory : <API key>; } request_finish(request); } } // Else, perform the request immediately else { CURLcode code = curl_easy_perform(request->curl); if ((code != CURLE_OK) && (request->status == S3StatusOK)) { request->status = <API key>(code); } // Finish the request, ensuring that all callbacks have been made, and // also releases the request request_finish(request); } } void request_finish(Request *request) { // If we haven't detected this already, we now know that the headers are // definitely done being read in <API key>(request); // If there was no error processing the request, then possibly there was // an S3 error parsed, which should be converted into the request status if (request->status == S3StatusOK) { <API key>(&(request->errorParser), &(request->status)); // If there still was no error recorded, then it is possible that // there was in fact an error but that there was no error XML // detailing the error if ((request->status == S3StatusOK) && ((request->httpResponseCode < 200) || (request->httpResponseCode > 299))) { switch (request->httpResponseCode) { case 0: // This happens if the request never got any HTTP response // headers at all, we call this a ConnectionFailed error request->status = <API key>; break; case 100: // Some versions of libcurl erroneously set HTTP // status to this break; case 301: request->status = <API key>; break; case 307: request->status = <API key>; break; case 400: request->status = <API key>; break; case 403: request->status = <API key>; break; case 404: request->status = <API key>; break; case 405: request->status = <API key>; break; case 409: request->status = <API key>; break; case 411: request->status = <API key>; break; case 412: request->status = <API key>; break; case 416: request->status = <API key>; break; case 500: request->status = <API key>; break; case 501: request->status = <API key>; break; case 503: request->status = <API key>; break; default: request->status = <API key>; break; } } } (*(request->completeCallback)) (request->status, &(request->errorParser.s3ErrorDetails), request->callbackData); request_release(request); } S3Status <API key>(CURLcode code) { switch (code) { case CURLE_OUT_OF_MEMORY: return S3StatusOutOfMemory; case <API key>: case <API key>: return <API key>; case <API key>: return <API key>; case CURLE_WRITE_ERROR: case <API key>: return <API key>; case CURLE_PARTIAL_FILE: return S3StatusOK; case CURLE_SSL_CACERT: return <API key>; default: return <API key>; } } S3Status S3_generate_<API key> (char *buffer, const S3BucketContext *bucketContext, const char *key, int64_t expires, const char *resource) { #define MAX_EXPIRES (((int64_t) 1 << 31) - 1) // S3 seems to only accept expiration dates up to the number of seconds // representably by a signed 32-bit integer if (expires < 0) { expires = MAX_EXPIRES; } else if (expires > MAX_EXPIRES) { expires = MAX_EXPIRES; } // xxx todo: rework this so that it can be incorporated into shared code // with request_perform(). It's really unfortunate that this code is not // shared with request_perform(). // URL encode the key char urlEncodedKey[S3_MAX_KEY_SIZE * 3]; if (key) { urlEncode(urlEncodedKey, key, strlen(key)); } else { urlEncodedKey[0] = 0; } // Compute canonicalized resource char <API key>[<API key>]; <API key>(bucketContext->bucketName, resource, urlEncodedKey, <API key>); // We allow for: // 17 bytes for HTTP-Verb + \n // 1 byte for empty Content-MD5 + \n // 1 byte for empty Content-Type + \n // 20 bytes for Expires + \n // 0 bytes for <API key> // <API key> char signbuf[17 + 1 + 1 + 1 + 20 + sizeof(<API key>) + 1]; int len = 0; #define signbuf_append(format, ...) \ len += snprintf(&(signbuf[len]), sizeof(signbuf) - len, \ format, __VA_ARGS__) signbuf_append("%s\n", "GET"); // HTTP-Verb signbuf_append("%s\n", ""); // Content-MD5 signbuf_append("%s\n", ""); // Content-Type signbuf_append("%llu\n", (unsigned long long) expires); signbuf_append("%s", <API key>); // Generate an HMAC-SHA-1 of the signbuf unsigned char hmac[20]; HMAC_SHA1(hmac, (unsigned char *) bucketContext->secretAccessKey, strlen(bucketContext->secretAccessKey), (unsigned char *) signbuf, len); // Now base-64 encode the results char b64[((20 + 1) * 4) / 3]; int b64Len = base64Encode(hmac, 20, b64); // Now urlEncode that char signature[sizeof(b64) * 3]; urlEncode(signature, b64, b64Len); // Finally, compose the uri, with params: // ?AWSAccessKeyId=xxx[&Expires=]&Signature=xxx char queryParams[sizeof("AWSAccessKeyId=") + 20 + sizeof("&Expires=") + 20 + sizeof("&Signature=") + sizeof(signature) + 1]; sprintf(queryParams, "AWSAccessKeyId=%s&Expires=%ld&Signature=%s", bucketContext->accessKeyId, (long) expires, signature); return compose_uri(buffer, S3_MAX_<API key>, bucketContext, urlEncodedKey, resource, queryParams); }
package system // import "github.com/docker/docker/pkg/system" import ( "os" "path/filepath" "regexp" "strconv" "strings" "sync" "syscall" "time" "unsafe" winio "github.com/Microsoft/go-winio" "golang.org/x/sys/windows" ) const ( // <API key> is local administrators plus NT AUTHORITY\System <API key> = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" ) // MkdirAllWithACL is a wrapper for MkdirAll that creates a directory // with an appropriate SDDL defined ACL. func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { return mkdirall(path, true, sddl) } // MkdirAll implementation that is volume path aware for Windows. It can be used // as a drop-in replacement for os.MkdirAll() func MkdirAll(path string, _ os.FileMode) error { return mkdirall(path, false, "") } // mkdirall is a custom version of os.MkdirAll modified for use on Windows // so that it is both volume path aware, and can create a directory with // a DACL. func mkdirall(path string, applyACL bool, sddl string) error { if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { return nil } // The rest of this method is largely copied from os.MkdirAll and should be kept // as-is to ensure compatibility. // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{ Op: "mkdir", Path: path, Err: syscall.ENOTDIR, } } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j } if j > 1 { // Create parent err = mkdirall(path[0:j-1], false, sddl) if err != nil { return err } } // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. if applyACL { err = mkdirWithACL(path, sddl) } else { err = os.Mkdir(path, 0) } if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil } // mkdirWithACL creates a new directory. If there is an error, it will be of // type *PathError. . // This is a modified and combined version of os.Mkdir and windows.Mkdir // in golang to cater for creating a directory am ACL permitting full // access, with inheritance, to any subfolder/file for Built-in Administrators // and Local System. func mkdirWithACL(name string, sddl string) error { sa := windows.SecurityAttributes{Length: 0} sd, err := winio.<API key>(sddl) if err != nil { return &os.PathError{Op: "mkdir", Path: name, Err: err} } sa.Length = uint32(unsafe.Sizeof(sa)) sa.InheritHandle = 1 sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0])) namep, err := windows.UTF16PtrFromString(name) if err != nil { return &os.PathError{Op: "mkdir", Path: name, Err: err} } e := windows.CreateDirectory(namep, &sa) if e != nil { return &os.PathError{Op: "mkdir", Path: name, Err: e} } return nil } // IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, // golang filepath.IsAbs does not consider a path \windows\system32 as absolute // as it doesn't start with a drive-letter/colon combination. However, in // docker we need to verify things such as WORKDIR /windows/system32 in // a Dockerfile (which gets translated to \windows\system32 when being processed // by the daemon. This SHOULD be treated as absolute from a docker processing // perspective. func IsAbs(path string) bool { if !filepath.IsAbs(path) { if !strings.HasPrefix(path, string(os.PathSeparator)) { return false } } return true } // The origin of the functions below here are the golang OS and windows packages, // slightly modified to only cope with files, not directories due to the // specific use case. // The alteration is to allow a file on Windows to be opened with // <API key> (particular for docker load), to avoid eating // the standby list, particularly when accessing large files such as layer.tar. // CreateSequential creates the named file with mode 0666 (before umask), truncating // it if it already exists. If successful, methods on the returned // File can be used for I/O; the associated file descriptor has mode // O_RDWR. // If there is an error, it will be of type *PathError. func CreateSequential(name string) (*os.File, error) { return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) } // OpenSequential opens the named file for reading. If successful, methods on // the returned file can be used for reading; the associated file // descriptor has mode O_RDONLY. // If there is an error, it will be of type *PathError. func OpenSequential(name string) (*os.File, error) { return OpenFileSequential(name, os.O_RDONLY, 0) } // OpenFileSequential is the generalized open call; most users will use Open // or Create instead. // If there is an error, it will be of type *PathError. func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { if name == "" { return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} } r, errf := <API key>(name, flag, 0) if errf == nil { return r, nil } return nil, &os.PathError{Op: "open", Path: name, Err: errf} } func <API key>(name string, flag int, _ os.FileMode) (file *os.File, err error) { r, e := <API key>(name, flag|windows.O_CLOEXEC, 0) if e != nil { return nil, e } return os.NewFile(uintptr(r), name), nil } func makeInheritSa() *windows.SecurityAttributes { var sa windows.SecurityAttributes sa.Length = uint32(unsafe.Sizeof(sa)) sa.InheritHandle = 1 return &sa } func <API key>(path string, mode int, _ uint32) (fd windows.Handle, err error) { if len(path) == 0 { return windows.InvalidHandle, windows.<API key> } pathp, err := windows.UTF16PtrFromString(path) if err != nil { return windows.InvalidHandle, err } var access uint32 switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) { case windows.O_RDONLY: access = windows.GENERIC_READ case windows.O_WRONLY: access = windows.GENERIC_WRITE case windows.O_RDWR: access = windows.GENERIC_READ | windows.GENERIC_WRITE } if mode&windows.O_CREAT != 0 { access |= windows.GENERIC_WRITE } if mode&windows.O_APPEND != 0 { access &^= windows.GENERIC_WRITE access |= windows.FILE_APPEND_DATA } sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE) var sa *windows.SecurityAttributes if mode&windows.O_CLOEXEC == 0 { sa = makeInheritSa() } var createmode uint32 switch { case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL): createmode = windows.CREATE_NEW case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC): createmode = windows.CREATE_ALWAYS case mode&windows.O_CREAT == windows.O_CREAT: createmode = windows.OPEN_ALWAYS case mode&windows.O_TRUNC == windows.O_TRUNC: createmode = windows.TRUNCATE_EXISTING default: createmode = windows.OPEN_EXISTING } // Use <API key> rather than <API key> as implemented in golang. const <API key> = 0x08000000 // <API key> h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, <API key>, 0) return h, e } // Helpers for TempFileSequential var rand uint32 var randmu sync.Mutex func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) } func nextSuffix() string { randmu.Lock() r := rand if r == 0 { r = reseed() } r = r*1664525 + 1013904223 // constants from Numerical Recipes rand = r randmu.Unlock() return strconv.Itoa(int(1e9 + r%1e9))[1:] } // TempFileSequential is a copy of ioutil.TempFile, modified to use sequential // file access. Below is the original comment from golang: // TempFile creates a new temporary file in the directory dir // with a name beginning with prefix, opens the file for reading // and writing, and returns the resulting *os.File. // If dir is the empty string, TempFile uses the default directory // for temporary files (see os.TempDir). // Multiple programs calling TempFile simultaneously // will not choose the same file. The caller can use f.Name() // to find the pathname of the file. It is the caller's responsibility // to remove the file when no longer needed. func TempFileSequential(dir, prefix string) (f *os.File, err error) { if dir == "" { dir = os.TempDir() } nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextSuffix()) f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() rand = reseed() randmu.Unlock() } continue } break } return }
modules.define( 'spec', ['button', 'i-bem__dom', 'chai', 'jquery', 'BEMHTML'], function(provide, Button, BEMDOM, chai, $, BEMHTML) { var expect = chai.expect; describe('button_type_link', function() { var button; beforeEach(function() { button = buildButton({ block : 'button', mods : { type : 'link' }, url : '/' }); }); afterEach(function() { BEMDOM.destruct(button.domElem); }); describe('url', function() { it('should properly gets url', function() { button.domElem.attr('href').should.be.equal('/'); button.getUrl().should.be.equal('/'); }); it('should properly sets url', function() { button.setUrl('/bla'); button.domElem.attr('href').should.be.equal('/bla'); button.getUrl().should.be.equal('/bla'); }); }); describe('disabled', function() { it('should remove "href" attribute if disabled before init', function() { BEMDOM.destruct(button.domElem); // we need to destruct default button from beforeEach button = buildButton({ block : 'button', mods : { type : 'link', disabled : true }, url : '/' }); button.getUrl().should.be.equal('/'); expect(button.domElem.attr('href')).to.be.undefined; }); it('should update attributes properly', function() { button.setMod('disabled'); button.domElem.attr('aria-disabled').should.be.equal('true'); expect(button.domElem.attr('href')).to.be.undefined; button.delMod('disabled'); button.domElem.attr('href').should.be.equal('/'); expect(button.domElem.attr('aria-disabled')).to.be.undefined; }); }); function buildButton(bemjson) { return BEMDOM.init($(BEMHTML.apply(bemjson)) .appendTo('body')) .bem('button'); } }); provide(); });
<!DOCTYPE html> <meta charset="utf-8"> <title>Async local storage: should not work in non-secure contexts when included via an import statement</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> "use strict"; setup({ <API key>: true }); test(() => { assert_false(self.isSecureContext, "This test must run in a non-secure context"); }, "Prerequisite check"); async_test(t => { window.addEventListener("error", t.step_func_done(errorEvent => { assert_equals(errorEvent.error.constructor, DOMException, "Must trigger a DOMException"); assert_equals(errorEvent.error.name, "SecurityError", "The DOMException must be a \"SecurityError\""); }, { once: true })); }); </script> <script type="module"> import "std:async-local-storage"; </script>
import java.util.Scanner; public class SegmentTree { private static class Node { public int left, right; public long add, sum; public Node(int left, int right, long sum) { this.left = left; this.right = right; this.sum = sum; } } private Node[] tree; private int size; public SegmentTree(int n,int[] arr) { size = (n<<2); tree = new Node[size]; build(0, 0, n-1, arr); } private void build(int pos, int p, int r, int[] arr) { if (p == r) { tree[pos] = new Node(p, r, arr[p]); } else { build(2*pos+1, p, (p+r)/2, arr); build(2*pos+2, (p+r)/2+1, r, arr); tree[pos] = new Node(p, r, tree[2*pos+1].sum + tree[2*pos+2].sum); } } public void update(int p, int r, long delt) { p = (tree[0].left < p)? p : tree[0].left; r = (tree[0].right > r)? r : tree[0].right; if (p <= r) { updateHelp(0, p, r, delt); } } private void updateHelp(int pos, int p, int r, long delt) { if (tree[pos].left>=p && tree[pos].right<=r) { tree[pos].add += delt; tree[pos].sum += (tree[pos].right-tree[pos].left+1)*delt; } else { if (tree[pos].add!=0) { pushDown(pos); } int mid = (tree[pos].left+tree[pos].right)/2; if (p <= mid) { updateHelp(2*pos+1, p, r, delt); } if (mid+1 <= r) { updateHelp(2*pos+2, p, r, delt); } tree[pos].sum = tree[2*pos+1].sum + tree[2*pos+2].sum; } } private void pushDown(int pos) { int left = 2*pos+1, right = 2*pos+2; tree[left].add += tree[pos].add; tree[right].add += tree[pos].add; tree[left].sum += (tree[left].right-tree[left].left+1)*tree[pos].add; tree[right].sum += (tree[right].right-tree[right].left+1)*tree[pos].add; tree[pos].add = 0; } public long query(int p,int r) { if (tree[0].left<=p && tree[0].right>=r) { return queryHelp(0,p,r); } else { return 0; } } private long queryHelp(int pos,int p,int r) { if (tree[pos].left>=p && tree[pos].right<=r) { return tree[pos].sum; } else { if (tree[pos].add!=0) { pushDown(pos); } long val = 0; int mid = (tree[pos].left+tree[pos].right)/2; if (p <= mid) { val += queryHelp(2*pos+1, p, r); } if (mid+1 <= r) { val += queryHelp(2*pos+2, p, r); } return val; } } public static void main(String[] args) { Main.main(args); } } class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; int q = in.nextInt(); for (int i=0;i<n;i++) { arr[i] = in.nextInt(); } SegmentTree tr = new SegmentTree(n,arr); for (int i=0;i<q;i++) { String op = in.next(); if (op.equals("C")) { int p = in.nextInt()-1; int r = in.nextInt()-1; tr.update(p,r,in.nextInt()); } else if (op.equals("Q")) { int p = in.nextInt()-1; int r = in.nextInt()-1; System.out.println(tr.query(p,r)); } } in.close(); } }
// |jit-test| allow-oom; <API key> gcparam("maxBytes", gcparam("gcBytes") + 4*1024); var max = 400; function f(b) { if (b) { f(b - 1); } else { g = { apply:function(x,y) { } }; } g.apply(null, arguments); } f(max - 1);
{% extends "demos/base.html" %} {% block body_attributes %}id="demostudio"{% endblock %} {% block bodyclass %}section-demos landing {% if is_demo_home %}section-demos-home{% endif %}{% endblock %} {% block extrahead %} <link rel="alternate" type="application/atom+xml" title="{{_('Recent demos')}}" href="{{ url('demos_feed_recent', format='atom') }}" /> <link rel="alternate" type="application/atom+xml" title="{{_('Featured demos')}}" href="{{ url('demos_feed_featured', format='atom') }}" /> {% endblock %} {% block title %}{{ page_title(_('Demo Studio')) }}{% endblock %} {% block content %} <section id="content"> <div class="wrap"> <header id="demos-head"> <h1><a href="{{ url('demos') }}">{{_("Mozilla Demo Studio")}}</a></h1> <ul class="demo-buttons"> <li class="submit"><a href="{{ url('demos_submit') }}" class="button positive"><b></b>{{_("Submit a Demo")}}</a></li> <li class="learnmore menu"><a href="#learn-pop" class="button">{{ _('Learn More') }}</a> <div id="learn-pop" aria-hidden="true"> {% trans %} <p>Welcome to the Mozilla Demo Studio, where developers like you can develop, share, demonstrate, and learn all about Web technologies. See what's possible by exploring Demo Studio:</p> <ul> <li>View demos that showcase what HTML, CSS, and JavaScript can do.</li> <li>Inspect the source code for those demos so you can see how they work.</li> <li>Read documentation to learn about the open standards and technologies that power the Web.</li> </ul> {% endtrans %} </div> </li> </ul> </header> {% if <API key> | length >= 3 %} <section id="featured-demos"> <header> <h2>{{_("Featured Demos")}}</h2> </header> <ul class="nav-slide"> <li class="nav-prev"><a href="#demo-prev" class="prev" title="{{_("See the previous demo")}}">{{_("Previous")}}</a></li> <li class="nav-next"><a href="#demo-next" class="next" title="{{_("See the next demo")}}">{{_("Next")}}</a></li> </ul> {% set submission = <API key>[1] %} <div id="demo-main"> {# <strong class="flag">{{_("Derby Winner")}}</strong> #} <div class="preview"> <a href="{{ url('demos_detail', slug=submission.slug) }}"> <img src="{{ submission.screenshot_1.url }}" alt="" width="435" height="326"> </a> <div class="demo-details"> <h2 class="demo-title"> <a href="{{ url('demos_detail', slug=submission.slug) }}">{{ submission.title }}</a> </h2> <p class="byline vcard"> {{ user_link(submission.creator, show_gravatar=True) }} </p> <p class="desc"> <span class="descText">{{ submission.summary }}</span> <a href="{{ url('demos_detail', slug=submission.slug) }}" class="descLink">{{_("Details")}}</a> </p> <p class="launch"> <a href="{{ url('demos_launch', slug=submission.slug) }}" class="button">{{_("Launch")}}</a> </p> </div> </div> </div> {% set submission = <API key>[0] %} <div id="demo-prev" class="side"> <div class="preview"> <h2 class="demo-title"> <a href="{{ url('demos_detail', slug=submission.slug) }}"> <img class="preview" src="{{ submission.screenshot_1.url }}" alt="" width="261" height="195"> <b>{{ submission.title }}</b> </a> </h2> </div> </div> {% set submission = <API key>[2] %} <div id="demo-next" class="side"> <div class="preview"> <h2 class="demo-title"> <a href="{{ url('demos_detail', slug=submission.slug) }}"> <img class="preview" src="{{ submission.screenshot_1.url }}" alt="" width="261" height="195"> <b>{{ submission.title }}</b> </a> </h2> </div> </div> </section> {% endif %} <section id="content-main" class="full" role="main"> <div id="search-browse"> <form class="demo-search" method="GET" action="{{ url('demos_search') }}"> <p> <input type="search" id="search-demos" name="q" placeholder="{{_("Search demos")}}" /> <noscript><button type="submit">{{_("Search demos")}}</button></noscript> </p> </form> {% trans %}<b>or</b>{% endtrans %} <div id="demo-tags" class="menu"> <a href="#tags-list" class="button neutral">{{_("Browse by Technology")}}</a> <ul id="tags-list"> {% for tag in <API key>() %} {% if tag.name.startswith('tech:') %} <li><a href="{{ url('demos_tag', tag=tag.name) }}">{{ tag_title(tag) }}</a></li> {% endif %} {% endfor %} </ul> </div> <div class="demo-mobile-list"> <ul> <li><a href="all?sort=upandcoming#gallery-list" class="button neutral">{{ ("Browse by up & coming") }}</a></li> <li><a href="all?sort=launches#gallery-list" class="button neutral">{{ ("Browse by most viewed") }}</a></li> <li><a href="all?sort=likes#gallery-list" class="button neutral">{{ ("Browse by most liked") }}</a></li> <li><a href="all?sort=created#gallery-list" class="button neutral">{{ ("Browse by most recent") }}</a></li> </ul> </div> </div> <div class="<API key>"> {{ submission_listing(request, submission_list, is_paginated, paginator, page_obj, _('Subscribe to a feed of %(tag_title)s demos', tag_title=_('recent')), url('demos_feed_recent', format='rss'), cols_per_row=4, pagination_base_url=url('demos_all') ) }} </div> </section><!-- /#content-main --> </div> </section> {% endblock %} {% block js %} {{ super() }} <script type="text/javascript"> $(document).ready(function() { var $featuredDemos = $("#featured-demos"), $details = $("#demo-main .demo-details"), $demoPrev = $('#demo-prev'), $demoNext = $('#demo-next'); $featuredDemos.addClass("js"); $("#demo-main .demo-details, #featured-demos .side .demo-title b").hide().attr("aria-hidden", "true"); $("#demo-main .preview").hoverIntent({ interval: 150, over: function(){ $details.fadeIn().removeAttr("aria-hidden"); }, out: function(){ $details.fadeOut("fast").attr("aria-hidden", "true"); } }); $("#featured-demos .side .preview").hoverIntent({ interval: 250, over: function(){ $(this).find("img").animate({ opacity: "1" }, 150); $(this).find(".demo-title b").fadeIn(150).removeAttr("aria-hidden"); }, out: function(){ $(this).find("img").animate({ opacity: ".6" }, 250); $(this).find(".demo-title b").fadeOut(250).attr("aria-hidden", "true"); } }); /** * Set up featured demos rotation - loads up the JSON feed for featured demos * and does DOM juggling to page through the items. */ var <API key> = '{{ url('demos_feed_featured', format='json') }}'; // Hide buttons until feed loaded. $(".nav-slide .next, .nav-slide .prev").hide(); // Load the feed, wire everything up once the data's been received. $.getJSON(<API key>, function (demos) { // Refrain from wiring up nav, if no items fetched from feed. if (!demos || demos.length == 0) { return; } // Start the current index at 1, since 0 and 2 should already be in prev // and next positions. var currentIndex = 1; // Store node queries that don't need to be made more than once var $demoNextPreview = $('#demo-next .preview'), $demoMainPreview = $('#demo-main .preview'), $demoPrevPreview = $('#demo-prev .preview'); // Create next / prev button vars here var $nextBtn = $('.nav-slide .next'), $prevBtn = $('.nav-slide .prev'); var <API key> = createDemoUpdates(-1, $demoPrev); var <API key> = createDemoUpdates(1, $demoNext); var demoFadeTime = 250; var demoDelayFactor = .5; if($('#demo-prev').css('display') == 'none') { // Small screen, "previous" and "next" aren't shown demoDelayFactor = 0; } // Show the next button and wire up click handler. $nextBtn.show().on('click', function() { currentIndex = (currentIndex == demos.length - 1? 0 : currentIndex + 1); $demoNextPreview.fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); $demoMainPreview.delay(parseInt(demoFadeTime * demoDelayFactor)).fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); $demoPrevPreview.delay(parseInt(demoFadeTime * demoDelayFactor * 2)).fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); return false; }); // Show the previous button and wire up click handler. $prevBtn.show().on('click', function() { currentIndex = (currentIndex == 0 ? demos.length - 1 : currentIndex - 1); $demoPrevPreview.fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); $demoMainPreview.delay(parseInt(demoFadeTime * demoDelayFactor)).fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); $demoNextPreview.delay(parseInt(demoFadeTime * demoDelayFactor * 2)).fadeOut(demoFadeTime, function() { <API key>(); $(this).fadeIn(demoFadeTime); }); return false; }); // Update the main demo from the current index demo. function <API key>() { var demo = demos[currentIndex]; $('#demo-main') .find('.preview img').attr('src', demo.screenshot).end() .find('.preview a').attr('href', demo.link).end() .find('.demo-title a') .attr('href', demo.link) .text(demo.title) .end() .find('.byline a') .attr('href', demo.author_link) .find('span').text(demo.author_name).end() .find('img').attr('src', demo.author_avatar).end() .end() .find('.descText').text(demo.summary).end() .find('.descLink') .attr('href', demo.link) .end() .find('.launch a').attr('href', demo.link + '/launch') .end(); } // Create functions for next and previous movement function createDemoUpdates(offset, $element) { return function() { var scrollIndex = currentIndex + offset; if(!demos[scrollIndex]) { if(offset < 0) { // Previous, so show the last one in the "prev" spot scrollIndex = demos.length - 1; } else { // Next, show the first one in the "next" spot scrollIndex = 0; } } var demo = demos[scrollIndex]; $element .find('.preview img').attr('src', demo ? demo.screenshot : '').end() .find('.demo-title a').attr('href', demo ? demo.link : '#').end() .find('.demo-title b').text(demo ? demo.title : '').end(); }; } // Preload images for sake of smoothness $.each(demos, function() { $('<img>').attr({ 'src': this.screenshot, 'aria-hidden': 'true', 'class': 'offscreen' }).appendTo(document.body); }); }); }); </script> {% endblock %}
""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import <API key> from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import <API key> from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(<API key>, <API key>): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.<API key> = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def <API key>(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) <API key> = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), <API key>) self.assertNotIn(unicode(self.html_block.location), <API key>)
package com.torodb.torod.core.language.querycriteria; import com.torodb.torod.core.language.AttributeReference; import com.torodb.torod.core.language.querycriteria.utils.<API key>; import com.torodb.torod.core.subdocument.values.Value; public class <API key> extends <API key> { private static final long serialVersionUID = 1L; public <API key>(AttributeReference attributeReference, Value<?> val) { super(attributeReference, val); } @Override protected int getBaseHash() { return 5; } @Override public String toString() { return <API key>() + " >= " + getValue(); } @Override public <Result, Arg> Result accept(<API key><Result, Arg> visitor, Arg arg) { return visitor.visit(this, arg); } }
import Analyzer from 'parser/core/Analyzer'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; class Insanity extends Analyzer { _insanityEvents = []; <API key>(event) { if (event.resourceChangeType === RESOURCE_TYPES.INSANITY.id) { this._insanityEvents = [ this._insanityEvents, event, ]; } } get events() { return this._insanityEvents; } } export default Insanity;
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is built by mktables from e.g. UnicodeData.txt. # Any changes made here will be lost! # This file supports: # \p{L} (and fuzzy permutations) # Meaning: Major Category 'L' return <<'END'; 0041 005A 0061 007A 00AA 00B5 00BA 00C0 00D6 00D8 00F6 00F8 02C1 02C6 02D1 02E0 02E4 02EE 037A 037D 0386 0388 038A 038C 038E 03A1 03A3 03CE 03D0 03F5 03F7 0481 048A 0513 0531 0556 0559 0561 0587 05D0 05EA 05F0 05F2 0621 063A 0640 064A 066E 066F 0671 06D3 06D5 06E5 06E6 06EE 06EF 06FA 06FC 06FF 0710 0712 072F 074D 076D 0780 07A5 07B1 07CA 07EA 07F4 07F5 07FA 0904 0939 093D 0950 0958 0961 097B 097F 0985 098C 098F 0990 0993 09A8 09AA 09B0 09B2 09B6 09B9 09BD 09CE 09DC 09DD 09DF 09E1 09F0 09F1 0A05 0A0A 0A0F 0A10 0A13 0A28 0A2A 0A30 0A32 0A33 0A35 0A36 0A38 0A39 0A59 0A5C 0A5E 0A72 0A74 0A85 0A8D 0A8F 0A91 0A93 0AA8 0AAA 0AB0 0AB2 0AB3 0AB5 0AB9 0ABD 0AD0 0AE0 0AE1 0B05 0B0C 0B0F 0B10 0B13 0B28 0B2A 0B30 0B32 0B33 0B35 0B39 0B3D 0B5C 0B5D 0B5F 0B61 0B71 0B83 0B85 0B8A 0B8E 0B90 0B92 0B95 0B99 0B9A 0B9C 0B9E 0B9F 0BA3 0BA4 0BA8 0BAA 0BAE 0BB9 0C05 0C0C 0C0E 0C10 0C12 0C28 0C2A 0C33 0C35 0C39 0C60 0C61 0C85 0C8C 0C8E 0C90 0C92 0CA8 0CAA 0CB3 0CB5 0CB9 0CBD 0CDE 0CE0 0CE1 0D05 0D0C 0D0E 0D10 0D12 0D28 0D2A 0D39 0D60 0D61 0D85 0D96 0D9A 0DB1 0DB3 0DBB 0DBD 0DC0 0DC6 0E01 0E30 0E32 0E33 0E40 0E46 0E81 0E82 0E84 0E87 0E88 0E8A 0E8D 0E94 0E97 0E99 0E9F 0EA1 0EA3 0EA5 0EA7 0EAA 0EAB 0EAD 0EB0 0EB2 0EB3 0EBD 0EC0 0EC4 0EC6 0EDC 0EDD 0F00 0F40 0F47 0F49 0F6A 0F88 0F8B 1000 1021 1023 1027 1029 102A 1050 1055 10A0 10C5 10D0 10FA 10FC 1100 1159 115F 11A2 11A8 11F9 1200 1248 124A 124D 1250 1256 1258 125A 125D 1260 1288 128A 128D 1290 12B0 12B2 12B5 12B8 12BE 12C0 12C2 12C5 12C8 12D6 12D8 1310 1312 1315 1318 135A 1380 138F 13A0 13F4 1401 166C 166F 1676 1681 169A 16A0 16EA 1700 170C 170E 1711 1720 1731 1740 1751 1760 176C 176E 1770 1780 17B3 17D7 17DC 1820 1877 1880 18A8 1900 191C 1950 196D 1970 1974 1980 19A9 19C1 19C7 1A00 1A16 1B05 1B33 1B45 1B4B 1D00 1DBF 1E00 1E9B 1EA0 1EF9 1F00 1F15 1F18 1F1D 1F20 1F45 1F48 1F4D 1F50 1F57 1F59 1F5B 1F5D 1F5F 1F7D 1F80 1FB4 1FB6 1FBC 1FBE 1FC2 1FC4 1FC6 1FCC 1FD0 1FD3 1FD6 1FDB 1FE0 1FEC 1FF2 1FF4 1FF6 1FFC 2071 207F 2090 2094 2102 2107 210A 2113 2115 2119 211D 2124 2126 2128 212A 212D 212F 2139 213C 213F 2145 2149 214E 2183 2184 2C00 2C2E 2C30 2C5E 2C60 2C6C 2C74 2C77 2C80 2CE4 2D00 2D25 2D30 2D65 2D6F 2D80 2D96 2DA0 2DA6 2DA8 2DAE 2DB0 2DB6 2DB8 2DBE 2DC0 2DC6 2DC8 2DCE 2DD0 2DD6 2DD8 2DDE 3005 3006 3031 3035 303B 303C 3041 3096 309D 309F 30A1 30FA 30FC 30FF 3105 312C 3131 318E 31A0 31B7 31F0 31FF 3400 4DB5 4E00 9FBB A000 A48C A717 A71A A800 A801 A803 A805 A807 A80A A80C A822 A840 A873 AC00 D7A3 F900 FA2D FA30 FA6A FA70 FAD9 FB00 FB06 FB13 FB17 FB1D FB1F FB28 FB2A FB36 FB38 FB3C FB3E FB40 FB41 FB43 FB44 FB46 FBB1 FBD3 FD3D FD50 FD8F FD92 FDC7 FDF0 FDFB FE70 FE74 FE76 FEFC FF21 FF3A FF41 FF5A FF66 FFBE FFC2 FFC7 FFCA FFCF FFD2 FFD7 FFDA FFDC 10000 1000B 1000D 10026 10028 1003A 1003C 1003D 1003F 1004D 10050 1005D 10080 100FA 10300 1031E 10330 10340 10342 10349 10380 1039D 103A0 103C3 103C8 103CF 10400 1049D 10800 10805 10808 1080A 10835 10837 10838 1083C 1083F 10900 10915 10A00 10A10 10A13 10A15 10A17 10A19 10A33 12000 1236E 1D400 1D454 1D456 1D49C 1D49E 1D49F 1D4A2 1D4A5 1D4A6 1D4A9 1D4AC 1D4AE 1D4B9 1D4BB 1D4BD 1D4C3 1D4C5 1D505 1D507 1D50A 1D50D 1D514 1D516 1D51C 1D51E 1D539 1D53B 1D53E 1D540 1D544 1D546 1D54A 1D550 1D552 1D6A5 1D6A8 1D6C0 1D6C2 1D6DA 1D6DC 1D6FA 1D6FC 1D714 1D716 1D734 1D736 1D74E 1D750 1D76E 1D770 1D788 1D78A 1D7A8 1D7AA 1D7C2 1D7C4 1D7CB 20000 2A6D6 2F800 2FA1D END
package pl.edu.icm.coansys.disambiguation.author.pig.merger; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.mapreduce.Counter; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.tools.pigstats.PigStatusReporter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.edu.icm.coansys.commons.java.DiacriticsRemover; import pl.edu.icm.coansys.commons.java.StackTraceExtractor; import pl.edu.icm.coansys.models.DocumentProtos.Author; import pl.edu.icm.coansys.models.DocumentProtos.BasicMetadata; import pl.edu.icm.coansys.models.DocumentProtos.DocumentMetadata; import pl.edu.icm.coansys.models.DocumentProtos.DocumentWrapper; import pl.edu.icm.coansys.models.DocumentProtos.KeyValue; /** * * @author pdendek */ public class <API key> extends EvalFunc<Tuple> { PigStatusReporter myPigStatusReporter; private static final Logger logger = LoggerFactory .getLogger(<API key>.class); @Override public Schema outputSchema(Schema p_input) { try { return Schema.<API key>(DataType.TUPLE, DataType.CHARARRAY, DataType.BYTEARRAY); } catch (FrontendException e) { logger.error("Error in creating output schema:", e); throw new <API key>(e); } } @Override public Tuple exec(Tuple input) throws IOException { if (input == null || input.size() != 3) { return null; } try { myPigStatusReporter = PigStatusReporter.getInstance(); //load input tuple /doi String docId = (String) input.get(0); /normal document DataByteArray dbaD = (DataByteArray) input.get(1); /orcid document DataByteArray dbaO = (DataByteArray) input.get(2); //load input documents DocumentWrapper dwD = DocumentWrapper.parseFrom(dbaD.get()); List<Author> aDL = dwD.getDocumentMetadata().getBasicMetadata().getAuthorList(); DocumentWrapper dwO = DocumentWrapper.parseFrom(dbaO.get()); List<Author> aOL = dwO.getDocumentMetadata().getBasicMetadata().getAuthorList(); //calculate merged author list List<Author> aRL = matchAuthors(docId,aDL,aOL); //construct resulting document BasicMetadata.Builder bmR = BasicMetadata.newBuilder(DocumentWrapper.newBuilder(dwD).getDocumentMetadata().getBasicMetadata()); bmR.clearAuthor(); bmR.addAllAuthor(aRL); DocumentMetadata.Builder dmR = DocumentMetadata.newBuilder(DocumentWrapper.newBuilder(dwD).getDocumentMetadata()); dmR.setBasicMetadata(bmR); DocumentWrapper.Builder dwR = DocumentWrapper.newBuilder(dwD); dwR.setDocumentMetadata(dmR); //construct resulting tuple Tuple result = TupleFactory.getInstance().newTuple(); result.append(docId); result.append(new DataByteArray(dwR.build().toByteArray())); return result; } catch (Exception e) { logger.error("Error in processing input row:", e); throw new IOException("Caught exception processing input row:\n" + StackTraceExtractor.getStackTrace(e)); } } protected List<Author> matchAuthors(String docId, List<Author> base, List<Author> second) { List<Author> result = new ArrayList<Author>(base.size()); List<Author> secondCopy = new ArrayList<Author>(second); boolean changedBln = false; int changedInt = 0; logger.error(" logger.error("number of base authors: "+base.size()+"\tnumber of orcid authors"); for (Author author : base) { Author foundAuthor = null; for (Author secondAuthor : secondCopy) { if ( <API key>(author.getName(), secondAuthor.getName()) || //<API key>(author.getForenames(), secondAuthor.getForenames()) && <API key>(author.getSurname(), secondAuthor.getSurname()) ){ foundAuthor = secondAuthor; break; } } if (foundAuthor != null) { result.add(merge(author,foundAuthor)); changedBln = true; changedInt++; if(myPigStatusReporter != null){ Counter c = myPigStatusReporter.getCounter("ORCID Enhancement", "Author Enhanced"); if(c!=null){ c.increment(1); } } } else { result.add(Author.newBuilder(author).build()); } } if(changedBln){ logger.info(" logger.info("Changed docId:"+docId); if(myPigStatusReporter != null){ Counter c = myPigStatusReporter.getCounter("ORCID Enhancement", "Document Enhanced"); if(c!=null){ c.increment(1); } } } logger.error("number of intersections: "+changedInt); return result; } private Author merge(Author author, Author foundAuthor) { Author.Builder builder = Author.newBuilder(author); for(KeyValue kv : foundAuthor.getExtIdList()){ if("orcid-author-id".equals(kv.getKey())){ KeyValue.Builder kvb = KeyValue.newBuilder(); kvb.setKey(kv.getKey()); kvb.setValue(kv.getValue()); builder.addExtId(kvb.build()); logger.info("<k:"+kv.getKey()+"; v:"+kv.getValue()+">"); logger.info("<kc:"+kvb.getKey()+"; vc:"+kvb.getValue()+">"); } } Author ret = builder.build(); logger.info("<auth:"+ret.toString()+">"); return ret; } private boolean <API key>(String firstName, String secondName) { if (firstName.isEmpty() || secondName.isEmpty()) { return false; } return DiacriticsRemover.removeDiacritics(firstName).equalsIgnoreCase( DiacriticsRemover.removeDiacritics(secondName)); } }
package org.opennms.web.command; /** * Command object for listing a specific statistics report. This object deserializes query params * for a specific report, identified by integer ID. * * @author <a href="mailto:dj@opennms.org">DJ Gregor</a> * @version $Id: $ * @since 1.8.1 */ public class <API key> { private Integer m_id; /** * <p>getId</p> * * @return a {@link java.lang.Integer} object. */ public Integer getId() { return m_id; } /** * <p>setId</p> * * @param id a {@link java.lang.Integer} object. */ public void setId(Integer id) { m_id = id; } }
package azuretesting import ( "encoding/json" "reflect" ) // JsonMarshalRaw does the same a json.Marshal, except that it does not // use the MarshalJSON methods of the value being marshaled. If any types // are specified in the allow set then those will use their MarshalJSON // method. // Many of the types in the Azure SDK have MarshalJSON which skip over // fields that are marked as READ-ONLY, this is useful for the client, // but a problem when pretending to be a server. func JsonMarshalRaw(v interface{}, allow ...reflect.Type) ([]byte, error) { allowed := make(map[reflect.Type]bool, len(allow)) for _, a := range allow { allowed[a] = true } if v != nil { v = rawValueMaker{allowed}.rawValue(reflect.ValueOf(v)).Interface() } return json.Marshal(v) } type rawValueMaker struct { allowed map[reflect.Type]bool } func (m rawValueMaker) rawValue(v reflect.Value) reflect.Value { t := v.Type() if m.allowed[t] { return v } switch t.Kind() { case reflect.Ptr: return m.rawPointerValue(v) case reflect.Struct: return m.rawStructValue(v) case reflect.Map: return m.rawMapValue(v) case reflect.Slice: return m.rawSliceValue(v) default: return v } } func (m rawValueMaker) rawPointerValue(v reflect.Value) reflect.Value { if v.IsNil() { return v } rv := m.rawValue(v.Elem()) if rv.CanAddr() { return rv.Addr() } pv := reflect.New(rv.Type()) pv.Elem().Set(rv) return pv } func (m rawValueMaker) rawStructValue(v reflect.Value) reflect.Value { t := v.Type() fields := make([]reflect.StructField, 0, t.NumField()) values := make([]reflect.Value, 0, t.NumField()) for i := 0; i < t.NumField(); i++ { sf := t.Field(i) if sf.PkgPath != "" || sf.Tag.Get("json") == "-" { // Skip fields that won't ever be marshaled. continue } if tag, ok := sf.Tag.Lookup("json"); ok && tag == "" { // Also skip fields with a present, but empty, json tag. continue } rv := m.rawValue(v.Field(i)) sf.Type = rv.Type() sf.Anonymous = false fields = append(fields, sf) values = append(values, rv) } newT := reflect.StructOf(fields) newV := reflect.New(newT).Elem() for i, v := range values { newV.Field(i).Set(v) } return newV } var interfaceType = reflect.TypeOf((*interface{})(nil)).Elem() func (m rawValueMaker) rawMapValue(v reflect.Value) reflect.Value { newV := reflect.MakeMap(reflect.MapOf(v.Type().Key(), interfaceType)) for _, key := range v.MapKeys() { value := v.MapIndex(key) newV.SetMapIndex(key, m.rawValue(value)) } return newV } func (m rawValueMaker) rawSliceValue(v reflect.Value) reflect.Value { newV := reflect.MakeSlice(reflect.SliceOf(interfaceType), v.Len(), v.Len()) for i := 0; i < v.Len(); i++ { newV.Index(i).Set(m.rawValue(v.Index(i))) } return newV }
#pragma checksum "C:\Users\agomez.ETIC\Documents\Visual Studio 2013\Projects\Edatalia_signplyRT\Edatalia_signplyRT\ServiceContractPage.xaml" "{<API key>}" "<API key>" // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace Edatalia_signplyRT { partial class ServiceContractPage : global::Windows.UI.Xaml.Controls.Page { [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.Page pageRoot; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.StackPanel spContractData; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.DatePicker dtPicker; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.TextBox tbImporte; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.Button backButton; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.TextBlock pageTitle; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.Image imgTittle; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.AppBar bottomAppBar; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.AppBarButton appbtnOpen; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private global::Windows.UI.Xaml.Controls.AppBarButton appbtnCancel; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] private bool _contentLoaded; [global::System.CodeDom.Compiler.<API key>("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")] [global::System.Diagnostics.<API key>()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; global::Windows.UI.Xaml.Application.LoadComponent(this, new global::System.Uri("ms-appx:///ServiceContractPage.xaml"), global::Windows.UI.Xaml.Controls.Primitives.<API key>.Application); pageRoot = (global::Windows.UI.Xaml.Controls.Page)this.FindName("pageRoot"); spContractData = (global::Windows.UI.Xaml.Controls.StackPanel)this.FindName("spContractData"); dtPicker = (global::Windows.UI.Xaml.Controls.DatePicker)this.FindName("dtPicker"); tbImporte = (global::Windows.UI.Xaml.Controls.TextBox)this.FindName("tbImporte"); backButton = (global::Windows.UI.Xaml.Controls.Button)this.FindName("backButton"); pageTitle = (global::Windows.UI.Xaml.Controls.TextBlock)this.FindName("pageTitle"); imgTittle = (global::Windows.UI.Xaml.Controls.Image)this.FindName("imgTittle"); bottomAppBar = (global::Windows.UI.Xaml.Controls.AppBar)this.FindName("bottomAppBar"); appbtnOpen = (global::Windows.UI.Xaml.Controls.AppBarButton)this.FindName("appbtnOpen"); appbtnCancel = (global::Windows.UI.Xaml.Controls.AppBarButton)this.FindName("appbtnCancel"); } } }
<?php /** * @package API\Accrual */ class APIAccrualBalance extends APIFactory { protected $main_class = '<API key>'; public function __construct() { parent::__construct(); //Make sure parent constructor is always called. return TRUE; } /** * Get options for dropdown boxes. * @param string $name Name of options to return, ie: 'columns', 'type', 'status' * @param mixed $parent Parent name/ID of options to return if data is in hierarchical format. (ie: Province) * @return array */ function getOptions( $name, $parent = NULL ) { if ( $name == 'columns' AND ( !$this->getPermissionObject()->Check('accrual', 'enabled') OR !( $this->getPermissionObject()->Check('accrual', 'view') OR $this->getPermissionObject()->Check('accrual', 'view_child') ) ) ) { $name = 'list_columns'; } return parent::getOptions( $name, $parent ); } /** * Get accrual balance data for one or more accrual balancees. * @param array $data filter data * @return array */ function getAccrualBalance( $data = NULL, $disable_paging = FALSE ) { if ( !$this->getPermissionObject()->Check('accrual', 'enabled') OR !( $this->getPermissionObject()->Check('accrual', 'view') OR $this->getPermissionObject()->Check('accrual', 'view_own') OR $this->getPermissionObject()->Check('accrual', 'view_child') ) ) { return $this->getPermissionObject()->PermissionDenied(); } $data = $this-><API key>( $data, $disable_paging ); $data['filter_data']['<API key>'] = $this->getPermissionObject()-><API key>( 'accrual', 'view' ); $blf = TTnew( '<API key>' ); $blf-><API key>( $this-><API key>()->getId(), $data['filter_data'], $data['<API key>'], $data['filter_page'], NULL, $data['filter_sort'] ); Debug::Text('Record Count: '. $blf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10); if ( $blf->getRecordCount() > 0 ) { $this-><API key>()->start( $this->getAMFMessageID(), $blf->getRecordCount() ); $this->setPagerObject( $blf ); foreach( $blf as $b_obj ) { $retarr[] = $b_obj->getObjectAsArray( $data['filter_columns'], $data['filter_data']['<API key>'] ); $this-><API key>()->set( $this->getAMFMessageID(), $blf->getCurrentRow() ); } $this-><API key>()->stop( $this->getAMFMessageID() ); return $this->returnHandler( $retarr ); } return $this->returnHandler( TRUE ); //No records returned. } } ?>
Clazz.declarePackage ("org.jmol.shapespecial"); Clazz.load (["org.jmol.shape.AtomShape", "org.jmol.atomdata.RadiusData", "org.jmol.util.BitSet"], "org.jmol.shapespecial.Dots", ["java.util.Hashtable", "org.jmol.constant.EnumVdw", "org.jmol.geodesic.EnvelopeCalculation", "org.jmol.util.BitSetUtil", "$.Colix", "$.Escape", "$.Logger", "$.Matrix3f", "$.StringXBuilder"], function () { c$ = Clazz.decorateAsClass (function () { this.ec = null; this.isSurface = false; this.bsOn = null; this.bsSelected = null; this.bsIgnore = null; this.thisAtom = 0; this.thisRadius = 0; this.thisArgb = 0; this.rdLast = null; Clazz.instantialize (this, arguments); }, org.jmol.shapespecial, "Dots", org.jmol.shape.AtomShape); Clazz.prepareFields (c$, function () { this.bsOn = new org.jmol.util.BitSet (); this.rdLast = new org.jmol.atomdata.RadiusData (null, 0, null, null); }); Clazz.defineMethod (c$, "initShape", function () { Clazz.superCall (this, org.jmol.shapespecial.Dots, "initShape", []); this.translucentAllowed = false; this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads); }); Clazz.defineMethod (c$, "getSize", function (atomIndex) { return (this.mads == null ? Clazz.doubleToInt (Math.floor (this.ec.getRadius (atomIndex) * 2000)) : this.mads[atomIndex] * 2); }, "~N"); Clazz.defineMethod (c$, "setProperty", function (propertyName, value, bs) { if ("init" === propertyName) { this.initialize (); return; }if ("translucency" === propertyName) { if (!this.translucentAllowed) return; }if ("ignore" === propertyName) { this.bsIgnore = value; return; }if ("select" === propertyName) { this.bsSelected = value; return; }if ("radius" === propertyName) { this.thisRadius = (value).floatValue (); if (this.thisRadius > 16) this.thisRadius = 16; return; }if ("colorRGB" === propertyName) { this.thisArgb = (value).intValue (); return; }if ("atom" === propertyName) { this.thisAtom = (value).intValue (); if (this.thisAtom >= this.atoms.length) return; this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true); this.ec.allocDotsConvexMaps (this.atomCount); return; }if ("dots" === propertyName) { if (this.thisAtom >= this.atoms.length) return; this.isActive = true; this.ec.setFromBits (this.thisAtom, value); this.atoms[this.thisAtom].setShapeVisibility (this.myVisibilityFlag, true); if (this.mads == null) { this.ec.setMads (null); this.mads = Clazz.newShortArray (this.atomCount, 0); for (var i = 0; i < this.atomCount; i++) if (this.atoms[i].isInFrame () && this.atoms[i].isShapeVisible (this.myVisibilityFlag)) try { this.mads[i] = Clazz.floatToShort (this.ec.<API key> (i) * 1000); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } this.ec.setMads (this.mads); }this.mads[this.thisAtom] = Clazz.floatToShort (this.thisRadius * 1000); if (this.colixes == null) { this.colixes = Clazz.newShortArray (this.atomCount, 0); this.paletteIDs = Clazz.newByteArray (this.atomCount, 0); }this.colixes[this.thisAtom] = org.jmol.util.Colix.getColix (this.thisArgb); this.bsOn.set (this.thisAtom); return; }if ("refreshTrajectories" === propertyName) { bs = (value)[1]; var m4 = (value)[2]; if (m4 == null) return; var m = new org.jmol.util.Matrix3f (); m4.getRotationScale (m); this.ec.reCalculate (bs, m); return; }if (propertyName === "deleteModelAtoms") { var firstAtomDeleted = ((value)[2])[1]; var nAtomsDeleted = ((value)[2])[2]; org.jmol.util.BitSetUtil.deleteBits (this.bsOn, bs); this.ec.deleteAtoms (firstAtomDeleted, nAtomsDeleted); }Clazz.superCall (this, org.jmol.shapespecial.Dots, "setProperty", [propertyName, value, bs]); }, "~S,~O,org.jmol.util.BitSet"); Clazz.defineMethod (c$, "initialize", function () { this.bsSelected = null; this.bsIgnore = null; this.isActive = false; if (this.ec == null) this.ec = new org.jmol.geodesic.EnvelopeCalculation (this.viewer, this.atomCount, this.mads); }); Clazz.overrideMethod (c$, "setSizeRD", function (rd, bsSelected) { if (rd == null) rd = new org.jmol.atomdata.RadiusData (null, 0, org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE, null); if (this.bsSelected != null) bsSelected = this.bsSelected; if (org.jmol.util.Logger.debugging) { org.jmol.util.Logger.debug ("Dots.setSize " + rd.value); }var isVisible = true; var setRadius = 3.4028235E38; this.isActive = true; switch (rd.factorType) { case org.jmol.atomdata.RadiusData.EnumType.OFFSET: break; case org.jmol.atomdata.RadiusData.EnumType.ABSOLUTE: if (rd.value == 0) isVisible = false; setRadius = rd.value; default: rd.valueExtended = this.viewer.<API key> (); } var maxRadius; switch (rd.vdwType) { case org.jmol.constant.EnumVdw.ADPMIN: case org.jmol.constant.EnumVdw.ADPMAX: case org.jmol.constant.EnumVdw.HYDRO: case org.jmol.constant.EnumVdw.TEMP: maxRadius = setRadius; break; case org.jmol.constant.EnumVdw.IONIC: maxRadius = this.modelSet.<API key> () * 2; break; default: maxRadius = this.modelSet.<API key> (); } var newSet = (this.rdLast.value != rd.value || this.rdLast.valueExtended != rd.valueExtended || this.rdLast.factorType !== rd.factorType || this.rdLast.vdwType !== rd.vdwType || this.ec.getDotsConvexMax () == 0); if (isVisible) { for (var i = bsSelected.nextSetBit (0); i >= 0; i = bsSelected.nextSetBit (i + 1)) if (!this.bsOn.get (i)) { this.bsOn.set (i); newSet = true; } } else { var isAll = (bsSelected == null); var i0 = (isAll ? this.atomCount - 1 : bsSelected.nextSetBit (0)); for (var i = i0; i >= 0; i = (isAll ? i - 1 : bsSelected.nextSetBit (i + 1))) this.bsOn.setBitTo (i, false); }for (var i = this.atomCount; --i >= 0; ) { this.atoms[i].setShapeVisibility (this.myVisibilityFlag, this.bsOn.get (i)); } if (!isVisible) return; if (newSet) { this.mads = null; this.ec.newSet (); }var dotsConvexMaps = this.ec.getDotsConvexMaps (); if (dotsConvexMaps != null) { for (var i = this.atomCount; --i >= 0; ) if (this.bsOn.get (i)) { dotsConvexMaps[i] = null; } }if (dotsConvexMaps == null) { this.colixes = Clazz.newShortArray (this.atomCount, 0); this.paletteIDs = Clazz.newByteArray (this.atomCount, 0); }this.ec.calculate (rd, maxRadius, this.bsOn, this.bsIgnore, !this.viewer.getDotSurfaceFlag (), this.viewer.<API key> (), this.isSurface, true); this.rdLast = rd; }, "org.jmol.atomdata.RadiusData,org.jmol.util.BitSet"); Clazz.overrideMethod (c$, "<API key>", function () { for (var i = this.atomCount; --i >= 0; ) { var atom = this.atoms[i]; if ((atom.<API key> () & this.myVisibilityFlag) == 0 || this.modelSet.isAtomHidden (i)) continue; atom.setClickable (this.myVisibilityFlag); } }); Clazz.overrideMethod (c$, "getShapeState", function () { var dotsConvexMaps = this.ec.getDotsConvexMaps (); if (dotsConvexMaps == null || this.ec.getDotsConvexMax () == 0) return ""; var s = new org.jmol.util.StringXBuilder (); var temp = new java.util.Hashtable (); var atomCount = this.viewer.getAtomCount (); var type = (this.isSurface ? "geoSurface " : "dots "); for (var i = 0; i < atomCount; i++) { if (!this.bsOn.get (i) || dotsConvexMaps[i] == null) continue; if (this.bsColixSet != null && this.bsColixSet.get (i)) org.jmol.shape.Shape.setStateInfo (temp, i, this.getColorCommand (type, this.paletteIDs[i], this.colixes[i])); var bs = dotsConvexMaps[i]; if (!bs.isEmpty ()) { var r = this.ec.<API key> (i); org.jmol.shape.Shape.appendCmd (s, type + i + " radius " + r + " " + org.jmol.util.Escape.escape (bs)); }} s.append (org.jmol.shape.Shape.getShapeCommands (temp, null)); return s.toString (); }); Clazz.defineStatics (c$, "<API key>", 10, "MAX_LEVEL", 3); });
import re import uuid from xmodule.assetstore.assetmgr import AssetManager XASSET_LOCATION_TAG = 'c4x' <API key> = 'xasset:' <API key> = '.jpg' <API key> = 1024 import os import logging import StringIO from urlparse import urlparse, urlunparse, parse_qsl from urllib import urlencode from opaque_keys.edx.locator import AssetLocator from opaque_keys.edx.keys import CourseKey, AssetKey from opaque_keys import InvalidKeyError from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.exceptions import NotFoundError from PIL import Image class StaticContent(object): def __init__(self, loc, name, content_type, data, last_modified_at=None, thumbnail_location=None, import_path=None, length=None, locked=False): self.location = loc self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed self.content_type = content_type self._data = data self.length = length self.last_modified_at = last_modified_at self.thumbnail_location = thumbnail_location # optional information about where this file was imported from. This is needed to support import/export # cycles self.import_path = import_path self.locked = locked @property def is_thumbnail(self): return self.location.category == 'thumbnail' @staticmethod def <API key>(original_name, dimensions=None): """ - original_name: Name of the asset (typically its location.name) - dimensions: `None` or a tuple of (width, height) in pixels """ name_root, ext = os.path.splitext(original_name) if not ext == <API key>: name_root = name_root + ext.replace(u'.', u'-') if dimensions: width, height = dimensions # pylint: disable=<API key> name_root += "-{}x{}".format(width, height) return u"{name_root}{extension}".format( name_root=name_root, extension=<API key>, ) @staticmethod def compute_location(course_key, path, revision=None, is_thumbnail=False): """ Constructs a location object for static content. - course_key: the course that this asset belongs to - path: is the name of the static asset - revision: is the object's revision information - is_thumbnail: is whether or not we want the thumbnail version of this asset """ path = path.replace('/', '_') return course_key.make_asset_key( 'asset' if not is_thumbnail else 'thumbnail', AssetLocator.<API key>(path) ).for_branch(None) def get_id(self): return self.location @property def data(self): return self._data ASSET_URL_RE = re.compile(r""" /?c4x/ (?P<org>[^/]+)/ (?P<course>[^/]+)/ (?P<category>[^/]+)/ (?P<name>[^/]+) """, re.VERBOSE | re.IGNORECASE) @staticmethod def is_c4x_path(path_string): """ Returns a boolean if a path is believed to be a c4x link based on the leading element """ return StaticContent.ASSET_URL_RE.match(path_string) is not None @staticmethod def <API key>(location): """ This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it. This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of courses. In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into the actual /c4x/... path which the client needs to reference static content """ if location is not None: return u"/static/{name}".format(name=location.name) else: return None @staticmethod def <API key>(course_key): if course_key is None: return None assert isinstance(course_key, CourseKey) placeholder_id = uuid.uuid4().hex # create a dummy asset location with a fake but unique name. strip off the name, and return it url_path = StaticContent.<API key>( course_key.make_asset_key('asset', placeholder_id).for_branch(None) ) return url_path.replace(placeholder_id, '') @staticmethod def <API key>(path): """ Generate an AssetKey for the given path (old c4x/org/course/asset/name syntax) """ try: return AssetKey.from_string(path) except InvalidKeyError: # TODO - re-address this once LMS-11198 is tackled. if path.startswith('/'): # try stripping off the leading slash and try again return AssetKey.from_string(path[1:]) @staticmethod def <API key>(course_key, path): """ Parses a path, extracting an asset key or creating one. Args: course_key: key to the course which owns this asset path: the path to said content Returns: AssetKey: the asset key that represents the path """ # Clean up the path, removing any static prefix and any leading slash. if path.startswith('/static/'): path = path[len('/static/'):] path = path.lstrip('/') try: return AssetKey.from_string(path) except InvalidKeyError: # If we couldn't parse the path, just let compute_location figure it out. # It's most likely a path like /image.png or something. return StaticContent.compute_location(course_key, path) @staticmethod def <API key>(course_key, path, base_url): """ Returns a fully-qualified path to a piece of static content. If a static asset CDN is configured, this path will include it. Otherwise, the path will simply be relative. Args: course_key: key to the course which owns this asset path: the path to said content Returns: string: fully-qualified path to asset """ # Break down the input path. _, _, relative_path, params, query_string, fragment = urlparse(path) # Convert our path to an asset key if it isn't one already. asset_key = StaticContent.<API key>(course_key, relative_path) # Check the status of the asset to see if this can be served via CDN aka publicly. serve_from_cdn = False try: content = AssetManager.find(asset_key, as_stream=True) is_locked = getattr(content, "locked", True) serve_from_cdn = not is_locked except (ItemNotFoundError, NotFoundError): # If we can't find the item, just treat it as if it's locked. serve_from_cdn = False # Update any query parameter values that have asset paths in them. This is for assets that # require their own after-the-fact values, like a Flash file that needs the path of a config # file passed to it e.g. /static/visualization.swf?configFile=/static/visualization.xml query_params = parse_qsl(query_string) <API key> = [] for query_name, query_value in query_params: if query_value.startswith("/static/"): new_query_value = StaticContent.<API key>(course_key, query_value, base_url) <API key>.append((query_name, new_query_value)) else: <API key>.append((query_name, query_value)) <API key> = StaticContent.<API key>(asset_key) base_url = base_url if serve_from_cdn else '' return urlunparse((None, base_url, <API key>, params, urlencode(<API key>), fragment)) def stream_data(self): yield self._data @staticmethod def <API key>(asset_key): """ Legacy code expects the serialized asset key to start w/ a slash; so, do that in one place :param asset_key: """ url = unicode(asset_key) if not url.startswith('/'): url = '/' + url # TODO - re-address this once LMS-11198 is tackled. return url class StaticContentStream(StaticContent): def __init__(self, loc, name, content_type, stream, last_modified_at=None, thumbnail_location=None, import_path=None, length=None, locked=False): super(StaticContentStream, self).__init__(loc, name, content_type, None, last_modified_at=last_modified_at, thumbnail_location=thumbnail_location, import_path=import_path, length=length, locked=locked) self._stream = stream def stream_data(self): while True: chunk = self._stream.read(<API key>) if len(chunk) == 0: break yield chunk def <API key>(self, first_byte, last_byte): """ Stream the data between first_byte and last_byte (included) """ self._stream.seek(first_byte) position = first_byte while True: if last_byte < position + <API key> - 1: chunk = self._stream.read(last_byte - position + 1) yield chunk break chunk = self._stream.read(<API key>) position += <API key> yield chunk def close(self): self._stream.close() def copy_to_in_mem(self): self._stream.seek(0) content = StaticContent(self.location, self.name, self.content_type, self._stream.read(), last_modified_at=self.last_modified_at, thumbnail_location=self.thumbnail_location, import_path=self.import_path, length=self.length, locked=self.locked) return content class ContentStore(object): ''' Abstraction for all ContentStore providers (e.g. MongoDB) ''' def save(self, content): raise NotImplementedError def find(self, filename): raise NotImplementedError def <API key>(self, course_key, start=0, maxresults=-1, sort=None, filter_params=None): ''' Returns a list of static assets for a course, followed by the total number of assets. By default all assets are returned, but start and maxresults can be provided to limit the query. The return format is a list of asset data dictionaries. The asset data dictionaries have the following keys: asset_key (:class:`opaque_keys.edx.AssetKey`): The key of the asset displayname: The human-readable name of the asset uploadDate (datetime.datetime): The date and time that the file was uploadDate contentType: The mimetype string of the asset md5: An md5 hash of the asset content ''' raise NotImplementedError def <API key>(self, course_key): """ Delete all of the assets which use this course_key as an identifier :param course_key: """ raise NotImplementedError def <API key>(self, source_course_key, dest_course_key): """ Copy all the course assets from source_course_key to dest_course_key """ raise NotImplementedError def generate_thumbnail(self, content, tempfile_path=None, dimensions=None): """Create a thumbnail for a given image. Returns a tuple of (StaticContent, AssetKey) `content` is the StaticContent representing the image you want to make a thumbnail out of. `tempfile_path` is a string path to the location of a file to read from in order to grab the image data, instead of relying on `content.data` `dimensions` is an optional param that represents (width, height) in pixels. It defaults to None. """ thumbnail_content = None # use a naming convention to associate originals with the thumbnail thumbnail_name = StaticContent.<API key>( content.location.name, dimensions=dimensions ) <API key> = StaticContent.compute_location( content.location.course_key, thumbnail_name, is_thumbnail=True ) # if we're uploading an image, then let's generate a thumbnail so that we can # serve it up when needed without having to rescale on the fly if content.content_type is not None and content.content_type.split('/')[0] == 'image': try: # My understanding is that PIL will maintain aspect ratios while restricting # the max-height/width to be whatever you pass in as 'size' # @todo: move the thumbnail size to a configuration setting?!? if tempfile_path is None: im = Image.open(StringIO.StringIO(content.data)) else: im = Image.open(tempfile_path) # I've seen some exceptions from the PIL library when trying to save palletted # PNG files to JPEG. Per the google-universe, they suggest converting to RGB first. im = im.convert('RGB') if not dimensions: dimensions = (128, 128) im.thumbnail(dimensions, Image.ANTIALIAS) thumbnail_file = StringIO.StringIO() im.save(thumbnail_file, 'JPEG') thumbnail_file.seek(0) # store this thumbnail as any other piece of content thumbnail_content = StaticContent(<API key>, thumbnail_name, 'image/jpeg', thumbnail_file) self.save(thumbnail_content) except Exception, e: # log and continue as thumbnails are generally considered as optional logging.exception(u"Failed to generate thumbnail for {0}. Exception: {1}".format(content.location, str(e))) return thumbnail_content, <API key> def ensure_indexes(self): """ Ensure that all appropriate indexes are created that are needed by this modulestore, or raise an exception if unable to. """ pass