text:
package omnitool::omniclass::form_maker;

=cut

Produces the %$form hash used by our Templates/Jemplates to generate web forms for
creating or updating records within this OmniClass's datatype.  Meant to be sent
out via a Tool.pm subclass / action module via it's prepare_json() method and
fed into one of the 'Form_mode.tt' Jemplates.

Full example of a %$form structure is below with all supported field types. Any other
forms you need to produce outside of this class should adopt that structure.  Also,
make sure your Tool mode calls for the 'interactive_form_elements' function to be
execute on load-up, so that some of the more interactive elements will get activated.

Form elements rendered via the 'form_elements.tt' Jemplated loaded up with by main
HTML skeleton page.

=cut

# feels like 1,000,000.0
$omnitool::omniclass::form_maker::VERSION = '6.0';

# time to grow up
use strict;

# kick off the routine to produce the form-info hash
sub form {
	# need myself and my args
	my $self = shift;
	my (%args) = @_;

	# declare vars
	my ($data_code, $form, $data_code_info, $field, $params_key);

	# Available Arguments:
	#	'action' => 'create' or 'update', defaulting to 'create' unless 'record' is filled
	#	'data_code' => data_code of record to load as presets for form; assumes 'update'
	#	'target_url' => target URI to submit the form into; defaults to $self->{luggage}{uri}
	#   'new_parent' => 'string',	# parent string of the data under which we will create data; for creates only
	#	'title'	 => Text to display above form; defaults to: ucfirst($args{action}.' a '.$self->{datatype_info}{name}
	#				datatype_hash tries to calculate 'a' or 'an'
	#	'submit_button_text'	=> I bet you can gueess; defaults to 'title' without the a/an
	#	'instructions'	=> text to display above form; defaults to $self->{datatype_info}{description}
	#	'hidden_fields'	=> ref to associative array of name=value pairs for the hidden fields
	#					  'record' and 'action' will be included by default
	#	'use_params_key' => if 1, will append record datacode (or 'new1') to field names
	#						useful for multi-record forms; if otherwise filled (not 0), will
	#						append that value to the field names
	#	'show_fields'	=> optional: comma-separated list of data_code ID's for the datatype_fields
	#						to build, and you should have 'name,' at the front to include the name
	#					    If blank, all fields are brought in; use this to create a 'mini' form.
	#						** If you use this, be sure to fill the 'skip_blanks' arg for saver(). **

	# sanity
	$data_code = $args{data_code}; # sanity

	# maybe they sent an altcode and it needs to be turned into a primary key?
	if ($data_code =~ /[a-z]/i) {
		($data_code) = $self->altcode_to_data_code($data_code);
	}

	# load up the record, if one was provided and we don't have it
	if ($args{data_code} && !$self->{records}{$data_code}{name}) {
		$self->load( 'data_codes' => [$data_code] );
	}

	# determine the 'action'
	if ($args{action} !~ /create|update/) { # not filled? determine reasonable default
		if ($self->{records}{$data_code}{name}) { # has a record, presume update
			$args{action} = 'update';
		} else { # no record = update
			$args{action} = 'create';
		}
	# if we are creating and have a record loaded, we are doing a 'create-from-another'
	} elsif ($args{action} eq 'create' && $self->{records}{$data_code}{name}) {
		$args{action} = 'create_from';
	}

	# determine our title
	if (!$args{title}) {
		if ($args{action} eq 'create_from') { # little more complex...make a nice phrase for create-from
			$self->{records}{$data_code}{name} = 'Another' if $self->{records}{$data_code}{name} =~ /^(Not Named|Unnamed)$/;
			$args{title} = 'Create '.$self->{datatype_info}{article}.' '.$self->{datatype_info}{name}.' from '.$self->{records}{$data_code}{name};
			$args{action} = 'create'; # simplify the submission process
		} else { # much simpler
			$args{title} = ucfirst($args{action}).' '.$self->{datatype_info}{article}.' '.$self->{datatype_info}{name};
		}
	}

	# submission button
	if (!$args{submit_button_text}) {
		if ($args{action} =~ /create/) {
			$args{submit_button_text} = 'Create '.$self->{datatype_info}{name};
		} else {
			$args{submit_button_text} = 'Update '.$self->{datatype_info}{name};
		}
	}

	# default instructions
	$args{instructions} = $self->{datatype_info}{description} if !$args{instructions};

	# make sure 'record' and 'action' are properly in the hidden fields
	if (!$args{hidden_fields}{action}) {
		$args{hidden_fields}{action} = $args{action};
	}
	if ($args{action} eq 'update' && !$args{hidden_fields}{record}) {
		$args{hidden_fields}{record} = $data_code;
	}
	if ($args{new_parent}) { # where are we going to place this
		$args{hidden_fields}{new_parent} = $args{new_parent};
	}

	# tell  omnitool::tool::action_tool to process our form
	$args{hidden_fields}{form_submitted} = 1;

	# default target_url to %$luggage{uri}
	$args{target_url} = $self->{luggage}{uri} if !$args{target_url};

	# normally, our field names will just match the table_column for their datatype_field,
	# but we may want to update multiple records in one form, so in that case, we will
	# need the field names tied to the records
	if ($args{use_params_key}) {
		# if it's 1 or 'yes', use the record datacode (or new1)
		if ($args{use_params_key} eq '1' || $args{use_params_key} =~ /^Yes$/i) {
			if ($args{action} =~ /create/ || !$data_code) {
				$args{the_params_key} = 'new1'; # JS may increment that '1'
			} elsif ($data_code) { # put in the proper $data_code ID
				$args{the_params_key} = $data_code;
			}

		# so long as it's not 'No', use that value as the extra bit for the field names
		# notice the flexibilty ;)
		} elsif ($args{use_params_key} !~ /^no$/i) {
			$args{the_params_key} = $args{use_params_key};
		}

		# now put that special key into our hidden fields, w/o the leading _
		$args{hidden_fields}{the_params_key} = $args{the_params_key};

		# make sure it ends with an underscore; modifying here before it gets loaded onto fields
		if ($args{the_params_key} && $args{the_params_key} !~ /^\_/) {
			$args{the_params_key} = $args{the_params_key}.'_';
		}

	}

	# convert %args into the beginning of our $form hashref
	$form = \%args;
	# the superfluous bits will be ignored ;)

	# if it has a parent, attach in the form for use in hooks
	if ($self->{metainfo}{$data_code}{parent}) {
		$$form{new_parent} = $self->{metainfo}{$data_code}{parent};

		# and use this new parent if one was not sent in
		$$form{hidden_fields}{new_parent} = $self->{metainfo}{$data_code}{parent}if !$$form{hidden_fields}{new_parent} ;
	}

	# finally time to add in the fields

	# but first ;) how about a hook opportunity to prepare for preparing the fields ;)
	if ($self->can('prepare_for_form_fields')) {
		$self->prepare_for_form_fields($form);
	}

	# crreate field_keys array reference in there for setup_field() to work properly
	$$form{field_keys} = [];

	# we are going to use a separate method to build them one at a time, for the sake
	# of separating some of this code and the possibility that we may want to build
	# just one field randomly later

	# if filled, $args{show_fields} will be a comma-delimited list of fields to provide
	# which is useful to limit the scope of this form
	# it would have the datatype_fields' data_codes, or perhaps 'name'

	# make sure to not show the name if we have those 'show_fields' and not the name
	if ($args{show_fields} && !$self->{belt}->really_in_list('name',$args{show_fields})) {
		$self->{datatype_info}{show_name} = 'No';
	}

	# alright, show the name first if it's permissible
	if ($self->{datatype_info}{show_name} eq 'Yes') {
		$self->setup_field('name',$form,$data_code);

	# it cannot be null though
	} else {
		$$form{hidden_fields}{name}  = 'Not Named';
	}

	# setup_field() will add to %{ $$form{fields} } and @{ $$form{field_keys} }

	# now go through the rest of the fields and build those
	foreach $field (@{ $self->{datatype_info}{fields_key} }) {
		# skip if 'show_fields' is filled and they didn't specify this field
		next if $args{show_fields} && !$self->{belt}->really_in_list($field,$args{show_fields});

		# skip virtual fields
		next if $self->{datatype_info}{fields}{$field}{virtual_field} eq 'Yes';

		# hidden field?
		if ($self->{datatype_info}{fields}{$field}{field_type} eq 'hidden_field') {

			# we the $params_key is for the field name and possible preset
			$params_key = $$form{the_params_key}.$self->{datatype_info}{fields}{$field}{table_column};

			# include it if there is a preset...
			if ($self->{luggage}{params}{$params_key}) { # PSGI params
				$$form{hidden_fields}{$params_key} = $self->{luggage}{params}{$params_key};
			# ...or a loaded-record preset
			} elsif ($self->{records}{$data_code}{$params_key}) { # loaded-record
				$$form{hidden_fields}{$params_key} = $self->{records}{$data_code}{$params_key};

			} elsif ($self->{datatype_info}{fields}{$field}{default_value}) {
				$$form{hidden_fields}{$params_key} = $self->{datatype_info}{fields}{$field}{default_value};
			}

		# otherwise, call our friendly method again
		} else {
			$self->setup_field($field,$form,$data_code);
		}
	}

	# all for a 'post_form_operations' hook to munge the %$form structure before sending out -- DANGER / BE CAREFUL
	if ($self->can('post_form_operations')) {
		$self->post_form_operations($form);
	}

	# return our form and we are done
	return $form;

}

# utility function to build the options hashref/arrayref based on a file path and file extension
# pass 'dir' for the second arg to look for sub-directories
# fill in third arg if you don't want to remove the file extension
sub options_from_directory {
	my $self = shift;
	my ($directory,$file_ext,$keep_ext) = @_;
	$file_ext ||= 'pm';
	return if !$directory;

	my ($dh, %options, @options_keys, $file, @files);

	# 'None' is first option
	$options{None} = 'None';
	push(@options_keys,'None');

	# ready them in the old fashioned way
	opendir($dh, $directory);
	@files = readdir ($dh);
	closedir $dh;
	foreach $file (sort(@files)) {
		# maybe they are looking for a directory?
		if ($file_ext eq 'dir' && (-d "$directory/$file")) {
			$options{$file} = $file;
			push(@options_keys,$file);
		# or a file with a certain extension
		} elsif ($file =~ /\.$file_ext$/) {
			$file =~ s/\.$file_ext// if !$keep_ext;
			$options{$file} = $file;
			push(@options_keys,$file);
		}
	}

    # return results
    return (\%options,\@options_keys);
}

# separate method to build the field info for a particular field
sub setup_field {
	my $self = shift;

	# declare variables
	my ($preset_value, $delimiter, $params_key, $key, $line, $name, $o, $option_values, $options_hook_method, $table_column, $value, $this_part, $part, @street_address_parts, $datatype_table_name,$datatype_display_field,$related_omniclass_object);

	# takes two args: the ID of the datatype_field (or 'name'), the %$form hashref,
	# and the ID for the loaded record we want to use
	# the rest will be in $self
	my ($field,$form,$data_code) = @_;
	return if !$field || !$form; # first two are required

	# we are going to key the %{$$form{fields}} with integers, so figure out which
	# one we are on
	$key = 1 + @{$$form{field_keys}};

	# make sure the keys are unique if in spreadsheet mode
	if ($$form{the_params_key}) {
		$key = $$form{the_params_key}.$key; # no longer an integer ;)
	}

	# add that key to our list
	push(@{$$form{field_keys}}, $key);

	# the name/title field is somewhat easy
	if ($field eq 'name') {

		$$form{fields}{$key} = {
			'title' => $self->{datatype_info}{name}.' Name',
			'name' => $$form{the_params_key}.'name',
			'field_type' => 'short_text',
			'is_required' => 1,
			# 'instructions' => 'Required.',
		};

		# figure name preset; more notes on presets below
		$params_key = $$form{the_params_key}.'name'; # sanity;
		if ($self->{luggage}{params}{$params_key}) { # PSGI params
			$$form{fields}{$key}{preset} = $self->{luggage}{params}{$params_key};

		} elsif ($self->{records}{$data_code}{name}) { # loaded-record
			$$form{fields}{$key}{preset} = $self->{records}{$data_code}{name};
		}

	# the rest is determined by the values set up in the datatype_fields table
	} else {
		# the title is pretty easy
		$$form{fields}{$key}{title} = $self->{datatype_info}{fields}{$field}{name};

		# we will want the table_column at hand for the field name and preset
		$table_column = $self->{datatype_info}{fields}{$field}{table_column};

		# the field name is usually just the table column, and we might include that extra params_key
		$$form{fields}{$key}{name} = $$form{the_params_key}.$table_column;

		# the field_type is very, very easy
		$$form{fields}{$key}{field_type} = $self->{datatype_info}{fields}{$field}{field_type};
		# 'short_text_encrypted' is actually 'short_text', as the encryption stuff happens on the server
		$$form{fields}{$key}{field_type} = 'short_text' if $$form{fields}{$key}{field_type} eq 'short_text_encrypted';

		# same for the instructions
		$$form{fields}{$key}{instructions} = $self->{datatype_info}{fields}{$field}{instructions};

		# whether or not the validate_form should enforce field requirements
		if ($self->{datatype_info}{fields}{$field}{is_required} eq 'Yes') {
			$$form{fields}{$key}{is_required} = 1;
		}

		# if it's an encrypted field, note in the instructions
		if ($self->{datatype_info}{fields}{$field}{field_type} =~ /encrypt/) {
			$$form{fields}{$key}{instructions} .= "\n" if $$form{fields}{$key}{instructions};
			$$form{fields}{$key}{instructions} = 'Encrypted Field. '.$$form{fields}{$key}{instructions};
		}

		# if it is a file-upload with a previous file, note that in the instructions
		if ($$form{action} eq 'update' && $self->{datatype_info}{fields}{$field}{field_type} eq 'file_upload' && $self->{records}{$data_code}{$table_column}) {
			# $attachment_info = $self->{file_manager}->load_file_info( $self->{records}{$r}{$table_column} );
			$$form{fields}{$key}{instructions} .= "\n" if $$form{fields}{$key}{instructions};
			$$form{fields}{$key}{instructions} .= 'Only use if you wish to overwrite the previous file. ('.$self->{records}{$data_code}{$table_column.'_download'}[0]{text}.')';
		}

		# max_length is basically for short_text/short_text_clean fields
		$$form{fields}{$key}{max_length} = $self->{datatype_info}{fields}{$field}{max_length};
		# short_text_tags fields are 64KB
		$$form{fields}{$key}{max_length} = 63000 if $$form{fields}{$key}{field_type} eq 'short_text_tags';
		$$form{fields}{$key}{max_length} ||= 100; # default to 100 characters

		# the preset could be, in this order: a value in the PSGI params, the value already in
		# the record, or the default_value for the datatype field.  Something could be in the
		# PSGI params if (a) we previously tried to submit this form, (b) we set up some
		# start values in the calling action-tool method, or (c) we didn't clear out the
		# tool-display-options for this tool on last execute
		$params_key = $$form{the_params_key}.$table_column; # sanity;
		if ($self->{luggage}{params}{$params_key}) { # PSGI params
			$$form{fields}{$key}{preset} = $self->{luggage}{params}{$params_key};

		} elsif ($self->{records}{$data_code}{$table_column}) { # loaded-record
			$$form{fields}{$key}{preset} = $self->{records}{$data_code}{$table_column};

		} else { # default value for datatype field
			$$form{fields}{$key}{preset} = $self->{datatype_info}{fields}{$field}{default_value};
		}

		# if it's a date field with no preset, use today
		if ($$form{fields}{$key}{field_type} eq 'simple_date' && !$$form{fields}{$key}{preset}) {
			$$form{fields}{$key}{preset} = $self->{belt}->todays_date();
		}

		# if this is a street address, we have to break up our preset into the six parts
		# any saved portion will be already combined into one text block, each piece on its own line
		if ($$form{fields}{$key}{field_type} eq 'street_address') {
			(@street_address_parts) = split /\n/, $$form{fields}{$key}{preset};
			foreach $part ('street_one','street_two','city','state','zip','country') {
				$this_part = shift @street_address_parts; # need this whether we use it or not to stay in sync
				if ($self->{luggage}{params}{$params_key.$part}) { # already PSGI params
					$$form{fields}{$key}{presets}{$part} = $self->{luggage}{params}{$params_key.$part};
				} else { # any possible preset (would have been loaded in)
					$$form{fields}{$key}{presets}{$part} = $this_part;
				}
			}
		}

		# access_roles_select, check_boxes and multi_select fields have a little different structure for presets
		# take the comma-delimited list for those values and make a little sub-hash for form_elements.tt
		if ($$form{fields}{$key}{field_type} =~ /check_boxes|multi_select|access_roles_select/) {
			foreach $preset_value (split /,/, $$form{fields}{$key}{preset}) {
				# need it sorted and testable
				push(@{ $$form{fields}{$key}{preset_keys} },$preset_value);
				$$form{fields}{$key}{presets}{$preset_value} = 1;
			}
		}

		# selects, multi-selects, checkboxes, and radio buttons need to have options values
		# set up.  Please see the example field keyed '9' below for how these look.
		# If we are within a datatype subclass with a hook named 'options_'.$table_column,
		# then call that to construct our options info; otherwise, try for the
		# 'option_values' value for this datatype field
		$options_hook_method = 'options_'.$table_column;
		if ($self->can($options_hook_method)) {
			# should not have to pass any args, as $self is pretty rich already; pass target id + probable parent value
			($$form{fields}{$key}{options},$$form{fields}{$key}{options_keys}) = $self->$options_hook_method($data_code, $$form{new_parent});

		# access_roles_select fields rely on the access roles for this application
		} elsif ($$form{fields}{$key}{field_type} eq 'access_roles_select') {
			# use the method in our parent
			($$form{fields}{$key}{options},$$form{fields}{$key}{options_keys}) = $self->get_access_roles();

			# get an 'open' in there
			$$form{fields}{$key}{options}{Open} = 'Open Access';
			unshift(@{$$form{fields}{$key}{options_keys}}, 'Open');

		# maybe they want to simply relate to another omniclass datatype via
		# the prep_menu_options() method: will be table_name.display_field
		} elsif ($self->{datatype_info}{fields}{$field}{option_values} =~ /^[a-z0-9\_]+\.[a-z0-9\_]+$/i) {
			($datatype_table_name,$datatype_display_field) = split /\./, $self->{datatype_info}{fields}{$field}{option_values};
			$related_omniclass_object = $self->get_omniclass_object(
				'dt' => $datatype_table_name,
				'load_all' => 1,
			);
			($$form{fields}{$key}{options}, $$form{fields}{$key}{options_keys}) = $related_omniclass_object->prep_menu_options($datatype_display_field);

		# otherwise a list in the field specification; could be just comma-separated,
		# double-semicolon-separated, or name=value pairs on separate lines
		} elsif ($self->{datatype_info}{fields}{$field}{option_values}) {
			$option_values = $self->{datatype_info}{fields}{$field}{option_values}; # sanity
			if ($option_values =~ /\n/) { # name=value on separate lines
				# fairly-standard parsing; start by breaking up by lines
				foreach $line (split /\n/, $option_values) {
					# then break by equals sign
					($name,$value) = split /=/, $line;
					# now feed it in
					$$form{fields}{$key}{options}{$name} = $value;
					push(@{ $$form{fields}{$key}{options_keys} }, $name);
					# if I were a real perl programmer, the last 10 lines would have been one line,
					# probably with no alphanumeric characters
				}

			} else { # ;;- or ,-delimited
				# figure out the delimier
				if ($option_values =~ /;;/) { # ;;-delimited
					$delimiter = ';;';
				} else { # assume ,-delimited
					$delimiter = ',';
				}

				# break it up and feed it in
				foreach $o (split /$delimiter/, $option_values) {
					$$form{fields}{$key}{options}{$o} = $o;
					push(@{ $$form{fields}{$key}{options_keys} }, $o);
				}
			}
		}
		# end options-handling
	} # end field-building
} # end method ;)

1;

__END__

Here is an example of a %$form structure which supports one of each of our
supported field types, usable with your form-creating Jemplates:

Note: You do NOT have to use numbers for your field keys.

	$form = {
		'target_url' => '/tools/some/action/method',
		'title' => 'How Great is Ginger?',
		'show_title' => 1, # fill if you want ModalForm.tt to show the form title; otherwise unnecessary
		'instructions' => 'Info to appear below title and above fields.',
		'submit_button_text' => 'Text for Submit Button',
		'hidden_fields' => {
			'field_name1' => 'field_value',
		},
		'field_keys' => [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26],
		'fields' => { # integer keys, easily sorted
			1 => {
				'title' => 'Color of Ginger',
				'name' => 'ginger_color',
				'preset' => 'Perfect',
				'field_type' => 'short_text',
				'instructions' => 'Color of Heaven.',
				'is_required' => 1, # will be required for form submit; works for text fields
				'max_length' => 200, # allow up to 200 characters,
				'readonly' => 'readonly', # include this to lock the field, otherwise leave out
			},
			2 => {
				'title' => 'Is Ginger Wonderful?',
				'name' => 'is_ginger_wonderful',
				'class' => 'some_css_class', # for modal and full-screen forms only
				'preset' => 'Yes',
				'field_type' => 'yes_no_select',
				'instructions' => 'I hope it appears',
			},
			3 => {
				'title' => 'How is Ginger Wonderful?',
				'name' => 'how_is_ginger_wonderful',
				'preset' => 'She is sooo wonderful!',
				'field_type' => 'long_text',
				'instructions' => 'I hope it appears',
			},
			4 => {
				'title' => "Ginger's Birthday",
				'name' => 'gingers_birthday',
				'preset' => '1999-08-01',
				'field_type' => 'simple_date',
			},
			5 => {  # NOTE: THIS IS NOT SUPPORTED IN OMNICLASS; only here for example / usable in search dialogs
					# if you need a date-range, use two simple_date fields.  Possible future support, later, much later.
				'title' => "Ginger's Reign of Glory",
				'start_name' => 'gingers_reign_start',
				'end_name' => 'gingers_reign_end',
				'preset_start' => '1999-08-01',
				'preset_end' => '2019-08-01',
				'field_type' => 'date_range',
			},
			6 => {
				'title' => "Ginger's Phone Number",
				'name' => 'gingers_phone',
				'preset' => '9192706916',
				'field_type' => 'phone_number',
			},
			7 => {
				'title' => "Ginger's Password",
				'name' => 'gingers_pw',
				'preset' => 'hail',
				'field_type' => 'password',
			},
			8 => {
				'title' => "Ginger's Status",
				'name' => 'gingers_status',
				'preset' => 'Active',
				'field_type' => 'active_status_select',
			},
			9 => {
				'title' => "Who is the Best?",
				'name' => 'gingers_chooser',
				'preset' => 'ging',
				'options_keys' => ['lb','mel','ging','pep','eric'],
				'options' => {
					'ging' => 'Ginger',
					'pep' => 'Pepper',
					'lb' => 'Lorelei',
					'eric' => 'Eric',
					'mel' => 'Melanie',
				},
				'field_type' => 'single_select', # use 'single_select_plain' for non-chosen / regular menu's
				'onchange' => qq{SOME_JAVASCRIPT_CODE}, # optional: JS to execute for 'onchange' event
														# better to use jquery to add via selectors
				# or, if you want to have this menu trigger the loading of another menu:
				'trigger_menu_target' => 'ID of menu that will get triggered/built',
				'trigger_menu_server_method' => 'subroutine_name_on_sever_to_generation_options',
			},
			10 => {
				'title' => "What Powers Does Ginger Have?",
				'name' => 'gingers_powers',
				'presets' => {
					'speed' => 1,
					'healing' => 1,
					'strength' => 1
				},
				'options_keys' => ['strength','mercy','healing','patience','speed'],
				'options' => {
					'patience' => 'Great Patience',
					'mercy' => 'Kindness and Mercy',
					'strength' => 'Infinite Strength',
					'healing' => 'Instant Healing',
					'speed' => 'Unimaginable Speed',
				},
				'field_type' => 'multi_select_ordered',
				# 'multi_select_ordered' allows-for and preserves ordering of options
				# 'multi_select_plain' uses jquery.chosen and is pretty, but no ordering
			},
			11 => {
				'title' => "Ginger's Home Address",
				'name' => 'gingers_address',
				'presets' => {
					'street_one' => '5213 Greyfield Blvd',
					'city' => 'Durham',
					'state' => 'NC',
					'zip' => '27713',
					'country' => 'USA',
				},
				'field_type' => 'street_address',
			},
			12 => {
				'title' => "Ginger's Best Trait",
				'name' => 'gingers_best_trait',
				'preset' => 'beauty',
				'options_keys' => ['brains','beauty','cunning','smell','mercy'],
				'options' => {
					'brains' => 'Her Brains',
					'beauty' => 'Her Beauty',
					'cunning' => 'Her Cunning',
					'smell' => 'Her Smell',
					'mercy' => 'Her Mercy',
				},
				'field_type' => 'radio_buttons',
			},
			13 => {
				'title' => "Ginger's Email Address",
				'name' => 'gingers_email',
				'presets' => {
					'username' => 'ginger',
					'domain' => 'chernoff.org'
				},
				'field_type' => 'email_address',
			},
			14 => {
				'title' => "Ginger's Tolerance for Idiots",
				'name' => 'gingers_tolerance_idiots',
				'preset' => 10,
				'field_type' => 'low_integer',
			},
			15 => {
				'title' => "Ginger's IQ",
				'name' => 'gingers_iq',
				'preset' => 876876,
				'field_type' => 'high_integer',
			},
			16 => {
				'title' => "Ginger's Thoughts per Second",
				'name' => 'gingers_thoughts_per_second',
				'preset' => '75839.65,
				'field_type' => 'low_decimal',
			},
			17 => {
				'title' => "Ginger's Monetary Value",
				'name' => 'gingers_value',
				'preset' => '999999999999.99',
				'field_type' => 'high_decimal',
			},
			18 => {
				'title' => "Ginger's Home Page",
				'name' => 'gingers_home_page',
				# 'preset' => 876876,
				'field_type' => 'web_url',
			},
			19 => {
				'title' => "Ginger's Birth Month",
				'name' => 'gingers_birth_month',
				'preset' => 'August 1999',
				'field_type' => 'month_name',
			},
			20 => {
				'title' => "Ginger's Talents",
				'name' => 'gingers_talents',
				'presets' => {
					'eating' => 1,
					'healing' => 1,
				},
				'options_keys' => ['healing','running','killing','eating'],
				'options' => {
					'healing' => 'Healing',
					'running' => 'Running',
					'killing' => 'Killing',
					'eating' => 'Eating',
				},
				'field_type' => 'check_boxes',
			},
			21 => {
				'title' => "Ginger's Picture",
				'name' => 'gingers_picture',
				'preset' => 'ginger.jpg',
				'field_type' => 'file_upload',
			},
			22 => {
				'title' => "Ginger's Life Story",
				'name' => 'gingers_life',
				'field_type' => 'rich_long_text',
			},
			23 => {
				'title' => "Ginger's Access Control",
				'name' => 'gingers_access',
				'field_type' => 'access_roles_select',
			},
			24 => {
				'title' => "Font Awesome Icon",
				'name' => 'ginger_icon',
				'field_type' => 'font_awesome_select',
				'preset' => 'fa-wrench',
			},
			25 => {
				'title' => "Display Text",
				'name' => 'plain_text_to_show',
				'field_type' => 'just_text',
				'preset' => 'These words would be displayed.',
			},
			26 => {
				'title' => "Tags Field",
				'name' => 'facets_of_ginger',
				'field_type' => 'short_text_tags',
				'preset' => 'Great,Wonderful,Magnificent',
				# this one will send back a comma-selected list; you will need an
				# 'options_' method to power the auto-suggester for this field
			},
			27 => { # for "I am not a robot" Google ReCaptcha.  Do not change, and look at https://www.google.com/recaptcha/admin
				'title' => 'Please Verify',
				'name' => 'recaptcha',
				'field_type' => 'recaptcha',
				'recaptcha_key' => $ENV{RECAPTCHA_SITEKEY},
			},

		},
	};


text:
package org.shaf.core.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.shaf.core._helper_.DummyStringObject;

/**
 * The class {@code RepositoryTest} contains tests for the class
 * {@link Repository}.
 *
 * @author Mykola Galushka
 */
public class RepositoryTest {

	/**
	 * The repository to test.
	 */
	private Repository<String, DummyStringObject> repository;

	/**
	 * Perform the pre-test initialization.
	 *
	 * @throws Exception
	 *             if the initialization fails for some reason.
	 */
	@Before
	public void setUp() throws Exception {
		this.repository = new Repository<String, DummyStringObject>() {

			@Override
			protected String[] keys(DummyStringObject obj) {
				return obj.getValue().split("\\:")[0].split("\\,");
			}
		};
	}

	/**
	 * Perform post-test clean-up.
	 *
	 * @throws Exception
	 *             if the clean-up fails for some reason.
	 */
	@After
	public void tearDown() throws Exception {
	}

	/**
	 * Run the register/get method tests.
	 *
	 * @throws Exception
	 *             if the test fails for some reason.
	 */
	@Test
	public void testRegisterGet() {
		this.repository.register(new DummyStringObject("a1,a2"));
		this.repository.register(new DummyStringObject("b1,b2"));
		this.repository.register(new DummyStringObject("c1,c2"));

		try {
			this.repository.register((DummyStringObject) null);
			fail();
		} catch (Exception exc) {
			assertEquals(NullPointerException.class, exc.getClass());
		}

		assertEquals("a1,a2", this.repository.get("a1").getValue());
		assertEquals("b1,b2", this.repository.get("b1").getValue());
		assertEquals("c1,c2", this.repository.get("c1").getValue());
		assertEquals("a1,a2", this.repository.get("a2").getValue());
		assertEquals("b1,b2", this.repository.get("b2").getValue());
		assertEquals("c1,c2", this.repository.get("c2").getValue());
		assertNull(this.repository.get("something"));

		try {
			this.repository.get(null);
			fail();
		} catch (Exception exc) {
			assertEquals(NullPointerException.class, exc.getClass());
		}
	}

	/**
	 * Run the contains method tests.
	 *
	 * @throws Exception
	 *             if the test fails for some reason.
	 */
	@Test
	public void testContains() {
		this.repository.register(new DummyStringObject("a1,a2"));

		assertTrue(this.repository.contains("a1"));
		assertTrue(this.repository.contains("a2"));
		assertFalse(this.repository.contains("something"));

		try {
			this.repository.contains(null);
			fail();
		} catch (Exception exc) {
			assertEquals(NullPointerException.class, exc.getClass());
		}
	}

	/**
	 * Run the remove method tests.
	 *
	 * @throws Exception
	 *             if the test fails for some reason.
	 */
	@Test
	public void testRemove() {
		this.repository.register(new DummyStringObject("a1,a2"));
		assertTrue(this.repository.contains("a1"));
		assertTrue(this.repository.contains("a2"));

		assertEquals("a1,a2", this.repository.remove("a1").getValue());
		assertFalse(this.repository.contains("a1"));
		assertTrue(this.repository.contains("a2"));

		assertEquals("a1,a2", this.repository.remove("a2").getValue());
		assertFalse(this.repository.contains("a1"));
		assertFalse(this.repository.contains("a2"));

		try {
			this.repository.remove(null);
			fail();
		} catch (Exception exc) {
			assertEquals(NullPointerException.class, exc.getClass());
		}
	}

	/**
	 * Run the iterator method tests.
	 *
	 * @throws Exception
	 *             if the test fails for some reason.
	 */
	@Test
	public void testIterator() {
		assertNotNull(this.repository.iterator());
	}

	/**
	 * Run the print method tests.
	 *
	 * @throws Exception
	 *             if the test fails for some reason.
	 */
	@Test
	public void testPrint() {
		this.repository.register(new DummyStringObject("a1,a2"));
		this.repository.register(new DummyStringObject("b1,b2"));
		this.repository.register(new DummyStringObject("c1,c2"));

		String outcome = this.repository.toString();

		assertNotNull(outcome);
		assertTrue(outcome.contains("a1=DummyStringObject{value=a1,a2}"));
		assertTrue(outcome.contains("a2=DummyStringObject{value=a1,a2}"));
		assertTrue(outcome.contains("b1=DummyStringObject{value=b1,b2}"));
		assertTrue(outcome.contains("b2=DummyStringObject{value=b1,b2}"));
		assertTrue(outcome.contains("c1=DummyStringObject{value=c1,c2}"));
		assertTrue(outcome.contains("c2=DummyStringObject{value=c1,c2}"));
	}
}

redpajama_set_name: RedPajamaGithub


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef FM_LAST_MOOST_SERVICE_SKELETON_H_
#define FM_LAST_MOOST_SERVICE_SKELETON_H_

/**
 * \file skeleton.hpp
 *
 * The moost::service::skeleton template encapsulates common patterns used to run
 * services at Last.fm. It makes writing new services (and adapting old services)
 * very easy.
 *
 * It covers the following areas:
 *
 *   - exception handling: it ensures all exceptions will be handled
 *
 *   - command line option handling (both common and service-specific)
 *
 *   - command line option validation
 *
 *   - optional process ownership handling (i.e. changing process ownership
 *     from root to a less privileged user)
 *
 *   - optional logging framework initialisation
 *
 *   - setup and configuration of moost::process::service
 *
 * All customisation is done either template policies or by subclassing the
 * moost::service::skeleton template:

\code
// MyService is a moost::process::service compatible class

class MyServiceSkeleton : public moost::service::skeleton<MyService, NoProcessOwnershipPolicy>
{
private:
   int m_port;

public:
   virtual std::string name() const        { return "MyService"; }
   virtual std::string description() const { return "Bla bla."; }
   virtual std::string copyright() const   { return "Last.fm 2011"; }

   virtual void add_options(boost::program_options::options_description& od)
   {
      od.add_options()
         ("port,p", boost::program_options::value<int>(&m_port)->default_value(4711), "server port")
         ;
   }

   shared_ptr<MyService> create_service_instance()
   {
      return shared_ptr<MyService>(new MyService(m_port, name()));
   }
};
\endcode

 * With the above class, your main() function becomes as simple as:

\code
int main(int argc, char **argv)
{
   return moost::service::main<MyServiceSkeleton>(argc, argv);
}
\endcode

 * Please do not put any other code in main(). Put any other setup code you may need
 * either in the constructor of your service skeleton or in an appropriate overridable
 * method provided by \c moost::service::skeleton.
 *
 * The advantage of using moost::service::skeleton for your service is that all
 * functionality shared by the various services will look alike and work exactly
 * the same as in every other service. This greatly simplifies service maintenance
 * and other tasks like writing init scripts. It also ensures that once a new common
 * feature is added, all services will support that feature as soon as they're
 * recompiled.
 *
 * Of course, not all services are the same, and so you can configure moost::service::skeleton
 * to your liking. This is done either by template policies or by overriding methods.
 * Currently, the following policies are supported:
 *
 * - The \c ProcessOwnershipPolicy controls whether the service process supports changing
 *   ownership at runtime. The \c UidGidProcessOwnershipPolicy will provide the \c --uid
 *   and \c --gid command line options and enforce them if the process is run as root.
 *   If you don't require this, use the \c NoProcessOwnershipPolicy instead.
 *
 * - The \c LoggingPolicy controls whether or not the service process supports logging.
 *   By default, the \c MoostLoggingPolicy enables logging using the standard logging
 *   framework. This adds the \c --log-level command line option to set a default log
 *   level for moost::logging::standard_console and/or the remote shell. If your service
 *   doesn't support logging, you can use the \c NoLoggingPolicy instead.
 *
 * - The \c ConsoleLoggerPolicy is used to configure the moost::process::service instance
 *   and is taken from the \c LoggingPolicy by default.
 *
 * Here's an overview of what happens inside moost::service::main:
 *
 * - First of all, a try-catch-handler is set up. This handler is used purely for exceptions
 *   happening during construction of the skeleton instance. Once the skeleton instance is
 *   created, its main() method is called.
 *
 * - The skeleton's main() method is used only to set up a custom try-catch-handler. If
 *   you want to override the try-catch-handler, override main(). The try block only calls
 *   safe_main().
 *
 * - Now, command line options are gathered from various sources (policies, add_options())
 *   and all command line arguments are parsed.
 *
 * - If no command line arguments were found or the \c --help option was present, the
 *   skeleton writes a help message to the console and returns.
 *
 * - Next, command line options are validated.
 *
 * - Now the process ownership is changed according to the chosen policy.
 *
 * - Finally, the moost::process::service object is created and initialised using
 *   the instance returned by create_service_instance(). The moost::process::service
 *   object is configured based on the command line options provided and then its
 *   run() method is called.
 */

#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>

#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/filesystem.hpp>

#include "../logging.hpp"
#include "../process/service.hpp"
#include "../process/ownership.hpp"
#include "standard_options.hpp"
#include "../utils/assert.hpp"

namespace moost { namespace service {

/**
 * \brief This policy implements no process ownership handling
 */
class NoProcessOwnershipPolicy
{
public:
   void add_options(boost::program_options::options_description&, option_validator&)
   {
   }

   void validate_options(const boost::program_options::variables_map&) const
   {
   }

   void change_ownership(const boost::program_options::variables_map&)
   {
   }
};

/**
 * \brief This policy implements process ownership handling based on user/groud IDs
 */
class UidGidProcessOwnershipPolicy
{
private:
   moost::process::ownership own;
   std::string m_uid;
   std::string m_gid;

public:
   void add_options(boost::program_options::options_description& od, option_validator&)
   {
      od.add_options()
         ("uid", boost::program_options::value<std::string>(&m_uid), "run process as this user")
         ("gid", boost::program_options::value<std::string>(&m_gid), "run process as this group")
         ;
   }

   void validate_options(const boost::program_options::variables_map& vm) const
   {
      if (own.is_superuser() && vm.count("uid") == 0)
      {
         throw std::runtime_error("please use --uid option when running as root");
      }

      if (vm.count("uid") == 0 && vm.count("gid") != 0)
      {
         throw std::runtime_error("cannot use --gid without --uid option");
      }
   }

   void change_ownership(const boost::program_options::variables_map& vm)
   {
      if (vm.count("uid"))
      {
         own.drop_privileges(m_uid, m_gid);
      }
   }
};

/**
 * \brief This policy implements no logging
 */
class NoLoggingPolicy
{
public:
   typedef moost::process::NoConsoleLoggerPolicy DefaultConsoleLoggerPolicy;

   void set_init_verbose(bool)
   {
   }

   void add_options(boost::program_options::options_description&, option_validator&)
   {
   }

   void validate_options(const boost::program_options::variables_map&) const
   {
   }

   bool initialise(const std::string&, const boost::program_options::variables_map&)
   {
      return false;
   }

   template <class T>
   void configure_service(T&) const
   {
   }
};

/**
 * \brief This policy implements logging using moost::logging
 */
class MoostLoggingPolicy
{
private:
   std::string m_log_level;
   std::string m_log_config;
   bool m_verbose;

public:
   typedef moost::process::MoostStandardConsoleLoggerPolicy DefaultConsoleLoggerPolicy;

   MoostLoggingPolicy()
      : m_verbose(false)
   {
   }

   void set_init_verbose(bool verbose)
   {
      m_verbose = verbose;
   }

   void add_options(boost::program_options::options_description& od, option_validator& opt_validator)
   {
      standard_options(od, opt_validator)
         ("log-level,l", boost::program_options::value<std::string>(&m_log_level)->default_value("info"), "default shell log level")
         ("logging-config", boost::program_options::value<std::string>(&m_log_config), "logging configuration file", validator::file(m_log_config))
         ;
   }

   void validate_options(const boost::program_options::variables_map&) const
   {
      log4cxx::LevelPtr invalid_level(new log4cxx::Level(-1, LOG4CXX_STR("INVALID"), 7 ));
      log4cxx::LevelPtr level = log4cxx::Level::toLevel(m_log_level, invalid_level);

      if (level == invalid_level)
      {
         throw std::runtime_error("invalid log level");
      }

      if (!m_log_config.empty() && !boost::filesystem::exists(m_log_config))
      {
         throw std::runtime_error("logging configuration file does not exist: " + m_log_config);
      }
   }

   bool initialise(const std::string& program_name, const boost::program_options::variables_map&)
   {
      moost::logging::global & glog = moost::logging::global_singleton::instance();

      glog.attach_ostream(std::cout);

      if (!(m_log_config.empty() ? glog.enable(program_name)
                                 : glog.enable(boost::filesystem::path(m_log_config))))
      {
         // the root (default) logger was not configured from a config file so we'll do our own thing with it

#if defined(NDEBUG) && !defined(SERVICE_SKELETON_NOCFG_LOG_ALL)
         MLOG_SET_DEFAULT_LEVEL_INFO();
#else
         MLOG_SET_DEFAULT_LEVEL_ALL();
#endif
      }

      return true;
   }

   template <class T>
   void configure_service(T& service) const
   {
      service.set_log_level(m_log_level);
      service.set_appender_factory(moost::service::appender_factory_ptr(new moost::service::log4cxx_appender_factory(m_log_level)));
   }
};

/**
 * \brief Configurable template implementing common functionality to run a service
 */
template <class ServiceT,
          class ProcessOwnershipPolicy = UidGidProcessOwnershipPolicy,
          class LoggingPolicy = MoostLoggingPolicy,
          class ConsoleLoggerPolicy = typename LoggingPolicy::DefaultConsoleLoggerPolicy>
class skeleton : public boost::noncopyable
{
private:
   bool m_logging_enabled;
   bool m_options_valid;
   std::string m_pidfile;
   unsigned short m_shell_port;
   boost::program_options::variables_map m_opt_varmap;
   ProcessOwnershipPolicy m_ownership;
   LoggingPolicy m_logging;
   std::string m_program_name;

   typedef moost::process::service<ServiceT, ConsoleLoggerPolicy> ProcessServiceType;

   class child_init_func
   {
   public:
      bool operator()()
      {
         m_log_enabled = m_log.initialise(m_program_name, m_varmap);
         m_log.configure_service(m_svc);
         return false;
      }

      child_init_func(ProcessServiceType& svc, LoggingPolicy& log, bool& log_enabled, const std::string& program_name, const boost::program_options::variables_map& varmap)
        : m_svc(svc)
        , m_log(log)
        , m_log_enabled(log_enabled)
        , m_program_name(program_name)
        , m_varmap(varmap)
      {
      }

   private:
      ProcessServiceType& m_svc;
      LoggingPolicy& m_log;
      bool& m_log_enabled;
      const std::string m_program_name;
      const boost::program_options::variables_map& m_varmap;
   };

protected:
   typedef ServiceT ServiceType;

   /**
    * \brief Add custom options for your service
    *
    * Override this if you want to define any extra command line options for your service.
    */
   virtual void add_options(boost::program_options::options_description&)
   {
   }

   /**
    * \brief Add custom options for your service, with validator support
    *
    * Override this if you want to define any extra command line options for your service.
    */
   virtual void add_options(boost::program_options::options_description&, option_validator&)
   {
   }

   /**
    * \brief Add options validation code
    *
    * Override this if you want to supply code to check command line options consistency.
    * You can access the raw option map using \c options().
    */
   virtual void validate_options() const
   {
   }

   /**
    * \brief Return the service name.
    */
   virtual std::string name() const = 0;

   /**
    * \brief Return the service version.
    */
   virtual std::string version() const = 0;

   /**
    * \brief Return short description of the service
    */
   virtual std::string description() const = 0;

   /**
    * \brief Return copyright string
    */
   virtual std::string copyright() const = 0;

   /**
    * \brief Create the service instance
    *
    * This method creates the instance of the service class after all checks have been
    * carried out, logging is set up and the process is running as a non-privileged user.
    */
   virtual boost::shared_ptr<ServiceType> create_service_instance() = 0;

   /**
    * \brief Return header for help message
    *
    * Override this if you really need full control over the service header that
    * is written to the console along with the command line options description.
    */
   virtual std::string help_header() const
   {
      std::ostringstream oss;
      oss << "\r\n" << name() << ": " << description() << "\r\n\r\n";
      oss << "Version: " << version() << " :: Build: " << __DATE__ << " (" << __TIME__ << ") :: (c) "
          << copyright() << "\r\n\r\n";
      return oss.str();
   }

   /**
    * \brief Check whether or not the logging framework is already set up.
    *
    * This is primarily useful for implementing custom catch() blocks in main().
    */
   bool logging_enabled() const
   {
      return m_logging_enabled;
   }

   /**
    * \brief Read-only access to command line options variable map.
    *
    * Call this method to validate/access command line options.
    */
   const boost::program_options::variables_map& options() const
   {
      if (!m_options_valid)
      {
         throw std::runtime_error("(BUG) attempt to access options map before initialisation");
      }

      return m_opt_varmap;
   }

   /**
    * \brief Check whether the service is about to be started in daemon mode.
    */
   bool running_as_daemon() const
   {
      return options().count("daemon") != 0;
   }

   /**
    * \brief Set up and process command line options.
    */
   void process_cmdline_options(boost::program_options::options_description& cmdline_options, option_validator& opt_validator, int argc, char **argv)
   {
      add_options(cmdline_options);
      add_options(cmdline_options, opt_validator);

      standard_options(cmdline_options, opt_validator)
         .port("shell-port", "remote shell port when daemonised", m_shell_port)
         ("pidfile", boost::program_options::value<std::string>(&m_pidfile), "pidfile location")
         ("noerr,n", "shut up stderr (for thrift)")
         ("help,h", "output help message and exit")
         ("version", "output service version and exit")
         ("daemon", "daemonise (fork to background)")
         ;

      m_ownership.add_options(cmdline_options, opt_validator);
      m_logging.add_options(cmdline_options, opt_validator);

      boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cmdline_options), m_opt_varmap);
      boost::program_options::notify(m_opt_varmap);
      m_options_valid = true;
   }

   /**
    * \brief Safe main() implementation.
    */
   int safe_main(int argc, char **argv, bool noargs)
   {
      m_program_name = argv[0];

      // process command line options first

      boost::program_options::options_description cmdline_options;
      option_validator opt_validator;
      process_cmdline_options(cmdline_options, opt_validator, argc, argv);

      if (options().count("help") || (!noargs && argc == 1))
      {
         std::cout << help_header() << cmdline_options << std::endl;
         return 0; // nothing more to do here
      }

      if (options().count("version"))
      {
         std::cout << version() << std::endl;
         return 0; // nothing more to do here
      }

      // some basic command line options consistency checks

      if (running_as_daemon() && m_shell_port == 0)
      {
         throw std::runtime_error("please use --shell-port option when running with --daemon");
      }

      moost::utils::assert_absolute_path(m_pidfile, "pidfile");

      // service specific checks

      validator::constraints_map_t opt_constraints;

      if (running_as_daemon())
      {
         opt_constraints["absolute_filenames"] = "1";
      }

      opt_validator(options(), opt_constraints);
      m_ownership.validate_options(options());
      m_logging.validate_options(options());
      validate_options();

      // configure logging initialisation verbosity

      m_logging.set_init_verbose(!running_as_daemon());

      // change ownership according to policy

      m_ownership.change_ownership(options());

      run();

      return 0;  // apparently, we've managed to finish cleanly
   }

   /**
    * \brief Run the service
    *
    * Override this if you want to do anything else than just running the service
    * depending on the commandline options. To actually run the service, call
    * run_service() from within your override.
    */
   virtual void run()
   {
      run_service();
   }

   /**
    * \brief Run the service
    *
    * Creates, configures and runs a service instance. Make sure you call this from
    * run() at some point when overriding it.
    */
   void run_service()
   {
      ProcessServiceType service(create_service_instance());

      child_init_func child_init(service, m_logging, m_logging_enabled, m_program_name, options());

      service.set_child_init_func(boost::ref(child_init));

      if (options().count("noerr"))
      {
         service.set_default_stderr_state(false);
      }

      if (!m_pidfile.empty())
      {
         service.set_pidfile(m_pidfile);
      }

      if (m_shell_port)
      {
         service.set_shell_port(m_shell_port);
      }

      service.run(running_as_daemon());
   }

public:
   skeleton()
      : m_logging_enabled(false)
      , m_options_valid(false)
      , m_shell_port(0)
   {
   }

   virtual ~skeleton()
   {
   }

   /**
    * \brief Main entry point for skeleton.
    *
    * Override this if you want to catch exceptions other than std:::exception or you
    * want to supply custom exception handling code. Make sure you don't change the
    * try { } block in your implementation and only call safe_main().
    */
   virtual int main(int argc, char **argv, bool noargs)
   {
      try
      {
         return safe_main(argc, argv, noargs);
      }
      catch (const std::exception& e)
      {
         if (logging_enabled())
         {
            MLOG_DEFAULT_FATAL(e.what());
         }

         throw; // will be caught by main template below
      }
      catch (...)
      {
         if (logging_enabled())
         {
            MLOG_DEFAULT_FATAL("unknown exception caught");
         }

         throw; // will be caught by main template below
      }

      return 1;
   }
};

template <class SkeletonT>
int main(int argc, char **argv, bool noargs = false)
{
   // This try/catch catches exceptions during construction of the skeleton instance
   // (those should be really rare).

   // Any other exceptions will be caught by the skeleton's main() implementation.

   try
   {
      return SkeletonT().main(argc, argv, noargs);
   }
   catch (const std::exception& e)
   {
      std::cerr << "ERROR: " << e.what() << std::endl;
   }
   catch (...)
   {
      std::cerr << "ERROR: unknown exception caught" << std::endl;
   }

   return 1;
}

} }

#endif


text:
"use strict";

const UIEventImpl = require("./UIEvent-impl").implementation;

class CompositionEventImpl extends UIEventImpl {
  initCompositionEvent(type, bubbles, cancelable, view, data) {
    if (this._dispatchFlag) {
      return;
    }

    this.initUIEvent(type, bubbles, cancelable, view, 0);
    this.data = data;
  }
}

module.exports = {
  implementation: CompositionEventImpl
};


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Programming/Coding Assignment
% LaTeX Template
%
% This template has been downloaded from:
% http://www.latextemplates.com
%
% Original author:
% Ted Pavlic (http://www.tedpavlic.com)
%
% Note:
% The \lipsum[#] commands throughout this template generate dummy text
% to fill the template out. These commands should all be removed when
% writing assignment content.
%
% This template uses a Perl script as an example snippet of code, most other
% languages are also usable. Configure them in the "CODE INCLUSION
% CONFIGURATION" section.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%	PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass{article}

\usepackage{fancyhdr} % Required for custom headers
\usepackage{lastpage} % Required to determine the last page for the footer
\usepackage{extramarks} % Required for headers and footers
\usepackage[usenames,dvipsnames]{color} % Required for custom colors
\usepackage{graphicx} % Required to insert images
\usepackage{listings} % Required for insertion of code
\usepackage{courier} % Required for the courier font
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{mathrsfs} % math script characters

% Margins
\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in

\linespread{1.1} % Line spacing

% Set up the header and footer
\pagestyle{fancy}
\lhead{\hmwkAuthorName} % Top left header
\chead{\hmwkTitle} % Top center head
\rhead{\firstxmark} % Top right header
\lfoot{\lastxmark} % Bottom left footer
\cfoot{} % Bottom center footer
\rfoot{Page\ \thepage\ of\ \protect\pageref{LastPage}} % Bottom right footer
\renewcommand\headrulewidth{0.4pt} % Size of the header rule
\renewcommand\footrulewidth{0.4pt} % Size of the footer rule

\setlength\parindent{0pt} % Removes all indentation from paragraphs

%----------------------------------------------------------------------------------------
%	CODE INCLUSION CONFIGURATION
%----------------------------------------------------------------------------------------

\definecolor{MyDarkGreen}{rgb}{0.0,0.4,0.0} % This is the color used for comments
\lstloadlanguages{Perl} % Load Perl syntax for listings, for a list of other languages supported see: ftp://ftp.tex.ac.uk/tex-archive/macros/latex/contrib/listings/listings.pdf
\lstset{language=Java, % Use Java in this example
        frame=single, % Single frame around code
        basicstyle=\small\ttfamily, % Use small true type font
        keywordstyle=[1]\color{Blue}\bf, % Perl functions bold and blue
        keywordstyle=[2]\color{Purple}, % Perl function arguments purple
        keywordstyle=[3]\color{Blue}\underbar, % Custom functions underlined and blue
        identifierstyle=, % Nothing special about identifiers
        commentstyle=\usefont{T1}{pcr}{m}{sl}\color{MyDarkGreen}\small, % Comments small dark green courier font
        stringstyle=\color{Purple}, % Strings are purple
        showstringspaces=false, % Don't put marks in string spaces
        tabsize=5, % 5 spaces per tab
        %
        % Put standard Perl functions not included in the default language here
        morekeywords={rand},
        %
        % Put Perl function parameters here
        morekeywords=[2]{on, off, interp},
        %
        % Put user defined functions here
        morekeywords=[3]{test},
       	%
        morecomment=[l][\color{Blue}]{...}, % Line continuation (...) like blue comment
        numbers=left, % Line numbers on left
        firstnumber=1, % Line numbers start with line 1
        numberstyle=\tiny\color{Blue}, % Line numbers are blue and small
        stepnumber=5 % Line numbers go in steps of 5
}

% Creates a new command to include a java script, the first parameter is the filename of the script (without .pl), the second parameter is the caption
\newcommand{\javascript}[2]{
\begin{itemize}
\item[]\lstinputlisting[caption=#2,label=#1]{#1.java}
\end{itemize}
}

%----------------------------------------------------------------------------------------
%	DOCUMENT STRUCTURE COMMANDS
%	Skip this unless you know what you're doing
%----------------------------------------------------------------------------------------

% Header and footer for when a page split occurs within a problem environment
\newcommand{\enterProblemHeader}[1]{
\nobreak\extramarks{#1}{#1 continued on next page\ldots}\nobreak
\nobreak\extramarks{#1 (continued)}{#1 continued on next page\ldots}\nobreak
}

% Header and footer for when a page split occurs between problem environments
\newcommand{\exitProblemHeader}[1]{
\nobreak\extramarks{#1 (continued)}{#1 continued on next page\ldots}\nobreak
\nobreak\extramarks{#1}{}\nobreak
}

\setcounter{secnumdepth}{0} % Removes default section numbers
\newcounter{homeworkProblemCounter} % Creates a counter to keep track of the number of problems

\newcommand{\homeworkProblemName}{}
\newenvironment{homeworkProblem}[1][Problem \arabic{homeworkProblemCounter}]{ % Makes a new environment called homeworkProblem which takes 1 argument (custom name) but the default is "Problem #"
\stepcounter{homeworkProblemCounter} % Increase counter for number of problems
\renewcommand{\homeworkProblemName}{#1} % Assign \homeworkProblemName the name of the problem
\section{\homeworkProblemName} % Make a section in the document with the custom problem count
\enterProblemHeader{\homeworkProblemName} % Header and footer within the environment
}{
\exitProblemHeader{\homeworkProblemName} % Header and footer after the environment
}

\newcommand{\problemAnswer}[1]{ % Defines the problem answer command with the content as the only argument
\noindent\framebox[\columnwidth][c]{\begin{minipage}{0.98\columnwidth}#1\end{minipage}} % Makes the box around the problem answer and puts the content inside
}

\newcommand{\homeworkSectionName}{}
\newenvironment{homeworkSection}[1]{ % New environment for sections within homework problems, takes 1 argument - the name of the section
\renewcommand{\homeworkSectionName}{#1} % Assign \homeworkSectionName to the name of the section from the environment argument
\subsection{\homeworkSectionName} % Make a subsection with the custom name of the subsection
\enterProblemHeader{\homeworkProblemName\ [\homeworkSectionName]} % Header and footer within the environment
}{
\enterProblemHeader{\homeworkProblemName} % Header and footer after the environment
}

%----------------------------------------------------------------------------------------
%	NAME AND CLASS SECTION
%----------------------------------------------------------------------------------------

\newcommand{\hmwkTitle}{Regression\ Notes} % Assignment title

\newcommand{\hmwkAuthorName}{Ryan Gehring} % Your name

%----------------------------------------------------------------------------------------
%	TITLE PAGE
%----------------------------------------------------------------------------------------

\title{
\vspace{2in}
\textmd{\textbf{\hmwkTitle}}\\
\vspace{3in}
}

\author{\textbf{\hmwkAuthorName}}
\date{} % Insert date here if you want it to appear below your name

%----------------------------------------------------------------------------------------

\begin{document}

\maketitle

%----------------------------------------------------------------------------------------
%	TABLE OF CONTENTS
%----------------------------------------------------------------------------------------

%\setcounter{tocdepth}{1} % Uncomment this line if you don't want subsections listed in the ToC

\newpage
\tableofcontents
\newpage

%----------------------------------------------------------------------------------------
%	Derivation of Coefficient Estimates
%----------------------------------------------------------------------------------------

\begin{homeworkProblem}[Theory]

\subsection{Model Parametrization}

A vector of response variables $Y$ is estimated by the product of a matrix of
predictive variables $X$ and coefficient vector $\beta$ with normal errors $\epsilon$.

\begin{equation}
Y = X \beta + \epsilon
\end{equation}

\subsection{Loss Function}
Minimize the sum of squared errors.

\begin{equation}
SSE = \epsilon^T \epsilon
\end{equation}

\begin{equation*}
SSE = (Y - X\beta)^T (Y - X\beta)
\end{equation*}

\subsection{Normal Equation}

To minimize loss, differentiate with respect to the coefficients, set to zero:
\begin{equation}
0 = -2X^T(Y - X\beta)
\end{equation}

\subsection{Coefficient Estimates}

Multiply by $(X^T X)^{-1}$ (and absorb 2 into $\beta$) to get the least squares estimate $\beta$:
\begin{equation}
\beta = (X^TX)^{-1}X^TY
\end{equation}

\end{homeworkProblem}

%----------------------------------------------------------------------------------------
%	Java Implementation
%----------------------------------------------------------------------------------------

% To have just one problem per page, simply put a \clearpage after each problem

\begin{homeworkProblem}[Application]
\subsection{Java Implementation}
See below for an implementation using Apache commons math. The Github Repo contains code to run the model against an arbitrary csv data file.

\javascript{/Users/ryangehring/proj/RyanProvesStuff/regression/java/regression_tools}{Regression using commons math}

\subsection{Estimation of Bear Age from Body Measurements}
Above code was used to generate predictions of bear ages from a variety of body measurements.

Bear Data (truncated for readability):

\begin{tabular}{ l l l l l l l l  }
  AGE & SEX & HEADLEN & HEADWTH & NECK & LENGTH & CHEST & WEIGHT \\
19 & 0 & 11 & 5.5 & 16 & 53 & 26 & 80 \\
55 & 0 & 16.5 & 9 & 28 & 67.5 & 45 & 344 \\
81 & 0 & 15.5 & 8 & 31 & 72 & 54 & 416 \\
115 & 0 & 17 & 10 & 31.5 & 72 & 49 & 348 \\
104 & 1 & 15.5 & 6.5 & 22 & 62 & 35 & 166 \\
100 & 1 & 13 & 7 & 21 & 70 & 41 & 220 \\
56 & 0 & 15 & 7.5 & 26.5 & 73.5 & 41 & 262 \\
51 & 0 & 13.5 & 8 & 27 & 68.5 & 49 & 360 \\
57 & 1 & 13.5 & 7 & 20 & 64 & 38 & 204 \\
53 & 1 & 12.5 & 6 & 18 & 58 & 31 & 144 \\
68 & 0 & 16 & 9 & 29 & 73 & 44 & 332 \\
8 & 0 & 9 & 4.5 & 13 & 37 & 19 & 34 \\
44 & 1 & 12.5 & 4.5 & 10.5 & 63 & 32 & 140
\end{tabular}

$R^2$ was measured to be ~0.64.

\begin{tabular}{l l}
SEX:	& 26.148987054376104 \\
HEADLEN: & 3.0528248476353443 \\
HEADWTH: & 3.791600738790277 \\
NECK: & 1.366288821513322 \\
LENGTH: & -0.11350398628450656 \\
CHEST: & -2.9977072569525833 \\
WEIGHT: & 0.3122111457892039
\end{tabular}

\end{homeworkProblem}

%----------------------------------------------------------------------------------------

\end{document}


text:
require 'spec_helper'
require File.join(File.dirname(__FILE__), '..', 'support/lib/timing_log')

module LogfileInterval
  data_dir = File.join(File.dirname(__FILE__), '..', 'support/logfiles')

  describe Interval do
    before :each do
      @end_time = Time.new(2013, 12, 01, 16, 00, 00, '-08:00')
      @length = 300
    end

    it 'gets instantiated with empty data' do
      interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)
      interval.size.should == 0
      interval[:total_time].should == 0
      interval[:num_bytes].should == 0
      interval[:action].should == 0
      interval[:ip].should == 0
    end

    context :to_hash do
      it 'returns a hash' do
        interval = Interval.new(@end_time, @length, ParsedLine::TimingLog)
        interval.to_hash.should be_a(Hash)
      end

      it 'has a key for all columns' do
        record   = ParsedLine::TimingLog.create_record('1385942400, 192.168.0.5, posts#index, 100, 2000, 53.0')
        interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)
        interval.add_record(record)
        hinterval = interval.to_hash
        hinterval.keys.should include(:ip, :total_time, :action, :num_bytes, :rss)
      end

      it 'has start_time and end_time keys' do
        record   = ParsedLine::TimingLog.create_record('1385942400, 192.168.0.5, posts#index, 100, 2000, 53.0')
        interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)
        interval.add_record(record)
        hinterval = interval.to_hash
        hinterval.keys.should include(:start_time, :end_time)
      end

      it 'with no data, should have keys with 0 values' do
        interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)
        hinterval = interval.to_hash
        hinterval[:num_lines].should == 0
        hinterval[:ip].should == 0
        hinterval[:action].should == 0
        hinterval[:total_time].should == 0
        hinterval[:num_bytes].should == 0
        hinterval[:rss].should == 0
      end
    end

    context :add_record do
      context 'basics' do
        before :each do
          @interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)
        end

        it 'rejects record out of interval' do
          oor_record = ParsedLine::TimingLog.create_record('1385942450, 192.168.0.5, posts#index, 100, 20000, 50.0')
          lambda { @interval.add_record(oor_record) }.should raise_error(Interval::OutOfRange)
        end

        it 'rejects record at interval start_time' do
          oor_record = ParsedLine::TimingLog.create_record('1385942100, 192.168.0.5, posts#index, 100, 20000, 50.0')
          lambda { @interval.add_record(oor_record) }.should raise_error(Interval::OutOfRange)
        end

        it 'accepts record at interval end_time' do
          oor_record = ParsedLine::TimingLog.create_record('1385942400, 192.168.0.5, posts#index, 100, 20000, 50.0')
          lambda { @interval.add_record(oor_record) }.should_not raise_error
        end

        it 'adds 1 record to interval' do
          record1 = ParsedLine::TimingLog.create_record('1385942400, 192.168.0.5, posts#index, 100, 20000, 50.0')
          @interval.add_record(record1)

          @interval.size.should == 1
          @interval[:num_lines].should == 1
          @interval[:total_time].should == 100
          @interval[:num_bytes].should == 20000
          @interval[:action].should == {"posts#index"=>1}
          @interval[:ip].should == {"192.168.0.5"=>1}
        end
      end

      context 'with count and group by options' do
        it 'creates an aggregator of type Count' do
          expect(Aggregator::Count).to receive(:new).twice
          interval = Interval.new(@end_time, @length, ParsedLine::TimingLogWithGrouping.columns)
        end

        it 'add_record accepts key and subkey' do
          interval = Interval.new(@end_time, @length, ParsedLine::TimingLogWithGrouping.columns)
          record1 = ParsedLine::TimingLogWithGrouping.create_record('1385942400, 192.168.0.5, posts#index, 100, 20000, 53.0')
          interval.add_record(record1)
          interval.size.should == 1
        end
      end

      context 'with 3 records' do
        before :each do
          @interval = Interval.new(@end_time, @length, ParsedLine::TimingLog.columns)

          record1 = ParsedLine::TimingLog.create_record('1385942400, 192.168.0.5, posts#index, 100, 20000, 53.0')
          @interval.add_record(record1)
          record2 = ParsedLine::TimingLog.create_record('1385942300, 192.168.0.5, posts#show, 50, 10000, 51.0')
          @interval.add_record(record2)
          record3 = ParsedLine::TimingLog.create_record('1385942200, 10.10.10.10, posts#show, 60, 12000, 50.0')
          @interval.add_record(record3)
        end

        it 'increments size' do
          @interval.size.should == 3
        end

        it 'counts the number of lines with the num_lines aggregator' do
          @interval[:num_lines].should == 3
        end

        it 'averages columns with average aggregator' do
          @interval[:total_time].should == 70
        end

        it 'sums up columns with sum aggregator' do
          @interval[:num_bytes].should == 42000
        end

        it 'averages the delta columns with delta aggregator' do
          @interval[:rss].should == -1.5
        end

        it 'counts columns with group aggregator' do
          @interval[:ip].should ==  { '192.168.0.5' => 2, '10.10.10.10' => 1 }
          @interval[:action].should == { 'posts#index' => 1, 'posts#show' => 2}
        end
      end

      context 'with group_by key' do
        before :each do
          @interval = Interval.new(@end_time, @length, ParsedLine::TimingLogWithGrouping.columns)

          record1 = ParsedLine::TimingLogWithGrouping.create_record('1385942400, 192.168.0.5, posts#index, 100, 20000, 53.0')
          @interval.add_record(record1)
          record2 = ParsedLine::TimingLogWithGrouping.create_record('1385942300, 192.168.0.5, posts#show, 50, 10000, 51.0')
          @interval.add_record(record2)
          record3 = ParsedLine::TimingLogWithGrouping.create_record('1385942200, 192.168.0.5, posts#show, 60, 12000, 50.0')
          @interval.add_record(record3)
          record4 = ParsedLine::TimingLogWithGrouping.create_record('1385942180, 10.10.10.10, posts#index, 100, 20000, 48.0')
          @interval.add_record(record4)
        end

        it 'counts value column per group column' do
          @interval[:action].should be_a(Hash)
          @interval[:action].size.should == 2
          @interval[:action]['posts#index'].should == 2
          @interval[:action]['posts#show'].should  == 2
        end

        it 'counts value and group_by pairs' do
          @interval[:ip_by_action].should be_a(Hash)
          @interval[:ip_by_action]['192.168.0.5'].should be_a(Hash)
          @interval[:ip_by_action]['192.168.0.5']['posts#index'].should == 1
          @interval[:ip_by_action]['192.168.0.5']['posts#show'].should  == 2
          @interval[:ip_by_action]['10.10.10.10']['posts#index'].should == 1
        end

        it 'averages value column per group column' do
          @interval[:total_time].should be_a(Hash)
          @interval[:total_time].size.should == 2
          @interval[:total_time]['posts#index'].should == 100
          @interval[:total_time]['posts#show'].should  == 55
        end

        it 'sums up value column per group column' do
          @interval[:num_bytes].should be_a(Hash)
          @interval[:num_bytes].size.should == 2
          @interval[:num_bytes]['posts#index'].should == 40000
          @interval[:num_bytes]['posts#show'].should  == 22000
        end

        it 'averages deltas on value column per group column' do
          @interval[:rss].should be_a(Hash)
          @interval[:rss].size.should == 2
          @interval[:rss]['posts#index'].should == -5
          @interval[:rss]['posts#show'].should  == -1
        end
      end
    end
  end
end


text:
package org.ohmage.service;

import java.util.List;

import org.ohmage.cache.PreferenceCache;
import org.ohmage.cache.UserBin;
import org.ohmage.domain.ServerConfig;
import org.ohmage.domain.campaign.SurveyResponse;
import org.ohmage.exception.CacheMissException;
import org.ohmage.exception.DomainException;
import org.ohmage.exception.ServiceException;
import org.ohmage.jee.servlet.RequestServlet;
import org.ohmage.util.StringUtils;

/**
 * This class contains the services that pertain to the server's configuration.
 *
 * @author John Jenkins
 */
public class ConfigServices {
	/**
	 * Default constructor. Made private so that it cannot be instantiated.
	 */
	private ConfigServices() {}

	/**
	 * Creates a server configuration object to hold the server's
	 * configuration.
	 *
	 * @return A ServerConfig object representing the server's configuration.
	 *
	 * @throws ServiceException Thrown if there is an error reading from the
	 * 							cache or decoding a value from it.
	 */
	public static ServerConfig readServerConfiguration()
			throws ServiceException {

		PreferenceCache instance = PreferenceCache.instance();

		String appName;
		try {
			appName = instance.lookup(PreferenceCache.KEY_APPLICATION_NAME);
		}
		catch(CacheMissException e) {
			throw new ServiceException("The application name was unknown.", e);
		}

		String appVersion;
		try {
			appVersion = instance.lookup(PreferenceCache.KEY_APPLICATION_VERSION);
		}
		catch(CacheMissException e) {
			throw new ServiceException("The application version was unknown.", e);
		}

		String appBuild;
		try {
			appBuild = instance.lookup(PreferenceCache.KEY_APPLICATION_BUILD);
		}
		catch(CacheMissException e) {
			throw new ServiceException("The application build was unknown.", e);
		}

		SurveyResponse.PrivacyState defaultSurveyResponsePrivacyState;
		try {
			defaultSurveyResponsePrivacyState =
				SurveyResponse.PrivacyState.getValue(
						instance.lookup(PreferenceCache.KEY_DEFAULT_SURVEY_RESPONSE_SHARING_STATE)
					);
		}
		catch(CacheMissException e) {
			throw new ServiceException("The application name was unknown.", e);
		}
		catch(IllegalArgumentException e) {
			throw new ServiceException("The survey response privacy state is not a valid survey response privacy state.");
		}

		List<SurveyResponse.PrivacyState> surveyResponsePrivacyStates =
				SurveyResponseServices.instance().getSurveyResponsePrivacyStates();

		boolean defaultCampaignCreationPrivilege;
		try {
			defaultCampaignCreationPrivilege =
				Boolean.valueOf(
						instance.lookup(PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE)
					);
		}
		catch(CacheMissException e) {
			throw new ServiceException("The default campaign creation privilege was unknown.", e);
		}
		catch(IllegalArgumentException e) {
			throw new ServiceException("The default campaign creation privilege was not a valid boolean.", e);
		}

		boolean mobilityEnabled;
		try {
			mobilityEnabled =
					StringUtils.decodeBoolean(
							PreferenceCache.instance().lookup(
									PreferenceCache.KEY_MOBILITY_ENABLED));
		}
		catch(CacheMissException e) {
			throw new ServiceException("Whether or not Mobility is enabled is missing from the database.", e);
		}

		boolean selfRegistrationAllowed;
		try {
			selfRegistrationAllowed =
					StringUtils.decodeBoolean(
							PreferenceCache.instance().lookup(
									PreferenceCache.KEY_ALLOW_SELF_REGISTRATION));
		}
		catch(CacheMissException e) {
			throw new ServiceException("Whether or not self registration is allowed is missing from the database.", e);
		}

		try {
			return
				new ServerConfig(
					appName,
					appVersion,
					appBuild,
					defaultSurveyResponsePrivacyState,
					surveyResponsePrivacyStates,
					defaultCampaignCreationPrivilege,
					mobilityEnabled,
					UserBin.LIFETIME,
					RequestServlet.MAX_REQUEST_SIZE,
					RequestServlet.MAX_FILE_SIZE,
					selfRegistrationAllowed);
		}
		catch(DomainException e) {
			throw new ServiceException(e);
		}
	}
}


text:
#include "Thread.h"
#include "test_Utils.h"

#include "Cond.h"
#include "Mutex.h"
#include "Trace.h"

#include <iostream>
#include <vector>

// -----------------------------------------------------------------------------

namespace {

class TestBaseTask
        :
                public ITask
{

    int m_id;
    Mutex &m_mutex;
    int &m_instance_counter;
    int &m_execution_counter;

public:

    TestBaseTask(int id,
                 Mutex &mutex,
                 int &instance_counter,
                 int &execution_counter)
            :
            m_id(id),
            m_mutex(mutex),
            m_instance_counter(instance_counter),
            m_execution_counter(execution_counter)
    {
        trace(m_id, "created");

        Locker<Mutex> lock(m_mutex);
        ++m_instance_counter;
    }

    virtual void
    execute()
    {
        trace(m_id, "executed");

        Locker<Mutex> lock(m_mutex);
        ++m_execution_counter;
    }

    virtual
    ~TestBaseTask()
    {
        trace(m_id, "destroyed");

        Locker<Mutex> lock(m_mutex);
        --m_instance_counter;
    }

};

// -----------------------------------------------------------------------------

void
test_base()
{
    const int NUM_THREADS = 100;

    Mutex mutex;
    int instance_counter = 0;
    int execution_counter = 0;

    {
        std::vector<Thread> threads;
        threads.reserve(NUM_THREADS);
        for (int i = 0; i < NUM_THREADS; ++i)
        {
            Task new_task = std::make_shared<TestBaseTask>(
                    i + 1, mutex, instance_counter, execution_counter);
            TEST_CHECK(instance_counter >= 1);

            Thread new_thread(IThread::create(new_task));
            threads.push_back(new_thread);
        }

        for (auto &thread: threads)
        {
            thread->join();
        }

        TEST_CHECK(NUM_THREADS == execution_counter);
    }

    TEST_CHECK(0 == instance_counter);
}

// -----------------------------------------------------------------------------

class TestJoinTask
        :
                public ITask
{

    int m_id;
    Mutex &m_mutex;
    Cond &m_cond_wait;
    Cond *m_cond_signal;
    int &m_instance_counter;
    int &m_execution_counter;

public:

    TestJoinTask(int id,
                 Mutex &mutex,
                 Cond &cond_wait,
                 Cond *cond_signal,
                 int &instance_counter,
                 int &execution_counter)
            :
            m_id(id),
            m_mutex(mutex),
            m_cond_wait(cond_wait),
            m_cond_signal(cond_signal),
            m_instance_counter(instance_counter),
            m_execution_counter(execution_counter)
    {
        trace(m_id, "created");

        Locker<Mutex> lock(m_mutex);
        ++m_instance_counter;
    }

    virtual void
    execute()
    {
        trace(m_id, "executing");

        Thread self = IThread::self();

        if (m_cond_signal)
        {
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            self->yield();
            m_cond_signal->signal();
        }

        {
            Locker<Mutex> lock(m_mutex);
            m_cond_wait.wait(m_mutex);

            ++m_execution_counter;
        }

        self->yield();

        trace(m_id, "executing");
    }

    virtual
    ~TestJoinTask()
    {
        trace(m_id, "destroyed");

        Locker<Mutex> lock(m_mutex);
        --m_instance_counter;
    }

};

// -----------------------------------------------------------------------------

void
test_join()
{
    const int NUM_THREADS = 100;

    Mutex mutex;
    Cond cond_task, cond_init;
    int instance_counter = 0;
    int execution_counter = 0;

    {
        std::vector<Thread> threads;
        threads.reserve(NUM_THREADS);
        for (int i = 0; i < NUM_THREADS; ++i)
        {
            Cond *cond_signal = 0;
            if (i + 1 == NUM_THREADS)
            {
                cond_signal = &cond_init;
            }

            Task new_task = std::make_shared<TestJoinTask>(
                    i + 1,
                    mutex,
                    cond_task,
                    cond_signal,
                    instance_counter,
                    execution_counter);
            TEST_CHECK(instance_counter >= 1);

            Thread new_thread(IThread::create(new_task));
            threads.push_back(new_thread);
        }
        TEST_CHECK(0 == execution_counter);
        TEST_CHECK(NUM_THREADS == instance_counter);

        {
            Locker<Mutex> locker(mutex);
            cond_init.wait(mutex);
            cond_task.broadcast();
        }

        for (int i = 0; i < NUM_THREADS; ++i)
        {
            trace(i + 1, "joining it");
            threads[i]->join();
            trace(i + 1, "joined");
        }
        trace("Done.");
        TEST_CHECK(NUM_THREADS == execution_counter);
    }

    TEST_CHECK(0 == instance_counter);
}

} // anonymous namespace

// -----------------------------------------------------------------------------

void
test_Thread()
{
    test_base();
    test_join();
}

// -----------------------------------------------------------------------------


text: export const isProduction = process.env.NODE_ENV === 'production';


text:
<web-fragment>
	<servlet>
		<display-name>SerialRestServlet</display-name>
		<servlet-name>SerialRestServlet</servlet-name>
		<servlet-class>org.eclipse.jetty.example.asyncrest.SerialRestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SerialRestServlet</servlet-name>
		<url-pattern>/testSerial</url-pattern>
	</servlet-mapping>

	<servlet>
		<display-name>AsyncRestServlet</display-name>
		<servlet-name>AsyncRestServlet</servlet-name>
		<servlet-class>org.eclipse.jetty.example.asyncrest.AsyncRestServlet</servlet-class>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>AsyncRestServlet</servlet-name>
		<url-pattern>/testAsync</url-pattern>
	</servlet-mapping>
</web-fragment>


text:
package org.sfx.catholicjourney.core.utils;

/**
 * Created by simonadmin on 2015-03-18.
 */
public interface ImageUrlBuilder {

	enum ImageCropMode {
		fit,
		fill,
		limit
	}

	ImageUrlBuilder withImagePath(String imagePath);

	ImageUrlBuilder withWidth(int width);

	ImageUrlBuilder withHeight(int height);

	ImageUrlBuilder withCrop(ImageCropMode cropMode);

	String build();
}


text:
Table API - the CDUD
====================
``` JSON
	{
		"Section": "TabServer"
	,	"SubSection": "API"
	,	"SubSectionGroup": "Config"
	,	"SubSectionTitle": "API"
	,	"SubSectionTooltip": "Details on the API suported in TabServer2"
	, 	"MultiSection":2
	}
```

These interfaces are created in crud.go, lines 68 to 82.

## Insert

HTTP, method POST

``` green-bar
	/api/table/NAME?col=Value&col2=value...
```

If you supply the ID as Primary key it will be used.
The ID/PK is specified in the `sql-cfg.json` file.

## Insert - with ID

HTTP, method POST

``` green-bar
	/api/table/NAME/ID?col=Value&col2=value...
```

If you supply the ID as Primary key it will be used.
The ID/PK is specified in the `sql-cfg.json` file.

## Update

HTTP, method PUT

``` green-bar
	/api/table/NAME?col=Value&col2=value...
```

The primary key can be a multi-part PK and must be supplied
in the parameters.   It is possible to do non-PK updates with
this.  There is a flag in `sql-cfg.json` for this.
The ID/PK is specified in the `sql-cfg.json` file.

## Update - with ID

HTTP, method PUT

``` green-bar
	/api/table/NAME/ID?col=Value&col2=value...
```

If you supply the ID as Primary key it will be used.
The ID/PK is specified in the `sql-cfg.json` file.

## Delete

HTTP, method DELETE

``` green-bar
	/api/table/NAME?col=Value&col2=value...
```

The primary key can be a multi-part PK and must be supplied
in the parameters.   It is possible to do non-PK updates with
this.  There is a flag in `sql-cfg.json` for this.
The ID/PK is specified in the `sql-cfg.json` file.

## Delete - with ID

HTTP, method DELETE

``` green-bar
	/api/table/NAME/ID?col=Value&col2=value...
```

If you supply the ID as Primary key it will be used.
The ID/PK is specified in the `sql-cfg.json` file.

## Select

Select can be performed in both

``` green-bar
	/api/table/NAME/ID
```

and

``` green-bar
	/api/table/NAME?col=Val1&col2=val2
```

format.   It is assumed that this is for a single row - primary or
unique key select.

Select provides a set of other options.  You can not name columns
with these options and use them in the `?col=val1` format.

``` green-bar
	?orderBy=[{"ColName":"abc","Dir":"asc"}]
```

is a JSON encoded array of columns with "asc" and "desc".
Note lower case on asc/desc.  Also the "Dir" is optional
and assumed to be "asc" if not specified.

``` green-bar
	?where={...}
```

a where clause - as a parse tree subset of a SELECT were
clause.  More on this later.

``` green-bar
	?limit=
	?offset=
```

Are integer values that will subset the query to the
specified range.  These are optional.


text:
package ddevapp_test

import (
	"github.com/drud/ddev/pkg/ddevapp"
	"github.com/drud/ddev/pkg/globalconfig"
	"github.com/drud/ddev/pkg/testcommon"
	asrt "github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"os"
	"strings"
	"testing"
)

// TestTraefikSimple tests basic traefik router usage
func TestTraefikSimple(t *testing.T) {
	assert := asrt.New(t)

	// Make sure this leaves us in the original test directory
	origDir, _ := os.Getwd()

	site := TestSites[0] // 0 == wordpress
	app, err := ddevapp.NewApp(site.Dir, true)
	assert.NoError(err)

	ddevapp.PowerOff()
	origTraefik := globalconfig.DdevGlobalConfig.UseTraefik
	globalconfig.DdevGlobalConfig.UseTraefik = true
	err = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)
	require.NoError(t, err)
	origConfig := *app

	t.Cleanup(func() {
		err = os.Chdir(origDir)
		assert.NoError(err)
		err = app.Stop(true, false)
		assert.NoError(err)
		ddevapp.PowerOff()
		err = origConfig.WriteConfig()
		assert.NoError(err)
		globalconfig.DdevGlobalConfig.UseTraefik = origTraefik
		err = globalconfig.WriteGlobalConfig(globalconfig.DdevGlobalConfig)
		assert.NoError(err)
	})

	app.AdditionalHostnames = []string{"one", "two", "*.wild"}
	app.AdditionalFQDNs = []string{"onefullurl.ddev.site", "twofullurl.ddev.site", "*.wild.fqdn"}
	err = app.WriteConfig()
	require.NoError(t, err)
	err = app.StartAndWait(5)
	require.NoError(t, err)

	desc, err := app.Describe(false)
	assert.True(desc["use_traefik"].(bool))

	// Test reachabiliity in each of the hostnames
	httpURLs, httpsURLs, allURLs := app.GetAllURLs()

	// If no mkcert trusted https, use only the httpURLs
	// This is especially the case for colima
	t.Logf("CAROOT='%s'", globalconfig.GetCAROOT())
	if globalconfig.GetCAROOT() == "" {
		allURLs = httpURLs
	}

	for _, u := range allURLs {
		// Use something here for wildcard
		u = strings.Replace(u, `*`, `somewildcard`, 1)
		_, err = testcommon.EnsureLocalHTTPContent(t, u+site.Safe200URIWithExpectation.URI, site.Safe200URIWithExpectation.Expect)
		assert.NoError(err, "failed EnsureLocalHTTPContent() %s: %v", u+site.Safe200URIWithExpectation.URI, err)
	}

	// Test Reachability to PhpMyAdmin, which uses different technique
	_, _ = testcommon.EnsureLocalHTTPContent(t, httpURLs[0]+":8036", "phpMyAdmin")
	if globalconfig.DdevGlobalConfig.MkcertCARoot != "" {
		_, _ = testcommon.EnsureLocalHTTPContent(t, httpsURLs[0]+":8037", "phpMyAdmin")
	}
}


text:
#ifndef itkRenyiEntropyThresholdCalculator_h
#define itkRenyiEntropyThresholdCalculator_h

#include "itkHistogramThresholdCalculator.h"

namespace itk
{

/** \class RenyiEntropyThresholdCalculator
 * \brief Computes the RenyiEntropy's threshold for an image.
 *
 * Kapur J.N., Sahoo P.K., and Wong A.K.C. (1985) "A New Method for
 * Gray-Level Picture Thresholding Using the Entropy of the Histogram"
 * Graphical Models and Image Processing, 29(3): 273-285
 * M. Emre Celebi
 * 06.15.2007
 *
 * This class is templated over the input histogram type.
 * \warning This calculator assumes that the input histogram has only one dimension.
 *
 * \author Richard Beare. Department of Medicine, Monash University,
 * Melbourne, Australia.
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction, INRA de Jouy-en-Josas, France.
 *
 * This implementation was taken from the Insight Journal paper:
 * https://hdl.handle.net/10380/3279  or
 * http://www.insight-journal.org/browse/publication/811
 *
 * \ingroup Operators
 * \ingroup ITKThresholding
 */
template <typename THistogram, typename TOutput=double>
class RenyiEntropyThresholdCalculator : public HistogramThresholdCalculator<THistogram, TOutput>
{
public:
  /** Standard class typedefs. */
  typedef RenyiEntropyThresholdCalculator Self;
  typedef Object                          Superclass;
  typedef SmartPointer<Self>              Pointer;
  typedef SmartPointer<const Self>        ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(RenyiEntropyThresholdCalculator, Object);

  /** Type definition for the input image. */
  typedef THistogram  HistogramType;
  typedef TOutput     OutputType;

protected:
  RenyiEntropyThresholdCalculator() { m_FirstBin = 0; m_LastBin = 0; m_Size = 0; }
  virtual ~RenyiEntropyThresholdCalculator() {}

  void GenerateData(void) ITK_OVERRIDE;

  typedef typename HistogramType::TotalAbsoluteFrequencyType  TotalAbsoluteFrequencyType;
  typedef typename HistogramType::AbsoluteFrequencyType       AbsoluteFrequencyType;
  typedef typename HistogramType::InstanceIdentifier          InstanceIdentifier;
  typedef typename HistogramType::SizeValueType               SizeValueType;

  InstanceIdentifier MaxEntropyThresholding( const HistogramType* histogram,
                                             const std::vector< double >& normHisto,
                                             const std::vector< double >& P1,
                                             const std::vector< double >& P2 );

  InstanceIdentifier MaxEntropyThresholding2( const HistogramType* histogram,
                                              const std::vector< double >& normHisto,
                                              const std::vector< double >& P1,
                                              const std::vector< double >& P2 );

  InstanceIdentifier MaxEntropyThresholding3( const HistogramType* histogram,
                                              const std::vector< double >& normHisto,
                                              const std::vector< double >& P1,
                                              const std::vector< double >& P2 );

private:
  RenyiEntropyThresholdCalculator(const Self&) ITK_DELETE_FUNCTION;
  void operator=(const Self&) ITK_DELETE_FUNCTION;

  InstanceIdentifier  m_FirstBin;
  InstanceIdentifier  m_LastBin;
  SizeValueType       m_Size;
};

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkRenyiEntropyThresholdCalculator.hxx"
#endif

#endif


text:
namespace UnitTests
{
    TEST_CLASS(ShaderParser)
	{
	public:
		TEST_METHOD(ParserAllShaderSources)
		{
            UnitTest_SetWorkingDirectory();
            ConsoleRig::GlobalServices services(GetStartupConfig());

                // Search for all of the shader sources in the xleres directory
            auto inputFiles = FindFilesHierarchical("game/xleres", "*.h", FindFilesFilter::File);
            auto inputFiles1 = FindFilesHierarchical("game/xleres", "*.sh", FindFilesFilter::File);
            auto inputFiles2 = FindFilesHierarchical("game/xleres", "*.?sh", FindFilesFilter::File);

            inputFiles.insert(inputFiles.end(), inputFiles1.begin(), inputFiles1.end());
            inputFiles.insert(inputFiles.end(), inputFiles2.begin(), inputFiles2.end());

                // Now try to parse each one using the shader parser...
                // Look for parsing errors and unsupported syntax

            for (auto& i:inputFiles) {
                size_t blockSize = 0;
                auto memBlock = LoadFileAsMemoryBlock(i.c_str(), &blockSize);

                const char* flgId = "FunctionLinkingGraph";
                if (blockSize > XlStringLen(flgId) &&
                    XlEqString(MakeStringSection((const char*)memBlock.get(), (const char*)&memBlock[XlStringLen(flgId)]), flgId))
                    continue;

                auto signature = ShaderSourceParser::BuildShaderFragmentSignature(
                    (const char*)memBlock.get(), blockSize);

                (void)signature;
            }
        }
    };
}


text:
class AddAutosaveTokenColumnsToAssessorsAndAdmins < ActiveRecord::Migration[4.2]
  def change
    add_column :assessors, :autosave_token, :string, unique: true
    add_column :admins, :autosave_token, :string, unique: true
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
    	<groupId>org.teatrove</groupId>
        <artifactId>teatrove</artifactId>
        <version>4.2.0-SNAPSHOT</version>
    </parent>

    <groupId>org.teatrove</groupId>
    <artifactId>build-tools</artifactId>

    <packaging>pom</packaging>

    <name>Build Tools</name>

    <modules>
        <module>package-info-maven-plugin</module>
        <module>teatools</module>
        <module>toolbox</module>
        <module>teacompiler</module>
    </modules>
</project>


text:
from django.contrib.auth import views as auth_views
from django.urls import path

from mezzanine.conf import settings
from mezzanine.core import views as core_views

urlpatterns = []

if "django.contrib.admin" in settings.INSTALLED_APPS:
    urlpatterns += [
        path(
            "password_reset/",
            auth_views.PasswordResetView.as_view(),
            name="password_reset",
        ),
        path(
            "password_reset/done/",
            auth_views.PasswordResetDoneView.as_view(),
            name="password_reset_done",
        ),
        path(
            "reset/done/",
            auth_views.PasswordResetCompleteView.as_view(),
            name="password_reset_complete",
        ),
        path(
            "reset/<uidb64>/<token>/",
            auth_views.PasswordResetConfirmView.as_view(),
            name="password_reset_confirm",
        ),
    ]

urlpatterns += [
    path("edit/", core_views.edit, name="edit"),
    path("search/", core_views.search, name="search"),
    path("set_site/", core_views.set_site, name="set_site"),
]