text:
"""Generic object editor view that uses REST services."""

__author__ = 'Pavel Simakov (psimakov@google.com)'

import os
import urllib

import jinja2
import webapp2

import appengine_config
from common import jinja_utils
from common import schema_fields
from common import tags
from controllers import utils
from models import custom_modules
from models import transforms
from models.config import ConfigProperty

# a set of YUI and inputex modules required by the editor
COMMON_REQUIRED_MODULES = [
    'inputex-group', 'inputex-form', 'inputex-jsonschema']

ALL_MODULES = [
    'querystring-stringify-simple', 'inputex-select', 'inputex-string',
    'inputex-radio', 'inputex-date', 'inputex-datepicker', 'inputex-checkbox',
    'inputex-list', 'inputex-color', 'gcb-rte', 'inputex-textarea',
    'inputex-url', 'inputex-uneditable', 'inputex-integer', 'inputex-hidden',
    'inputex-file', 'io-upload-iframe']

RESOURCES_PATH = '/modules/oeditor/resources'

# Global code syntax highlighter controls.
CAN_HIGHLIGHT_CODE = ConfigProperty(
    'gcb_can_highlight_code', bool, (
        'Whether or not to highlight code syntax '
        'in Dashboard editors and displays.'),
    True)

class ObjectEditor(object):
    """Generic object editor powered by jsonschema."""

    # Modules can add extra script tags to the oeditor page by registering a
    # callback function here. The callback function will receive the app_context
    # as an argument, and should return an iterable of strings, each of which is
    # the URL of a script library.
    EXTRA_SCRIPT_TAG_URLS = []

    @classmethod
    def get_html_for(
        cls, handler, schema_json, annotations, object_key,
        rest_url, exit_url,
        extra_args=None,
        save_method='put',
        delete_url=None, delete_message=None, delete_method='post',
        auto_return=False, read_only=False,
        required_modules=None,
        extra_css_files=None,
        extra_js_files=None,
        additional_dirs=None,
        delete_button_caption='Delete',
        save_button_caption='Save',
        exit_button_caption='Close'):
        """Creates an HTML code needed to embed and operate this form.

        This method creates an HTML, JS and CSS  required to embed JSON
        schema-based object editor into a view.

        Args:
            handler: a BaseHandler class, which will host this HTML, JS and CSS
            schema_json: a text of JSON schema for the object being edited
            annotations: schema annotations dictionary
            object_key: a key of an object being edited
            rest_url: a REST endpoint for object GET/PUT operation
            exit_url: a URL to go to after the editor form is dismissed
            extra_args: extra request params passed back in GET and POST
            save_method: how the data should be saved to the server (put|upload)
            delete_url: optional URL for delete operation
            delete_message: string. Optional custom delete confirmation message
            delete_method: optional HTTP method for delete operation
            auto_return: whether to return to the exit_url on successful save
            read_only: optional flag; if set, removes Save and Delete operations
            required_modules: list of inputex modules required for this editor
            extra_css_files: list of extra CSS files to be included
            extra_js_files: list of extra JS files to be included
            additional_dirs: list of extra directories to look for
                Jinja template files, e.g., JS or CSS files included by modules.
            delete_button_caption: string. A caption for the 'Delete' button
            save_button_caption: a caption for the 'Save' button
            exit_button_caption: a caption for the 'Close' button

        Returns:
            The HTML, JS and CSS text that will instantiate an object editor.
        """
        required_modules = required_modules or ALL_MODULES

        if not delete_message:
            kind = transforms.loads(schema_json).get('description')
            if not kind:
                kind = 'Generic Object'
            delete_message = 'Are you sure you want to delete this %s?' % kind

        # construct parameters
        get_url = rest_url
        get_args = {'key': object_key}
        post_url = rest_url
        post_args = {'key': object_key}

        if extra_args:
            get_args.update(extra_args)
            post_args.update(extra_args)

        if read_only:
            post_url = ''
            post_args = ''

        custom_rte_tag_icons = []
        for tag, tag_class in tags.get_tag_bindings().items():
            custom_rte_tag_icons.append({
                'name': tag,
                'iconUrl': tag_class().get_icon_url()})

        extra_script_tag_urls = []
        for callback in cls.EXTRA_SCRIPT_TAG_URLS:
            for url in callback():
                extra_script_tag_urls.append(url)

        template_values = {
            'enabled': custom_module.enabled,
            'schema': schema_json,
            'get_url': '%s?%s' % (get_url, urllib.urlencode(get_args, True)),
            'save_url': post_url,
            'save_args': transforms.dumps(post_args),
            'exit_button_caption': exit_button_caption,
            'exit_url': exit_url,
            'required_modules': COMMON_REQUIRED_MODULES + required_modules,
            'extra_css_files': extra_css_files or [],
            'extra_js_files': extra_js_files or [],
            'schema_annotations': [
                (item[0], transforms.dumps(item[1])) for item in annotations],
            'save_method': save_method,
            'auto_return': auto_return,
            'delete_button_caption': delete_button_caption,
            'save_button_caption': save_button_caption,
            'custom_rte_tag_icons': transforms.dumps(custom_rte_tag_icons),
            'delete_message': delete_message,
            'can_highlight_code': CAN_HIGHLIGHT_CODE.value,
            'extra_script_tag_urls': extra_script_tag_urls,
        }

        if delete_url and not read_only:
            template_values['delete_url'] = delete_url
        if delete_method:
            template_values['delete_method'] = delete_method
        if appengine_config.BUNDLE_LIB_FILES:
            template_values['bundle_lib_files'] = True

        return jinja2.utils.Markup(handler.get_template('oeditor.html', (
            [os.path.dirname(__file__)] + (additional_dirs or [])
        )).render(template_values))

class PopupHandler(webapp2.RequestHandler, utils.ReflectiveRequestHandler):
    """A handler to serve the content of the popup subeditor."""

    default_action = 'custom_tag'
    get_actions = ['edit_custom_tag', 'add_custom_tag']
    post_actions = []

    def get_template(self, template_name, dirs):
        """Sets up an environment and Gets jinja template."""
        return jinja_utils.get_template(
            template_name, dirs + [os.path.dirname(__file__)])

    def _validate_schema(self, tag, schema):
        if schema.has_subregistries():
            return tag.unavailable_schema(
                'This tag has an invalid schema and cannot be edited. '
                'Only simple field types are allowed.')

        text_field_count = 0
        index = schema_fields.FieldRegistryIndex(schema)
        index.rebuild()
        for name in index.names_in_order:
            if index.find(name).type == 'text':
                text_field_count += 1
        if text_field_count > 1:
            return tag.unavailable_schema(
                'This tag has an invalid schema and cannot be edited. '
                'Only one field of type "text" is allowed.')

        return schema

    def get_edit_custom_tag(self):
        """Return the the page used to edit a custom HTML tag in a popup."""
        tag_name = self.request.get('tag_name')
        tag_bindings = tags.get_tag_bindings()
        tag_class = tag_bindings[tag_name]
        tag = tag_class()
        schema = tag.get_schema(self)
        schema = self._validate_schema(tag, schema)

        template_values = {}
        template_values['form_html'] = ObjectEditor.get_html_for(
            self, schema.get_json_schema(), schema.get_schema_dict(), None,
            None, None,
            required_modules=tag_class.required_modules(),
            extra_js_files=tag_class.extra_js_files(),
            extra_css_files=tag_class.extra_css_files(),
            additional_dirs=tag_class.additional_dirs())
        self.response.out.write(
            self.get_template('popup.html', []).render(template_values))

    def get_add_custom_tag(self):
        """Return the page for the popup used to add a custom HTML tag."""
        tag_name = self.request.get('tag_name')
        excluded_tags = self.request.get_all('excluded_tags')

        tag_bindings = tags.get_tag_bindings()

        select_data = []
        for name in tag_bindings.keys():
            if name not in excluded_tags:
                clazz = tag_bindings[name]
                select_data.append((name, '%s: %s' % (
                    clazz.vendor(), clazz.name())))
        select_data = sorted(select_data, key=lambda pair: pair[1])

        if tag_name:
            tag_class = tag_bindings[tag_name]
        else:
            tag_class = tag_bindings[select_data[0][0]]
        tag = tag_class()
        tag_schema = tag.get_schema(self)
        tag_schema = self._validate_schema(tag, tag_schema)

        schema = schema_fields.FieldRegistry('Add a Component')
        type_select = schema.add_sub_registry('type', 'Component Type')
        type_select.add_property(schema_fields.SchemaField(
            'tag', 'Name', 'string', select_data=select_data))
        schema.add_sub_registry('attributes', registry=tag_schema)

        template_values = {}
        template_values['form_html'] = ObjectEditor.get_html_for(
            self, schema.get_json_schema(), schema.get_schema_dict(), None,
            None, None,
            required_modules=tag_class.required_modules(),
            extra_js_files=['add_custom_tag.js'] + tag_class.extra_js_files(),
            extra_css_files=tag_class.extra_css_files(),
            additional_dirs=tag_class.additional_dirs())
        self.response.out.write(
            self.get_template('popup.html', []).render(template_values))

def create_bool_select_annotation(
    keys_list, label, true_label, false_label, class_name=None,
    description=None):
    """Creates inputex annotation to display bool type as a select."""
    properties = {
        'label': label, 'choices': [
            {'value': True, 'label': true_label},
            {'value': False, 'label': false_label}]}
    if class_name:
        properties['className'] = class_name
    if description:
        properties['description'] = description
    return (keys_list, {'type': 'select', '_inputex': properties})

custom_module = None

def register_module():
    """Registers this module in the registry."""

    from controllers import sites

    yui_handlers = [
        ('/static/inputex-3.1.0/(.*)', sites.make_zip_handler(
            os.path.join(
                appengine_config.BUNDLE_ROOT, 'lib/inputex-3.1.0.zip'))),
        ('/static/yui_3.6.0/(.*)', sites.make_zip_handler(
            os.path.join(
                appengine_config.BUNDLE_ROOT, 'lib/yui_3.6.0.zip'))),
        ('/static/2in3/(.*)', sites.make_zip_handler(
            os.path.join(
                appengine_config.BUNDLE_ROOT, 'lib/yui_2in3-2.9.0.zip')))]

    codemirror_handler = [
        ('/static/codemirror/(.*)', sites.make_zip_handler(
            os.path.join(
                appengine_config.BUNDLE_ROOT, 'lib/codemirror-4.5.0.zip')))]

    if appengine_config.BUNDLE_LIB_FILES:
        yui_handlers += [
            ('/static/combo/inputex', sites.make_css_combo_zip_handler(
                os.path.join(
                    appengine_config.BUNDLE_ROOT, 'lib/inputex-3.1.0.zip'),
                '/static/inputex-3.1.0/')),
            ('/static/combo/yui', sites.make_css_combo_zip_handler(
                os.path.join(appengine_config.BUNDLE_ROOT, 'lib/yui_3.6.0.zip'),
                '/yui/')),
            ('/static/combo/2in3', sites.make_css_combo_zip_handler(
                os.path.join(
                    appengine_config.BUNDLE_ROOT, 'lib/yui_2in3-2.9.0.zip'),
                '/static/2in3/'))]

    oeditor_handlers = [('/oeditorpopup', PopupHandler)]
    global_routes = yui_handlers + codemirror_handler + [
        (os.path.join(RESOURCES_PATH, '.*'), tags.ResourcesHandler)]

    global custom_module  # pylint: disable=global-statement
    custom_module = custom_modules.Module(
        'Object Editor',
        'A visual editor for editing various types of objects.',
        global_routes, oeditor_handlers)
    return custom_module


text:
package nom.bdezonia.zorbage.algorithm;

import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.Roots;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class BasicStats {

	// do not instantiate

	private BasicStats() { }

	/**
	 * Calculate some basic data measures using naive algorithms. Passing a high precision backed
	 * data source will result in perfectly accurate results.
	 *
	 * @param alg
	 * @param data
	 * @param mean
	 * @param stdErrMean
	 * @param stddev
	 * @param sampleVariance
	 * @param sampleSkew
	 * @param excessKurtosis
	 */
	public static <T extends Algebra<T,U> & Unity<U> & Addition<U> & Multiplication<U> & Invertible<U> & Roots<U>,
					U>
		void compute(T alg, IndexedDataSource<U> data, U mean, U stdErrMean, U stddev, U sampleVariance, U sampleSkew, U excessKurtosis)
	{
		if (data.size() < 2)
			throw new IllegalArgumentException("Basic statistics cannot be calculated from a data set with less than two elements");

		U value = alg.construct();
		U tmp = alg.construct();
		U sum = alg.construct();
		U n = alg.construct();
		U n_minus_one = alg.construct();
		U one = alg.construct();
		alg.unity().call(one);

		// calc n etc.
		//   there is probably a simpler and faster way to do this. if not I should make one.
		alg.zero().call(sum);
		for (long i = 0; i < data.size(); i++) {
			alg.add().call(sum, one, sum);
		}
		alg.assign().call(sum, n);
		alg.subtract().call(sum, one, n_minus_one);

		// calc mean
		//   mean = sum (xi / n)
		alg.zero().call(sum);
		for (long i = 0; i < data.size(); i++) {
			data.get(i, tmp);
			alg.divide().call(tmp, n, value);
			alg.add().call(sum, value, sum);
		}
		alg.assign().call(sum, mean);

		// calc sample variance
		//   sample variance s^2 = sum ((xi - xbar)^2 / n-1)
		alg.zero().call(sum);
		for (long i = 0; i < data.size(); i++) {
			data.get(i, tmp);
			alg.subtract().call(tmp, mean, tmp);
			alg.multiply().call(tmp, tmp, value);
			alg.divide().call(value, n_minus_one, value);
			alg.add().call(sum, value, sum);
		}
		alg.assign().call(sum, sampleVariance);
		alg.sqrt().call(sampleVariance, stddev);
		alg.sqrt().call(n, tmp);
		alg.divide().call(stddev, tmp, stdErrMean);

		// calc sample skew
		//   sample skew = sum ((xi - xbar)^3 / n * s^3)
		alg.zero().call(sum);
		for (long i = 0; i < data.size(); i++) {
			data.get(i, tmp);
			alg.subtract().call(tmp, mean, tmp);
			alg.divide().call(tmp, stddev, tmp);
			alg.multiply().call(tmp, tmp, value);
			alg.multiply().call(value, tmp, value);
			alg.divide().call(value, n, value);
			alg.add().call(sum, value, sum);
		}
		alg.assign().call(sum, sampleSkew);

		// calc excess kurtosis
		//   excess kurtosis = sum ((xi - xbar)^4 / n * s^4) - 3
		alg.zero().call(sum);
		for (long i = 0; i < data.size(); i++) {
			data.get(i, tmp);
			alg.subtract().call(tmp, mean, tmp);
			alg.divide().call(tmp, stddev, tmp);
			alg.multiply().call(tmp, tmp, tmp);
			alg.multiply().call(tmp, tmp, value);
			alg.divide().call(value, n, value);
			alg.add().call(sum, value, sum);
		}
		alg.subtract().call(sum, one, sum);
		alg.subtract().call(sum, one, sum);
		alg.subtract().call(sum, one, sum);
		alg.assign().call(sum, excessKurtosis);
	}
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef GCC_TARGHOOKS_H
#define GCC_TARGHOOKS_H

extern bool default_legitimate_address_p (machine_mode, rtx, bool);

extern void default_external_libcall (rtx);
extern rtx default_legitimize_address (rtx, rtx, machine_mode);
extern bool default_legitimize_address_displacement (rtx *, rtx *,
						     machine_mode);

extern int default_unspec_may_trap_p (const_rtx, unsigned);
extern machine_mode default_promote_function_mode (const_tree, machine_mode,
							int *, const_tree, int);
extern machine_mode default_promote_function_mode_always_promote
			(const_tree, machine_mode, int *, const_tree, int);

extern machine_mode default_cc_modes_compatible (machine_mode,
						      machine_mode);

extern bool default_return_in_memory (const_tree, const_tree);

extern rtx default_expand_builtin_saveregs (void);
extern void default_setup_incoming_varargs (cumulative_args_t, machine_mode, tree, int *, int);
extern rtx default_builtin_setjmp_frame_value (void);
extern bool default_pretend_outgoing_varargs_named (cumulative_args_t);

extern machine_mode default_eh_return_filter_mode (void);
extern machine_mode default_libgcc_cmp_return_mode (void);
extern machine_mode default_libgcc_shift_count_mode (void);
extern machine_mode default_unwind_word_mode (void);
extern unsigned HOST_WIDE_INT default_shift_truncation_mask
  (machine_mode);
extern unsigned int default_min_divisions_for_recip_mul (machine_mode);
extern int default_mode_rep_extended (machine_mode, machine_mode);

extern tree default_stack_protect_guard (void);
extern tree default_external_stack_protect_fail (void);
extern tree default_hidden_stack_protect_fail (void);

extern machine_mode default_mode_for_suffix (char);

extern tree default_cxx_guard_type (void);
extern tree default_cxx_get_cookie_size (tree);

extern bool hook_pass_by_reference_must_pass_in_stack
  (cumulative_args_t, machine_mode mode, const_tree, bool);
extern bool hook_callee_copies_named
  (cumulative_args_t ca, machine_mode, const_tree, bool);

extern void default_print_operand (FILE *, rtx, int);
extern void default_print_operand_address (FILE *, machine_mode, rtx);
extern bool default_print_operand_punct_valid_p (unsigned char);
extern tree default_mangle_assembler_name (const char *);

extern bool default_scalar_mode_supported_p (machine_mode);
extern bool default_libgcc_floating_mode_supported_p (machine_mode);
extern bool targhook_words_big_endian (void);
extern bool targhook_float_words_big_endian (void);
extern bool default_float_exceptions_rounding_supported_p (void);
extern bool default_decimal_float_supported_p (void);
extern bool default_fixed_point_supported_p (void);

extern bool default_has_ifunc_p (void);

extern const char * default_invalid_within_doloop (const rtx_insn *);

extern tree default_builtin_vectorized_function (unsigned int, tree, tree);
extern tree default_builtin_md_vectorized_function (tree, tree, tree);

extern tree default_builtin_vectorized_conversion (unsigned int, tree, tree);

extern int default_builtin_vectorization_cost (enum vect_cost_for_stmt, tree, int);

extern tree default_builtin_reciprocal (tree);

extern HOST_WIDE_INT default_vector_alignment (const_tree);

extern bool default_builtin_vector_alignment_reachable (const_tree, bool);
extern bool
default_builtin_support_vector_misalignment (machine_mode mode,
					     const_tree,
					     int, bool);
extern machine_mode default_preferred_simd_mode (machine_mode mode);
extern unsigned int default_autovectorize_vector_sizes (void);
extern machine_mode default_get_mask_mode (unsigned, unsigned);
extern void *default_init_cost (struct loop *);
extern unsigned default_add_stmt_cost (void *, int, enum vect_cost_for_stmt,
				       struct _stmt_vec_info *, int,
				       enum vect_cost_model_location);
extern void default_finish_cost (void *, unsigned *, unsigned *, unsigned *);
extern void default_destroy_cost_data (void *);

/* OpenACC hooks.  */
extern bool default_goacc_validate_dims (tree, int [], int);
extern int default_goacc_dim_limit (int);
extern bool default_goacc_fork_join (gcall *, const int [], bool);
extern void default_goacc_reduction (gcall *);

/* These are here, and not in hooks.[ch], because not all users of
   hooks.h include tm.h, and thus we don't have CUMULATIVE_ARGS.  */

extern bool hook_bool_CUMULATIVE_ARGS_false (cumulative_args_t);
extern bool hook_bool_CUMULATIVE_ARGS_true (cumulative_args_t);

extern bool hook_bool_CUMULATIVE_ARGS_mode_tree_bool_false
  (cumulative_args_t, machine_mode, const_tree, bool);
extern bool hook_bool_CUMULATIVE_ARGS_mode_tree_bool_true
  (cumulative_args_t, machine_mode, const_tree, bool);
extern int hook_int_CUMULATIVE_ARGS_mode_tree_bool_0
  (cumulative_args_t, machine_mode, tree, bool);
extern const char *hook_invalid_arg_for_unprototyped_fn
  (const_tree, const_tree, const_tree);
extern void default_function_arg_advance
  (cumulative_args_t, machine_mode, const_tree, bool);
extern rtx default_function_arg
  (cumulative_args_t, machine_mode, const_tree, bool);
extern rtx default_function_incoming_arg
  (cumulative_args_t, machine_mode, const_tree, bool);
extern unsigned int default_function_arg_boundary (machine_mode,
						   const_tree);
extern unsigned int default_function_arg_round_boundary (machine_mode,
							 const_tree);
extern bool hook_bool_const_rtx_commutative_p (const_rtx, int);
extern rtx default_function_value (const_tree, const_tree, bool);
extern rtx default_libcall_value (machine_mode, const_rtx);
extern bool default_function_value_regno_p (const unsigned int);
extern rtx default_internal_arg_pointer (void);
extern rtx default_static_chain (const_tree, bool);
extern void default_trampoline_init (rtx, tree, rtx);
extern int default_return_pops_args (tree, tree, int);
extern reg_class_t default_branch_target_register_class (void);
extern reg_class_t default_ira_change_pseudo_allocno_class (int, reg_class_t,
							    reg_class_t);
extern bool default_lra_p (void);
extern int default_register_priority (int);
extern bool default_register_usage_leveling_p (void);
extern bool default_different_addr_displacement_p (void);
extern reg_class_t default_secondary_reload (bool, rtx, reg_class_t,
					     machine_mode,
					     secondary_reload_info *);
extern void default_target_option_override (void);
extern void hook_void_bitmap (bitmap);
extern int default_reloc_rw_mask (void);
extern tree default_mangle_decl_assembler_name (tree, tree);
extern tree default_emutls_var_fields (tree, tree *);
extern tree default_emutls_var_init (tree, tree, tree);
extern bool default_hard_regno_scratch_ok (unsigned int);
extern bool default_mode_dependent_address_p (const_rtx, addr_space_t);
extern bool default_target_option_valid_attribute_p (tree, tree, tree, int);
extern bool default_target_option_pragma_parse (tree, tree);
extern bool default_target_can_inline_p (tree, tree);
extern bool default_valid_pointer_mode (machine_mode);
extern bool default_ref_may_alias_errno (struct ao_ref *);
extern machine_mode default_addr_space_pointer_mode (addr_space_t);
extern machine_mode default_addr_space_address_mode (addr_space_t);
extern bool default_addr_space_valid_pointer_mode (machine_mode,
						   addr_space_t);
extern bool default_addr_space_legitimate_address_p (machine_mode, rtx,
						     bool, addr_space_t);
extern rtx default_addr_space_legitimize_address (rtx, rtx, machine_mode,
						  addr_space_t);
extern bool default_addr_space_subset_p (addr_space_t, addr_space_t);
extern bool default_addr_space_zero_address_valid (addr_space_t);
extern int default_addr_space_debug (addr_space_t);
extern rtx default_addr_space_convert (rtx, tree, tree);
extern unsigned int default_case_values_threshold (void);
extern bool default_have_conditional_execution (void);

extern bool default_libc_has_function (enum function_class);
extern bool no_c99_libc_has_function (enum function_class);
extern bool gnu_libc_has_function (enum function_class);

extern tree default_builtin_tm_load_store (tree);

extern int default_memory_move_cost (machine_mode, reg_class_t, bool);
extern int default_register_move_cost (machine_mode, reg_class_t,
				       reg_class_t);

extern bool default_use_by_pieces_infrastructure_p (unsigned HOST_WIDE_INT,
						    unsigned int,
						    enum by_pieces_operation,
						    bool);

extern bool default_profile_before_prologue (void);
extern reg_class_t default_preferred_reload_class (rtx, reg_class_t);
extern reg_class_t default_preferred_output_reload_class (rtx, reg_class_t);
extern reg_class_t default_preferred_rename_class (reg_class_t rclass);
extern bool default_class_likely_spilled_p (reg_class_t);
extern unsigned char default_class_max_nregs (reg_class_t, machine_mode);

extern enum unwind_info_type default_debug_unwind_info (void);

extern void default_canonicalize_comparison (int *, rtx *, rtx *, bool);

extern int default_label_align_after_barrier_max_skip (rtx_insn *);
extern int default_loop_align_max_skip (rtx_insn *);
extern int default_label_align_max_skip (rtx_insn *);
extern int default_jump_align_max_skip (rtx_insn *);
extern section * default_function_section(tree decl, enum node_frequency freq,
					  bool startup, bool exit);
extern machine_mode default_dwarf_frame_reg_mode (int);
extern machine_mode default_get_reg_raw_mode (int);
extern bool default_keep_leaf_when_profiled ();

extern void *default_get_pch_validity (size_t *);
extern const char *default_pch_valid_p (const void *, size_t);

extern void default_asm_output_ident_directive (const char*);

extern machine_mode default_cstore_mode (enum insn_code);
extern bool default_member_type_forces_blk (const_tree, machine_mode);
extern void default_atomic_assign_expand_fenv (tree *, tree *, tree *);
extern tree build_va_arg_indirect_ref (tree);
extern tree std_gimplify_va_arg_expr (tree, tree, gimple_seq *, gimple_seq *);
extern bool can_use_doloop_if_innermost (const widest_int &,
					 const widest_int &,
					 unsigned int, bool);

extern rtx default_load_bounds_for_arg (rtx, rtx, rtx);
extern void default_store_bounds_for_arg (rtx, rtx, rtx, rtx);
extern rtx default_load_returned_bounds (rtx);
extern void default_store_returned_bounds (rtx,rtx);
extern tree default_chkp_bound_type (void);
extern enum machine_mode default_chkp_bound_mode (void);
extern tree default_builtin_chkp_function (unsigned int);
extern rtx default_chkp_function_value_bounds (const_tree, const_tree, bool);
extern tree default_chkp_make_bounds_constant (HOST_WIDE_INT lb, HOST_WIDE_INT ub);
extern int default_chkp_initialize_bounds (tree var, tree lb, tree ub,
					   tree *stmts);
extern void default_setup_incoming_vararg_bounds (cumulative_args_t ca ATTRIBUTE_UNUSED,
						  enum machine_mode mode ATTRIBUTE_UNUSED,
						  tree type ATTRIBUTE_UNUSED,
						  int *pretend_arg_size ATTRIBUTE_UNUSED,
						  int second_time ATTRIBUTE_UNUSED);
extern bool default_optab_supported_p (int, machine_mode, machine_mode,
				       optimization_type);

#endif /* GCC_TARGHOOKS_H */


text:
Improvement:

 - Log the browser URL when logging errors and exceptions

## 2.1.6 (2019-12-2)

Improvement:

 - Added support for NewRelic logging so errors can be sent there if needed

## 2.1.4 (2016-11-01)

Improvement:

  - Add setDefaultData(obj) to allow certain data to be logged on every logger call. (e.g. logging of user details)

## 2.1.3 (2016-10-26)

Bug fix:

  - Only log 'desc' param to console if set.

## 2.1.2 (2016-10-25)

Bug fix:

  - Log 'message' and 'desc' params correctly via the logger.

## 2.1.1 (2016-02-24)

Bug fix:

  - If overriding the logging threshold dynamically, also pass this value back to the remote logging URL.

## 2.1.0 (2016-02-23)

Features:

  - Allow override of the logging threshold by calling applicationLoggingService.setLoggingThreshold(level)

## 2.0.0 (2016-02-19)

Features:

  - Support all trace, debug, info, warn and error levels.
  - Use LOGGING_THRESHOLD instead of LOGGING_LEVEL in the config object for clarity, default is info level.

Bugfixes:

  - Use the correct console.xxx version to get the correct icons in the browser console for the log level requested.

## 1.x.x

Initial version


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dialogflow/v2/context.proto

package com.google.cloud.dialogflow.v2;

public final class ContextProto {
  private ContextProto() {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}

  public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
  }

  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_Context_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_Context_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_ListContextsRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_ListContextsRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_ListContextsResponse_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_GetContextRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_CreateContextRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_CreateContextRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_UpdateContextRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_UpdateContextRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_DeleteContextRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_DeleteContextRequest_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
      internal_static_google_cloud_dialogflow_v2_DeleteAllContextsRequest_descriptor;
  static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_cloud_dialogflow_v2_DeleteAllContextsRequest_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
    return descriptor;
  }

  private static com.google.protobuf.Descriptors.FileDescriptor descriptor;

  static {
    java.lang.String[] descriptorData = {
      "\n(google/cloud/dialogflow/v2/context.pro"
          + "to\022\032google.cloud.dialogflow.v2\032\034google/a"
          + "pi/annotations.proto\032\033google/protobuf/em"
          + "pty.proto\032 google/protobuf/field_mask.pr"
          + "oto\032\034google/protobuf/struct.proto\"\\\n\007Con"
          + "text\022\014\n\004name\030\001 \001(\t\022\026\n\016lifespan_count\030\002 \001"
          + "(\005\022+\n\nparameters\030\003 \001(\0132\027.google.protobuf"
          + ".Struct\"L\n\023ListContextsRequest\022\016\n\006parent"
          + "\030\001 \001(\t\022\021\n\tpage_size\030\002 \001(\005\022\022\n\npage_token\030"
          + "\003 \001(\t\"f\n\024ListContextsResponse\0225\n\010context"
          + "s\030\001 \003(\0132#.google.cloud.dialogflow.v2.Con"
          + "text\022\027\n\017next_page_token\030\002 \001(\t\"!\n\021GetCont"
          + "extRequest\022\014\n\004name\030\001 \001(\t\"\\\n\024CreateContex"
          + "tRequest\022\016\n\006parent\030\001 \001(\t\0224\n\007context\030\002 \001("
          + "\0132#.google.cloud.dialogflow.v2.Context\"}"
          + "\n\024UpdateContextRequest\0224\n\007context\030\001 \001(\0132"
          + "#.google.cloud.dialogflow.v2.Context\022/\n\013"
          + "update_mask\030\002 \001(\0132\032.google.protobuf.Fiel"
          + "dMask\"$\n\024DeleteContextRequest\022\014\n\004name\030\001 "
          + "\001(\t\"*\n\030DeleteAllContextsRequest\022\016\n\006paren"
          + "t\030\001 \001(\t2\357\007\n\010Contexts\022\254\001\n\014ListContexts\022/."
          + "google.cloud.dialogflow.v2.ListContextsR"
          + "equest\0320.google.cloud.dialogflow.v2.List"
          + "ContextsResponse\"9\202\323\344\223\0023\0221/v2/{parent=pr"
          + "ojects/*/agent/sessions/*}/contexts\022\233\001\n\n"
          + "GetContext\022-.google.cloud.dialogflow.v2."
          + "GetContextRequest\032#.google.cloud.dialogf"
          + "low.v2.Context\"9\202\323\344\223\0023\0221/v2/{name=projec"
          + "ts/*/agent/sessions/*/contexts/*}\022\252\001\n\rCr"
          + "eateContext\0220.google.cloud.dialogflow.v2"
          + ".CreateContextRequest\032#.google.cloud.dia"
          + "logflow.v2.Context\"B\202\323\344\223\002<\"1/v2/{parent="
          + "projects/*/agent/sessions/*}/contexts:\007c"
          + "ontext\022\262\001\n\rUpdateContext\0220.google.cloud."
          + "dialogflow.v2.UpdateContextRequest\032#.goo"
          + "gle.cloud.dialogflow.v2.Context\"J\202\323\344\223\002D2"
          + "9/v2/{context.name=projects/*/agent/sess"
          + "ions/*/contexts/*}:\007context\022\224\001\n\rDeleteCo"
          + "ntext\0220.google.cloud.dialogflow.v2.Delet"
          + "eContextRequest\032\026.google.protobuf.Empty\""
          + "9\202\323\344\223\0023*1/v2/{name=projects/*/agent/sess"
          + "ions/*/contexts/*}\022\234\001\n\021DeleteAllContexts"
          + "\0224.google.cloud.dialogflow.v2.DeleteAllC"
          + "ontextsRequest\032\026.google.protobuf.Empty\"9"
          + "\202\323\344\223\0023*1/v2/{parent=projects/*/agent/ses"
          + "sions/*}/contextsB\233\001\n\036com.google.cloud.d"
          + "ialogflow.v2B\014ContextProtoP\001ZDgoogle.gol"
          + "ang.org/genproto/googleapis/cloud/dialog"
          + "flow/v2;dialogflow\370\001\001\242\002\002DF\252\002\032Google.Clou"
          + "d.Dialogflow.V2b\006proto3"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
        descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.api.AnnotationsProto.getDescriptor(),
          com.google.protobuf.EmptyProto.getDescriptor(),
          com.google.protobuf.FieldMaskProto.getDescriptor(),
          com.google.protobuf.StructProto.getDescriptor(),
        },
        assigner);
    internal_static_google_cloud_dialogflow_v2_Context_descriptor =
        getDescriptor().getMessageTypes().get(0);
    internal_static_google_cloud_dialogflow_v2_Context_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_Context_descriptor,
            new java.lang.String[] {
              "Name", "LifespanCount", "Parameters",
            });
    internal_static_google_cloud_dialogflow_v2_ListContextsRequest_descriptor =
        getDescriptor().getMessageTypes().get(1);
    internal_static_google_cloud_dialogflow_v2_ListContextsRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_ListContextsRequest_descriptor,
            new java.lang.String[] {
              "Parent", "PageSize", "PageToken",
            });
    internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor =
        getDescriptor().getMessageTypes().get(2);
    internal_static_google_cloud_dialogflow_v2_ListContextsResponse_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor,
            new java.lang.String[] {
              "Contexts", "NextPageToken",
            });
    internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor =
        getDescriptor().getMessageTypes().get(3);
    internal_static_google_cloud_dialogflow_v2_GetContextRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_GetContextRequest_descriptor,
            new java.lang.String[] {
              "Name",
            });
    internal_static_google_cloud_dialogflow_v2_CreateContextRequest_descriptor =
        getDescriptor().getMessageTypes().get(4);
    internal_static_google_cloud_dialogflow_v2_CreateContextRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_CreateContextRequest_descriptor,
            new java.lang.String[] {
              "Parent", "Context",
            });
    internal_static_google_cloud_dialogflow_v2_UpdateContextRequest_descriptor =
        getDescriptor().getMessageTypes().get(5);
    internal_static_google_cloud_dialogflow_v2_UpdateContextRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_UpdateContextRequest_descriptor,
            new java.lang.String[] {
              "Context", "UpdateMask",
            });
    internal_static_google_cloud_dialogflow_v2_DeleteContextRequest_descriptor =
        getDescriptor().getMessageTypes().get(6);
    internal_static_google_cloud_dialogflow_v2_DeleteContextRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_DeleteContextRequest_descriptor,
            new java.lang.String[] {
              "Name",
            });
    internal_static_google_cloud_dialogflow_v2_DeleteAllContextsRequest_descriptor =
        getDescriptor().getMessageTypes().get(7);
    internal_static_google_cloud_dialogflow_v2_DeleteAllContextsRequest_fieldAccessorTable =
        new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
            internal_static_google_cloud_dialogflow_v2_DeleteAllContextsRequest_descriptor,
            new java.lang.String[] {
              "Parent",
            });
    com.google.protobuf.ExtensionRegistry registry =
        com.google.protobuf.ExtensionRegistry.newInstance();
    registry.add(com.google.api.AnnotationsProto.http);
    com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
        descriptor, registry);
    com.google.api.AnnotationsProto.getDescriptor();
    com.google.protobuf.EmptyProto.getDescriptor();
    com.google.protobuf.FieldMaskProto.getDescriptor();
    com.google.protobuf.StructProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
package org.apache.carbondata.core.util.comparator;

public class LongSerializableComparator implements SerializableComparator {
  @Override
  public int compare(Object key1, Object key2) {
    if (key1 == null && key2 == null) {
      return 0;
    } else if (key1 == null) {
      return -1;
    } else if (key2 == null) {
      return 1;
    }
    return Long.compare((long) key1, (long) key2);
  }
}


text:
CREATE VIEW {# geotrek.core #}.v_trails AS (
    SELECT core_topology.geom, core_topology.id, core_topology.uuid, core_trail.*
    FROM core_trail, core_topology
    WHERE core_trail.topo_object_id = core_topology.id
    AND core_topology.deleted = FALSE
);


text:
package org.ice4j.ice.harvest;

import org.ice4j.*;
import org.ice4j.ice.*;

import java.util.*;

/**
 * Uses a list of addresses as a predefined static mask in order to generate
 * {@link TransportAddress}es. This harvester is meant for use in situations
 * where servers are deployed behind a NAT or in a DMZ with static port mapping.
 *

 * Every time the {@link #harvest(Component)} method is called, the mapping
 * harvester will return a list of candidates that provide masked alternatives
 * for every host candidate in the component. Kind of like a STUN server.
 *

 * Example: You run this on a server with address 192.168.0.1, that is behind
 * a NAT with public IP: 93.184.216.119. You allocate a host candidate
 * 192.168.0.1/UDP/5000. This harvester is going to then generate an address
 * 93.184.216.119/UDP/5000
 *

 * This harvester is instant and does not introduce any harvesting latency.
 *
 * @author Emil Ivov
 */
public class MappingCandidateHarvester
    extends CandidateHarvester
{
    /**
     * The addresses that we will use as a mask
     */
    protected TransportAddress mask;

    /**
     * The addresses that we will be masking
     */
    protected TransportAddress face;

    /**
     * Creates a mapping harvester with the specified <tt>mask</tt>
     *
     * @param mask the <tt>TransportAddress</tt>es that would be used as a mask.
     * @param face the <tt>TransportAddress</tt>es that we will be masking.
     */
    public MappingCandidateHarvester(TransportAddress mask,
                                     TransportAddress face)
    {
        this.mask = mask;
        this.face = face;
    }

    /**
     * Maps all candidates to this harvester's mask and adds them to
     * <tt>component</tt>.
     *
     * @param component the {@link Component} that we'd like to map candidates
     * to.
     * @return  the <tt>LocalCandidate</tt>s gathered by this
     * <tt>CandidateHarvester</tt> or <tt>null</tt> if no mask is specified.
     */
    public Collection<LocalCandidate> harvest(Component component)
    {
        if (getMask() == null || getFace() == null)
            return null;

        /*
         * Report the LocalCandidates gathered by this CandidateHarvester so
         * that the harvest is sure to be considered successful.
         */
        Collection<LocalCandidate> candidates = new HashSet<LocalCandidate>();

        for (Candidate<?> cand : component.getLocalCandidates())
        {
            if (!(cand instanceof HostCandidate)
                || !cand.getTransportAddress().getHostAddress()
                            .equals(getFace().getHostAddress())
                || cand.getTransport() != getFace().getTransport())
            {
                continue;
            }

            HostCandidate hostCandidate = (HostCandidate) cand;
            TransportAddress mappedAddress = new TransportAddress(
                getMask().getHostAddress(),
                hostCandidate.getHostAddress().getPort(),
                hostCandidate.getHostAddress().getTransport());

            ServerReflexiveCandidate mappedCandidate
                = new ServerReflexiveCandidate(
                    mappedAddress,
                    hostCandidate,
                    hostCandidate.getStunServerAddress(),
                    CandidateExtendedType.STATICALLY_MAPPED_CANDIDATE);
            if (hostCandidate.isSSL())
                mappedCandidate.setSSL(true);

            //try to add the candidate to the component and then
            //only add it to the harvest not redundant
            if( !candidates.contains(mappedCandidate)
                && component.addLocalCandidate(mappedCandidate))
            {
                candidates.add(mappedCandidate);
            }
        }

        return candidates;
    }

    /**
     * Returns the public (mask) address, or null.
     * @return the public (mask) address, or null.
     */
    public TransportAddress getMask()
    {
        return this.mask;
    }

    /**
     * Returns the local (face) address, or null.
     * @return the local (face) address, or null.
     */
    public TransportAddress getFace()
    {
        return this.face;
    }
}


text:
//
// FreeVariables.scala -- Scala class/trait/object FreeVariables
// Project OrcScala
//
// Created by amp on Jun 2, 2013.
//
// Copyright (c) 2017 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//
package orc.ast.porc

/**
  * @author amp
  */
trait FreeVariables {
  this: PorcAST =>
  lazy val freeVars: Set[Variable] = {
    this match {
      case v: Variable => Set(v)
      case _ =>
        this.subtrees.flatMap(_.freeVars).toSet -- this.boundVars
    }
  }
}


text:
module ActiveRecord
  module ConnectionAdapters
    module Redshift
      module OID # :nodoc:
        class Enum < Type::Value # :nodoc:
          def type
            :enum
          end

          def type_cast(value)
            value.to_s
          end
        end
      end
    end
  end
end


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CmsStzefModulesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('name')
        ->add('contentHtml')
        ->add('dateCreation')
        ->add('modified')
        ->add('params')
        //->add('creatorUser')
        ->add('idTypeAccess')
        ->add('idTypeModule')
        ->add('idStatePublication')
        ->add('idSectionTheme')        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\CmsStzefModules'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_cmsstzefmodules';
    }

}


text:
namespace base {

struct Label {
    int index;
    const char *label;
};

class Labels {
public:
    Labels(const Label *alabel) {
        alabel_ = alabel;
    }
    const char *Find(int index) const {
        for (const Label *label = alabel_; label->label != NULL; label++) {
            if (label->index == index) {
                return label->label;
            }
        }
        return Format::ToString("UNKNOWN: %d", index);
    }
private:
    const Label *alabel_;
};

#ifdef LABELS
#define STARTLABEL(name) const base::Label name ## _labels[] = {
#define LABEL(x) { x, #x },
#define ENDLABEL(name) { 0, 0 } }; const base::Labels name(name ## _labels);
#else // !LABELS
#define STARTLABEL(name) const base::Label name ## _labels[] = {
#define LABEL(x)
#define ENDLABEL(name) { 0, 0 } }; const base::Labels name(name ## _labels);
#endif

class StringEncoder {
public:
    static const char *Escape(const char *s, bool quote = false);
    static const char *Replace(const char *s, const char *findstr,
            const char *replacewith);
    static const char *QueryEncode(const char *s);
};

} // namespace base

#endif // __BASE_MISC_H__


text:
package com.hackanton.event;

/**
 * @author ddorochov
 */
public enum EventType {
	HACKATHON, MEETUP, SEMINAR, WORKSHOP,
	JOB_FAIRS, TRAINING, CONFERENCE, OTHER;

	@Override
	public String toString() {
		String lowerCase = super.toString().toLowerCase();
		char firstLetter = lowerCase.charAt(0);
		return Character.toUpperCase(firstLetter) + lowerCase.substring(1);
	}
}


text:
layout: post
title: 404 - page not found
---

The requested page could not be found.


text:
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)

Run workdpress on Heroku with WP-Packagist

adding something in the readme


text:
var Koa = require('koa')
var bodyParser  = require('koa-bodyparser')
var cors = require('koa-cors')
var path = require('path')
var views = require('koa-views')
var serve = require('koa-static')
const Sequelize = require('sequelize')
var compress = require('koa-compress')

const config = require('./config')
const carController = require('./controllers/car')
const indexController = require('./controllers/index')

require('./lib/helper')()

var sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    idle: 30000
  }
})

const app = new Koa()

app.use(cors())

app.use(views(__dirname + '/views', {
  map: {
    html: 'nunjucks'
  }
}))
app.use(bodyParser())
  .use(indexController.routes())
  .use(carController.routes())

app.use(serve(__dirname + '/public/assets'))

module.exports =  app


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Willdenow, Willd. , Sp. pl. , Edn 4 6(2): 23 (1825)

#### Original name
Uredo aegopodii (Rebent.) G. Winter

### Remarks
null


text:
<?php

namespace Application\Authentication;
use Zend\Session\Container;

class AuthUser
{
    public function Validate(){
        //This plugin validates that a user has logged in properly
        $namespace = new Container('user');
        if ($namespace->datatelID == null){
           return false;
        }
        else{
                return true;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Route;

use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Builder\RouteBuilderInterface;
use Sonata\AdminBundle\Model\AuditManagerInterface;

/**
 * @final since sonata-project/admin-bundle 3.52
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class PathInfoBuilder implements RouteBuilderInterface
{
    /**
     * @var AuditManagerInterface
     */
    protected $manager;

    public function __construct(AuditManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    public function build(AdminInterface $admin, RouteCollection $collection)
    {
        $collection->add('list');
        $collection->add('create');
        $collection->add('batch');
        $collection->add('edit', sprintf('%s/edit', $admin->getRouterIdParameter()));
        $collection->add('delete', sprintf('%s/delete', $admin->getRouterIdParameter()));
        $collection->add('show', sprintf('%s/show', $admin->getRouterIdParameter()));
        $collection->add('export');

        if ($this->manager->hasReader($admin->getClass())) {
            $collection->add('history', sprintf('%s/history', $admin->getRouterIdParameter()));
            $collection->add('history_view_revision', sprintf('%s/history/{revision}/view', $admin->getRouterIdParameter()));
            $collection->add('history_compare_revisions', sprintf('%s/history/{baseRevision}/{compareRevision}/compare', $admin->getRouterIdParameter()));
        }

        if ($admin->isAclEnabled()) {
            $collection->add('acl', sprintf('%s/acl', $admin->getRouterIdParameter()));
        }

        // add children urls
        foreach ($admin->getChildren() as $children) {
            $collection->addCollection($children->getRoutes());
        }
    }
}


text:
<Alloy>
    <Window class="container" layout="vertical">
        <View height="90%" id="MapView_1" module="ti.map"/>
        <View height="10%" width="100%">
            <Button id="refreshBtn" onClick="redoQuery" title="Redo Query"/>
        </View>
    </Window>
</Alloy>


text:
package org.mybatis.guice.configuration.settings;

import com.google.inject.Injector;
import com.google.inject.Key;

import javax.inject.Inject;
import javax.inject.Provider;

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;

public final class JavaTypeAndHandlerConfigurationSettingProvider implements Provider<ConfigurationSetting> {
  @Inject
  private Injector injector;

  private final Wrapper<?> wrapper;

  private JavaTypeAndHandlerConfigurationSettingProvider(final Wrapper<?> wrapper) {
    this.wrapper = wrapper;
  }

  @Override
  public ConfigurationSetting get() {
    return wrapper.get(injector);
  }

  public static <T> JavaTypeAndHandlerConfigurationSettingProvider create(final Class<T> type,
      final Key<? extends TypeHandler<? extends T>> key) {
    return new JavaTypeAndHandlerConfigurationSettingProvider(new Wrapper<T>(type, key));
  }

  private static class Wrapper<T> {
    private final Class<T> type;
    private final Key<? extends TypeHandler<? extends T>> key;

    private Wrapper(final Class<T> type, final Key<? extends TypeHandler<? extends T>> key) {
      this.type = type;
      this.key = key;
    }

    ConfigurationSetting get(Injector injector) {
      final TypeHandler<? extends T> handlerInstance = injector.getInstance(key);
      return new ConfigurationSetting() {
        @Override
        public void applyConfigurationSetting(Configuration configuration) {
          configuration.getTypeHandlerRegistry().register(type, handlerInstance);
        }
      };
    }
  }
}


text:
namespace DataAccessLayer
{
    /// Interface definition for a key rule.
    public interface IKeyRule
    {
        /// Generate the key field.
        /// <param name="entity">The entity.</param>
        /// <returns>The key field.</returns>
        string GenerateKeyField(IEntity entity);
    }
}


text:
namespace tonic {

Dart_Handle CreateDartString(StringImpl* string_impl);
String ExternalizeDartString(Dart_Handle handle);

}  // namespace tonic

#endif  // TONIC_DART_STRING_H_


text:
#include <ruby.h>
#include <ruby/st.h>
#include <stdlib.h>
#include <assert.h>

#define COVERAGE_DEBUG_EVENTS 0

#define RCOVRT_VERSION_MAJOR 2
#define RCOVRT_VERSION_MINOR 0
#define RCOVRT_VERSION_REV   0

static VALUE mRcov;
static VALUE mRCOV__;
static VALUE oSCRIPT_LINES__;
static ID id_cover;
static st_table* coverinfo = 0;
static char coverage_hook_set_p;

struct cov_array {
  unsigned int len;
  unsigned int *ptr;
};

static struct cov_array *cached_array = 0;
static char *cached_file = 0;

static struct cov_array * coverage_increase_counter_uncached(char *sourcefile, unsigned int sourceline, char mark_only) {
  struct cov_array *carray = NULL;

  if(sourcefile == NULL) {
    /* "can't happen", just ignore and avoid segfault */
    return NULL;
  }
  else if(!st_lookup(coverinfo, (st_data_t)sourcefile, (st_data_t*)&carray)) {
    VALUE arr;

    arr = rb_hash_aref(oSCRIPT_LINES__, rb_str_new2(sourcefile));
    if(NIL_P(arr))
      return 0;
    rb_check_type(arr, T_ARRAY);
    carray = calloc(1, sizeof(struct cov_array));
    carray->ptr = calloc(RARRAY_LEN(arr), sizeof(unsigned int));
    carray->len = RARRAY_LEN(arr);
    st_insert(coverinfo, (st_data_t)strdup(sourcefile), (st_data_t) carray);
  }
  else {
    /* recovered carray, sanity check */
    assert(carray && "failed to create valid carray");
  }

  if(mark_only) {
    if(!carray->ptr[sourceline])
      carray->ptr[sourceline] = 1;
  }
  else {
    if (carray && carray->len > sourceline) {
      carray->ptr[sourceline]++;
    }
  }

  return carray;
}

static void coverage_mark_caller() {
  coverage_increase_counter_uncached(rb_sourcefile(), rb_sourceline(), 1);
}

static void coverage_increase_counter_cached(char *sourcefile, int sourceline) {
  if(cached_file == sourcefile && cached_array && cached_array->len > sourceline) {
    cached_array->ptr[sourceline]++;
    return;
  }
  cached_file = sourcefile;
  cached_array = coverage_increase_counter_uncached(sourcefile, sourceline, 0);
}

static void coverage_event_coverage_hook(rb_event_flag_t event, VALUE node, VALUE self, ID mid, VALUE klass) {
  char *sourcefile;
  unsigned int sourceline;
  static unsigned int in_hook = 0;

  if(in_hook) {
    return;
  }

  in_hook++;

  #if COVERAGE_DEBUG_EVENTS
  do {
    int status;
    VALUE old_exception;
    old_exception = rb_gv_get("$!");
    rb_protect(rb_inspect, klass, &status);
    if(!status) {
      printf("EVENT: %d %s %s %s %d\n", event,
             klass ? RSTRING(rb_inspect(klass))->ptr : "",
             mid ? (mid == ID_ALLOCATOR ? "ID_ALLOCATOR" : rb_id2name(mid))
             : "unknown",
             node ? node->nd_file : "", node ? nd_line(node) : 0);
    }
    else {
      printf("EVENT: %d %s %s %d\n", event,
             mid ? (mid == ID_ALLOCATOR ? "ID_ALLOCATOR" : rb_id2name(mid))
             : "unknown",
             node ? node->nd_file : "", node ? nd_line(node) : 0);
    }
    rb_gv_set("$!", old_exception);
  } while (0);
  #endif

  if(event & RUBY_EVENT_C_CALL) {
    coverage_mark_caller();
  }
  if(event & (RUBY_EVENT_C_CALL | RUBY_EVENT_C_RETURN | RUBY_EVENT_CLASS)) {
    in_hook--;
    return;
  }

  sourcefile = rb_sourcefile();
  sourceline = rb_sourceline();

  if (0 == sourceline || 0 == sourcefile) {
    in_hook--;
    return;
  }

  coverage_increase_counter_cached(sourcefile, sourceline);
  if(event & RUBY_EVENT_CALL)
    coverage_mark_caller();
  in_hook--;
}

static VALUE cov_install_coverage_hook(VALUE self) {
  if(!coverage_hook_set_p) {
    if(!coverinfo)
      coverinfo = st_init_strtable();
    coverage_hook_set_p = 1;
    /* TODO: allow C_CALL too, since it's supported already
     * the overhead is around ~30%, tested on typo */
    VALUE holder = 0;
    rb_add_event_hook(coverage_event_coverage_hook,
                      RUBY_EVENT_ALL & ~RUBY_EVENT_C_CALL &
                      ~RUBY_EVENT_C_RETURN & ~RUBY_EVENT_CLASS, holder);
    return Qtrue;
  }
  else
    return Qfalse;
}

static int populate_cover(st_data_t key, st_data_t value, st_data_t cover) {
  VALUE rcover;
  VALUE rkey;
  VALUE rval;
  struct cov_array *carray;
  unsigned int i;

  rcover = (VALUE)cover;
  carray = (struct cov_array *) value;
  rkey = rb_str_new2((char*) key);
  rval = rb_ary_new2(carray->len);
  for(i = 0; i < carray->len; i++)
    rb_ary_push(rval, UINT2NUM(carray->ptr[i]));

  rb_hash_aset(rcover, rkey, rval);

  return ST_CONTINUE;
}

static int free_table(st_data_t key, st_data_t value, st_data_t ignored) {
  struct cov_array *carray;

  carray = (struct cov_array *) value;
  free((char *)key);
  free(carray->ptr);
  free(carray);

  return ST_CONTINUE;
}

static VALUE cov_remove_coverage_hook(VALUE self) {
  if(!coverage_hook_set_p)
    return Qfalse;
  else {
    rb_remove_event_hook(coverage_event_coverage_hook);
    coverage_hook_set_p = 0;
    return Qtrue;
  }
}

static VALUE cov_generate_coverage_info(VALUE self) {
  VALUE cover;

  if(rb_const_defined_at(mRCOV__, id_cover)) {
    rb_mod_remove_const(mRCOV__, ID2SYM(id_cover));
  }

  cover = rb_hash_new();
  if(coverinfo)
    st_foreach(coverinfo, populate_cover, cover);
  rb_define_const(mRCOV__, "COVER", cover);

  return cover;
}

static VALUE cov_reset_coverage(VALUE self) {
  if(coverage_hook_set_p) {
    rb_raise(rb_eRuntimeError, "Cannot reset the coverage info in the middle of a traced run.");
    return Qnil;
  }

  cached_array = 0;
  cached_file = 0;
  st_foreach(coverinfo, free_table, Qnil);
  st_free_table(coverinfo);
  coverinfo = 0;

  return Qnil;
}

static VALUE cov_ABI(VALUE self) {
  VALUE ret;

  ret = rb_ary_new();
  rb_ary_push(ret, INT2FIX(RCOVRT_VERSION_MAJOR));
  rb_ary_push(ret, INT2FIX(RCOVRT_VERSION_MINOR));
  rb_ary_push(ret, INT2FIX(RCOVRT_VERSION_REV));

  return ret;
}

void Init_rcovrt() {
  ID id_rcov = rb_intern("Rcov");
  ID id_coverage__ = rb_intern("RCOV__");
  ID id_script_lines__ = rb_intern("SCRIPT_LINES__");

  id_cover = rb_intern("COVER");

  if(rb_const_defined(rb_cObject, id_rcov))
    mRcov = rb_const_get(rb_cObject, id_rcov);
  else
    mRcov = rb_define_module("Rcov");

  if(rb_const_defined(mRcov, id_coverage__))
    mRCOV__ = rb_const_get_at(mRcov, id_coverage__);
  else
    mRCOV__ = rb_define_module_under(mRcov, "RCOV__");

  if(rb_const_defined(rb_cObject, id_script_lines__))
    oSCRIPT_LINES__ = rb_const_get(rb_cObject, rb_intern("SCRIPT_LINES__"));
  else {
    oSCRIPT_LINES__ = rb_hash_new();
    rb_const_set(rb_cObject, id_script_lines__, oSCRIPT_LINES__);
  }

  coverage_hook_set_p = 0;

  rb_define_singleton_method(mRCOV__, "install_coverage_hook", cov_install_coverage_hook, 0);
  rb_define_singleton_method(mRCOV__, "remove_coverage_hook", cov_remove_coverage_hook, 0);
  rb_define_singleton_method(mRCOV__, "generate_coverage_info", cov_generate_coverage_info, 0);
  rb_define_singleton_method(mRCOV__, "reset_coverage", cov_reset_coverage, 0);
  rb_define_singleton_method(mRCOV__, "ABI", cov_ABI, 0);

  Init_rcov_callsite();
}


text:
package uk.ac.open.kmi.iserve.rest.sal.auth.oauth;//package uk.ac.open.kmi.iserve.sal.rest.auth.oauth;
//
//import java.io.IOException;
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.util.List;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpSession;
//import javax.ws.rs.FormParam;
//import javax.ws.rs.GET;
//import javax.ws.rs.POST;
//import javax.ws.rs.Path;
//import javax.ws.rs.Produces;
//import javax.ws.rs.QueryParam;
//import javax.ws.rs.core.Context;
//import javax.ws.rs.core.MediaType;
//import javax.ws.rs.core.Response;
//import javax.ws.rs.core.Response.Status;
//
//import org.openid4java.association.AssociationException;
//import org.openid4java.consumer.ConsumerException;
//import org.openid4java.consumer.ConsumerManager;
//import org.openid4java.consumer.VerificationResult;
//import org.openid4java.discovery.DiscoveryException;
//import org.openid4java.discovery.DiscoveryInformation;
//import org.openid4java.discovery.Identifier;
//import org.openid4java.message.AuthRequest;
//import org.openid4java.message.MessageException;
//import org.openid4java.message.ParameterList;
//import org.openrdf.repository.RepositoryException;
//
//import uk.ac.open.kmi.iserve.sal.manager.impl.ManagerSingleton;
//import uk.ac.open.kmi.iserve.sal.model.oauth.RequestToken;
//
//@Path("/authorize")
//public class AuthorizeResource {
//
//	private static final String loginHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
//		"\n" +
//		"\n" +
//		"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
//		"<title>Login iServe with OpenID</title>\n" +
//		"\n" +
//		"\n" +
//		"	<form action=\"authorize\" method=\"post\">\n" +
//		"
\n" +
//		"			<input type=\"hidden\" name=\"oauth_token\" id=\"oauth_token\" value=\"<<<oauth_token>>>\" />\n" +
//		"
OpenID	<input type=\"text\" name=\"OpenID\" />
\n" +
//		"
<input type=\"submit\" name=\"login\" value=\"Login\" />
\n" +
//		"
\n" +
//		"	</form>\n" +
//		"\n" +
//		"";
//
//	private static final String authHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
//		"\n" +
//		"\n" +
//		"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
//		"<title>Authorization</title>\n" +
//		"\n" +
//		"\n" +
//		"	<form action=\"authorize\" method=\"post\">\n" +
//		"
\n" +
//		"			<input type=\"hidden\" name=\"oauth_token\" id=\"oauth_token\" value=\"<<<oauth_token>>>\" />\n" +
//		"			<input type=\"hidden\" name=\"OpenID\" id=\"OpenID\" value=\"<<<openid>>>\" />\n" +
//		"
<<<customer_key>>> request for access to <<<openid>>>'s iServe account.
" +
//		"
	<input type=\"submit\" name=\"allow\" id=\"allow\" value=\"Allow\" />" +
//		"             <input type=\"submit\" name=\"deny\" id=\"deny\" value=\"Deny\" />
\n" +
//		"
\n" +
//		"	</form>\n" +
//		"\n" +
//		"";
//
//	private static ConsumerManager manager = null;
//
//	public AuthorizeResource() throws ConsumerException, RepositoryException, IOException {
//		// TODO: set the proxy for OpenID consumer
//		if ( manager == null ) {
//			manager = new ConsumerManager();
//		}
//	}
//
//	@GET
//	@Produces(MediaType.TEXT_HTML)
//	public Response authorize(@QueryParam("oauth_token") String oauthToken, @Context HttpServletRequest request) throws MessageException, DiscoveryException, AssociationException {
//		if ( oauthToken == null ) {
//			System.out.println("oauthToken == null");
//		}
//		if ( request.getSession().getAttribute("openid-disc") == null ) {
//			return Response.ok().entity(loginHtml.replaceAll("<<<oauth_token>>>", oauthToken)).build();
//		} else {
//			ParameterList response = new ParameterList(request.getParameterMap());
//			// retrieve the previously stored discovery information
//			DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
//			// extract the receiving URL from the HTTP request
//			StringBuffer receivingURL = request.getRequestURL();
//			String queryString = request.getQueryString();
//			if ( queryString != null && queryString.length() > 0 ) {
//				receivingURL.append("?").append(queryString);
//			}
//
//			// verify the response; ConsumerManager needs to be the same
//			// (static) instance used to place the authentication request
//			VerificationResult verification = manager.verify(
//					receivingURL.toString(),
//					response, discovered);
//
//            // examine the verification result and extract the verified identifier
//            Identifier verified = verification.getVerifiedId();
//            if (verified != null) {
//            	HttpSession session = request.getSession();
//    			session.setAttribute("logged-in", verified.toString());
//    			session.removeAttribute("openid-disc");
//    			RequestToken requestToken = ManagerSingleton.getInstance().findRequestToken(oauthToken);
//    			String entityString = authHtml.replaceAll("<<<customer_key>>>", requestToken.getConsumer().toString()).replaceAll("<<<openid>>>", verified.toString())
//    					.replace("<<<oauth_token>>>", oauthToken);
//            	return Response.ok().entity(entityString).build();
//            } else {
//              	return Response.status(400).entity("error").build();
//            }
//		}
//	}
//
//	//TODO: Fix authentication here!
//	@POST
//	@Produces(MediaType.TEXT_HTML)
//	public Response login(@FormParam("oauth_token") String oauthToken,
//			@FormParam("OpenID") String userSuppliedString,
//			@FormParam("allow") String allowString,
//			@FormParam("deny") String denyString,
//			@Context HttpServletRequest request) throws DiscoveryException, MessageException, ConsumerException, URISyntaxException {
//		if ( allowString != null || denyString != null ) {
//			if ( allowString != null && allowString.endsWith("Allow") ) {
//				// save the authorized oauth_token
//				// TODO: callback
//				ManagerSingleton.getInstance().saveAuthorization(oauthToken, userSuppliedString, null);
//				return Response.ok().entity("Go to Access Token").build();
//			} else if ( denyString != null && denyString.endsWith("Deny")) {
//				return Response.status(Status.BAD_REQUEST).entity("Denied by the user").build();
//			}
//			return Response.status(Status.BAD_REQUEST).entity("Error occurs during authorization").build();
//		} else {
//			String returnToUrl = "http://localhost:8080/iserve/oauth/authorize?oauth_token=" + oauthToken;
//			// perform discovery on the user-supplied identifier
//			List discoveries = manager.discover(userSuppliedString);
//
//			// attempt to associate with the OpenID provider
//			// and retrieve one service endpoint for authentication
//			DiscoveryInformation discovered = manager.associate(discoveries);
//
//			// store the discovery information in the user's session
//			request.getSession().setAttribute("openid-disc", discovered);
//
//			// obtain a AuthRequest message to be sent to the OpenID provider
//			AuthRequest authReq = manager.authenticate(discovered, returnToUrl);
//	//		if (!discovered.isVersion2() ) {
//				// Option 1: GET HTTP-redirect to the OpenID Provider endpoint
//				// The only method supported in OpenID 1.x
//				// redirect-URL usually limited ~2048 bytes
//				return Response.seeOther(new URI(authReq.getDestinationUrl(true))).build();
//	//		} else {
//				// Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)
//	//			RequestDispatcher dispatcher =
//	//                    getServletContext().getRequestDispatcher("formredirection.jsp");
//	//            httpReq.setAttribute("parameterMap", authReq.getParameterMap());
//	//            httpReq.setAttribute("destinationUrl", authReq.getDestinationUrl(false));
//	//            dispatcher.forward(httpReq, httpResp);
//	//			return null;
//	//		}
//		}
//	}
//
//}


text:
<component name="ProjectDictionaryState">
  <dictionary name="jfemiani">
    <words>
      <w>shapefiles</w>
    </words>
  </dictionary>
</component>


text:
package com.creativemindz.droidmodel;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
#ifndef SECP256K1_ECMULT_H
#define SECP256K1_ECMULT_H

#include "group.h"
#include "scalar.h"
#include "scratch.h"

/* Noone will ever need more than a window size of 24. The code might
 * be correct for larger values of ECMULT_WINDOW_SIZE but this is not
 * tested.
 *
 * The following limitations are known, and there are probably more:
 * If WINDOW_G > 27 and size_t has 32 bits, then the code is incorrect
 * because the size of the memory object that we allocate (in bytes)
 * will not fit in a size_t.
 * If WINDOW_G > 31 and int has 32 bits, then the code is incorrect
 * because certain expressions will overflow.
 */
#if ECMULT_WINDOW_SIZE < 2 || ECMULT_WINDOW_SIZE > 24
#  error Set ECMULT_WINDOW_SIZE to an integer in range [2..24].
#endif

/** The number of entries a table with precomputed multiples needs to have. */
#define ECMULT_TABLE_SIZE(w) (1L << ((w)-2))

/** Double multiply: R = na*A + ng*G */
static void secp256k1_ecmult(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng);

typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data);

/**
 * Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai.
 * Chooses the right algorithm for a given number of points and scratch space
 * size. Resets and overwrites the given scratch space. If the points do not
 * fit in the scratch space the algorithm is repeatedly run with batches of
 * points. If no scratch space is given then a simple algorithm is used that
 * simply multiplies the points with the corresponding scalars and adds them up.
 * Returns: 1 on success (including when inp_g_sc is NULL and n is 0)
 *          0 if there is not enough scratch space for a single point or
 *          callback returns 0
 */
static int secp256k1_ecmult_multi_var(const secp256k1_callback* error_callback, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n);

#endif /* SECP256K1_ECMULT_H */


text:
import pyexcel.ext.ods3  # noqa
import pyexcel.ext.xls
import pyexcel.ext.xlsx
from pyramid.view import view_config

import pyramid_excel as excel

from .models import Category, DBSession, Post

@view_config(route_name="home", renderer="templates/mytemplate.pt")
def my_view(request):
    return {"project": "MyProject"}

@view_config(route_name="switch")
def switch(request):
    sheet = request.get_sheet(field_name="file")
    return excel.make_response(
        sheet, request.matchdict.get("file_type", "csv")
    )

@view_config(route_name="upload", renderer="templates/upload_form.pt")
def upload_view(request):
    if request.method == "POST":
        data = request.get_array(field_name="file")
        return excel.make_response_from_array(data, "xls")

@view_config(route_name="download", renderer="templates/upload_form.pt")
def download_attachment(request):
    data = [[1, 2], [3, 4]]
    return excel.make_response_from_array(
        data,
        request.matchdict.get("file_type", "csv"),
        file_name=request.matchdict.get("file_name", ""),
    )

@view_config(route_name="uploadall")
def upload_all(request):
    def category_init_func(row):
        c = Category(row["name"])
        c.id = row["id"]
        return c

    def post_init_func(row):
        # this is lessons learned that relation needs an object not a string
        c = DBSession.query(Category).filter_by(name=row["category"]).first()
        p = Post(row["title"], row["body"], c, row["pub_date"])
        return p

    request.save_book_to_database(
        field_name="file",
        session=DBSession,
        tables=[Category, Post],
        initializers=[category_init_func, post_init_func],
    )
    return excel.make_response_from_tables(DBSession, [Category, Post], "xls")

@view_config(route_name="upload_categories")
def upload_categories(request):
    def table_init_func(row):
        return Category(row["name"])

    request.save_to_database(
        field_name="file",
        session=DBSession,
        table=Category,
        initializer=table_init_func,
    )
    return excel.make_response_from_a_table(DBSession, Category, "xls")


text:
'''
Created on Dec 11, 2013

@author: luka
'''
from django.forms.models import ModelForm
from django.contrib.auth.models import User
from django.forms.fields import CharField
from django.forms.util import ErrorList
from django.forms.forms import Form

class RegisterForm(ModelForm):
    password_retype = CharField(max_length=30, min_length=4, required=True)

    def is_valid(self):
        valid =super(RegisterForm, self).is_valid()

        if valid:
            if self.cleaned_data['password']!=self.cleaned_data['password_retype']:
                self.errors['password'] = ErrorList(['passwords don\'t match'])
                valid = False
            del self.cleaned_data['password_retype']

        return valid

    class Meta:
        model = User
        fields = ['username', 'password', 'email', 'first_name', 'last_name']

class LoginForm(Form):
    username = CharField(max_length=25, min_length=4)
    password = CharField(max_length=25, min_length=4)


text:
#include "PimInternal.h"

#include "PimLightDef.h"
#include "PimLayer.h"
#include "PimGameNode.h"
#include "PimVec2.h"
#include "PimGameControl.h"
#include "PimAssert.h"
#include "PimScene.h"
#include "PimRenderTexture.h"
#include "PimShaderManager.h"
#include "PimRenderWindow.h"

namespace Pim {
	/*
	=====================
	Layer::Layer
	=====================
	*/
	Layer::Layer(void) {
		color		= Color(1.f, 1.f, 1.f, 1.f);
		immovable	= false;
		scale		= Vec2(1.f, 1.f);
		lightSys	= NULL;
		parentScene = NULL;
		shader		= NULL;
		rt			= NULL;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	Layer::~Layer(void) {
		DestroyLightingSystem();

		if (rt) {
			delete rt;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	Scene* Layer::GetParentScene() const {
		if (parent) {
			return parent->GetParentScene();
		} else {
			return parentScene;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	Layer* Layer::GetParentLayer() {
		return this;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	Vec2 Layer::GetWorldPosition() const {
		if (immovable) {
			return position;
		}

		if (parent) {
			return GameNode::GetWorldPosition();
		}

		return position;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	float Layer::GetWorldRotation() const {
		if (parent) {
			return rotation + parent->GetWorldRotation();
		}

		return rotation;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	Vec2 Layer::GetLayerPosition() const {
		return Vec2(0.f, 0.f);
	}

	/*
	==================
	Layer::GetLayerRotation
	==================
	*/
	float Layer::GetLayerRotation() const {
		return 0.f;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetImmovableLayer(bool immov) {
		immovable = immov;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::Draw() {
		PrepareRT();

		glPushMatrix();

		if (immovable) {
			glLoadIdentity();
		}

		// Update position
		Vec2 fac = GameControl::GetSingleton()->GetCoordinateFactor();

		glTranslatef(position.x / fac.x, position.y / fac.y, 0.f);
		glRotatef(rotation, 0.f, 0.f, 1.f);

		fac = GameControl::GetSingleton()->GetWindowScale();
		glScalef(scale.x, scale.y, 1.f);

		OrderChildren();

		if (lightSys) {
			lightSys->UpdateShaderUniforms();
		}

		for (unsigned int i=0; i<children.size(); i++) {
			children[i]->Draw();
		}

		if (lightSys) {
			lightSys->RenderLightTexture();
		}

		glPopMatrix();

		RenderRT();
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetZOrder(const int z) {
		if (parent) {
			parent->dirtyZOrder = true;
		} else if (parentScene) {
			parentScene->dirtyZOrder = true;
		}

		zOrder = z;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetShader(Shader *s) {
		shader = s;

		if (s && !rt) {
				curRTRes = GameControl::GetSingleton()->GetRenderWindow()->GetOrtho();
				rt = new RenderTexture(curRTRes);
		}
	}

	/*
	=====================
	Layer::GetColor
	=====================
	*/
	Color Layer::GetColor() const {
		return color;
	}

	// ---------- LIGHTING SYSTEM METHODS ----------
	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::CreateLightingSystem(Vec2 resolution) {
		DestroyLightingSystem();
		lightSys = new LightingSystem(this, resolution);
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::DestroyLightingSystem() {
		if (lightSys) {
			delete lightSys;
			lightSys = NULL;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::AddLight(GameNode *node, LightDef *lDef) {
		PimAssert(node->parent != NULL, "ERROR: Orphan lights are not allowed");

		if (lightSys) {
			lightSys->AddLight(node, lDef);
		}
	}

	/*
	=====================
	Layer::Layer

		Add a light using a preloaded texture.
		Define the light texture to use with the identifier string.
		Lights can be preloaded through the PreloadLightDef method.
	=====================
	*/
	bool Layer::AddLight(GameNode *node, PreloadLightDef *pld, const string identifier) {
		if (lightSys) {
			if (!lightSys->UsePreloadedTexture(pld, identifier)) {
				return false;
			}

			AddLight(node, pld);
			return true;
		}

		return false;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::RemoveLight(GameNode *node) {
		if (lightSys) {
			lightSys->RemoveLight(node);
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::PreloadLightTexture(LightDef *ld, const string identifier) {
		if (ld) {
			if (lightSys) {
				lightSys->PreloadTexture(ld, identifier);
			}

			delete ld;
		}
	}

	/*
	=====================
	Layer::Layer

		The GameNode must have a ShadowShape prepared before it's added.
		use:	GameNode::SetShadowShape(Vec2[], int)
	=====================
	*/
	void Layer::AddShadowCaster(GameNode *caster) {
		if (lightSys) {
			PimAssert(caster->GetShadowShape() != NULL,
						"Error: Shadow Caster must have a defined shadow shape");

			lightSys->casters.push_back(caster);
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::RemoveShadowCaster(GameNode *caster) {
		if (lightSys) {
			lightSys->RemoveShadowCaster(caster);
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetCastShadows(bool shadows) {
		if (lightSys) {
			lightSys->castShadow = shadows;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetLightingUnlitColor(const Color color) {
		if (lightSys) {
			lightSys->SetUnlitColor(color);
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetLightAlpha(const float a) {
		if (lightSys) {
			lightSys->SetLightAlpha(a);
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetSmoothShadows(const bool flag) {
		if (lightSys) {
			lightSys->hqShadow = flag;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::SetShadowcasterDebugDraw(const bool flag) {
		if (lightSys) {
			lightSys->dbgDrawNormal = flag;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	LightingSystem* Layer::GetLightingSystem() const {
		return lightSys;
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::PrepareRT() {
		if (shader) {
			if (curRTRes != GameControl::GetSingleton()->GetRenderWindow()->GetOrtho()) {
				delete rt;

				curRTRes = GameControl::GetSingleton()->GetRenderWindow()->GetOrtho();
				rt = new RenderTexture(curRTRes);
			}

			rt->BindFBO();
			rt->Clear();
		} else if (rt) {
			delete rt;
			rt = NULL;
		}
	}

	/*
	=====================
	Layer::Layer
	=====================
	*/
	void Layer::RenderRT() const  {
		if (shader) {
			rt->UnbindFBO();

			glUseProgram(shader->GetProgram());

			rt->BindTex();

			glPushMatrix();
			glLoadIdentity();
			glColor3ub(255,255,255);

			glBegin(GL_QUADS);
				glTexCoord2i(0, 0); glVertex2f(0.f,			0.f);
				glTexCoord2i(1, 0); glVertex2f(curRTRes.x,	0.f);
				glTexCoord2i(1, 1); glVertex2f(curRTRes.x,	curRTRes.y);
				glTexCoord2i(0, 1); glVertex2f(0.f,			curRTRes.y);
			glEnd();

			glPopMatrix();

			glUseProgram(0);
		}
	}
}


text:
"""Django admin configuration form.

Contains classes to configure how the models are displayed and edited in the
Django administration side.

"""

from django.contrib import admin
from core.models import UserProfile, Course, Sale, Offer

class CourseAdmin(admin.ModelAdmin):
    """Admin form configuration for the Course model."""

    fieldsets = [
        ('Course', {'fields': [
            'number',
            'name',
        ]})
    ]
    list_display = ('number', 'name')

class SaleAdmin(admin.ModelAdmin):
    """Admin form configuration for the Sale model."""

    fieldsets = [
        ('Sale', {'fields': [
            'status',
            'merchant',
            'course',
            'matches_official',
            'condition',
            'title',
            'image',
            'price',
            'expires',
            'notes',
            'isbn'
        ]})
    ]
    list_display = ('id', 'title', 'course', 'merchant', 'status', 'price', 'expires')

class OfferAdmin(admin.ModelAdmin):
    """Admin form configuration for the Offer model."""

    fieldsets = [
        ('Book', {'fields': [
            'status',
            'sale',
            'buyer',
            'price'
        ]})
    ]
    list_display = ('sale', 'buyer', 'price', 'status')

class UserProfileAdmin(admin.ModelAdmin):
    """Admin form configurationfor the UserProfile model."""
    fieldsets = [
        (None, {'fields': [
            'user',
            'activation_key',
            'key_expires',
            'is_verified',
            'is_disabled',
            'phone',
            'show_phone',
            'last_login_date',
            'reg_ip',
            'last_login_ip',
            'first_login'
        ]}),
    ]
    list_display = ('user', 'last_login_date', 'key_expires')

# Register the admin forms.
admin.site.register(Course, CourseAdmin)
admin.site.register(Sale, SaleAdmin)
admin.site.register(Offer, OfferAdmin)
admin.site.register(UserProfile, UserProfileAdmin)


text:
using System.Collections.Generic;
using System.Windows;
using MiniETL.ViewModels;

namespace MiniETL.Components
{
	public abstract class ComponentBase : DependencyObject
	{
		public DesignerItemViewModel Parent { get; private set; }

		public static readonly DependencyProperty NameProperty = DependencyProperty.Register(
			"Name", typeof (string), typeof (ComponentBase), new PropertyMetadata(default(string)));

		public string Name
		{
			get { return (string) GetValue(NameProperty); }
			set { SetValue(NameProperty, value); }
		}

		public virtual void Init(DesignerItemViewModel parent)
		{
			Parent = parent;
		}

		public abstract List<FullyCreatedConnectorInfo> GetInputConnectors();
		public abstract List<FullyCreatedConnectorInfo> GetOutputConnectors();
	}
}


text:
package com.kylantraynor.civilizations.utils;

import org.json.simple.JSONObject;

public interface JSONSerializable {
    JSONObject toJSON();
    void load(JSONObject json);
}


text:
/*
 * Theoretically, directories can be more than 2Gb in length,
 * however, in practice this seems unlikely. So, we define
 * the type doff_t as a long to keep down the cost of doing
 * lookup on a 32-bit machine. If you are porting to a 64-bit
 * architecture, you should make doff_t the same as off_t.
 */
#define doff_t	long

typedef	struct	{
	struct timespec	iso_atime;	/* time of last access */
	struct timespec	iso_mtime;	/* time of last modification */
	struct timespec	iso_ctime;	/* time file changed */
	u_short		iso_mode;	/* files access mode and type */
	uid_t		iso_uid;	/* owner user id */
	gid_t		iso_gid;	/* owner group id */
	short		iso_links;	/* links of file */
	dev_t		iso_rdev;	/* Major/Minor number for special */
} ISO_RRIP_INODE;

struct iso_node {
	struct	vnode *i_vnode;	/* vnode associated with this inode */
	ino_t	i_number;	/* the identity of the inode */
				/* we use the actual starting block of the file */
	struct	iso_mnt *i_mnt;	/* filesystem associated with this inode */
	struct	lockf *i_lockf;	/* head of byte-level lock list */
	doff_t	i_endoff;	/* end of useful stuff in directory */
	doff_t	i_diroff;	/* offset in dir, where we found last entry */

	long iso_extent;	/* extent of file */
	unsigned long i_size;
	long iso_start;		/* actual start of data of file (may be different */
				/* from iso_extent, if file has extended attributes) */
	ISO_RRIP_INODE	inode;
};

#define	i_forw		i_chain[0]
#define	i_back		i_chain[1]

#define VTOI(vp) ((struct iso_node *)(vp)->v_data)
#define ITOV(ip) ((ip)->i_vnode)

#ifdef _KERNEL

#ifdef MALLOC_DECLARE
MALLOC_DECLARE(M_ISOFSMNT);
MALLOC_DECLARE(M_ISOFSNODE);
#endif

struct buf;
struct vop_bmap_args;
struct vop_cachedlookup_args;
struct vop_inactive_args;
struct vop_reclaim_args;

/*
 * Prototypes for ISOFS vnode operations
 */
int cd9660_lookup(struct vop_cachedlookup_args *);
int cd9660_inactive(struct vop_inactive_args *);
int cd9660_reclaim(struct vop_reclaim_args *);
int cd9660_bmap(struct vop_bmap_args *);
int cd9660_blkatoff(struct vnode *vp, off_t offset, char **res, struct buf **bpp);

void cd9660_defattr(struct iso_directory_record *,
			struct iso_node *, struct buf *, enum ISO_FTYPE);
void cd9660_deftstamp(struct iso_directory_record *,
			struct iso_node *, struct buf *, enum ISO_FTYPE);
int cd9660_tstamp_conv7(u_char *, struct timespec *, enum ISO_FTYPE);
int cd9660_tstamp_conv17(u_char *, struct timespec *);

#endif /* _KERNEL */


text:
import { createComponent } from 'react-fela'

const info = () => ({
  padding: 5,
  fontSize: '20px',
  color: 'gray',
  flexDirection: 'column'
})

export default createComponent(info)


text:
'use strict';

const expect = require('chai').expect;
const path = require('path');
const sinon = require('sinon');

describe('cli : facade : package', () => {

  const logSpy = {},
    Local = require('../../src/cli/domain/local'),
    local = new Local(),
    PackageFacade = require('../../src/cli/facade/package.js'),
    packageFacade = new PackageFacade({ local: local, logger: logSpy });

  const execute = function(compress, cb){
    logSpy.err = sinon.stub();
    logSpy.ok = sinon.stub();
    logSpy.warn = sinon.stub();
    packageFacade({
      componentPath: 'test/fixtures/components/hello-world/',
      compress: compress
    }, () => {
      cb();
    });
  };

  describe('before packaging a component', () => {

    it('should always show a message', (done) => {
      sinon.stub(local, 'package').yields('the component is not valid');
      execute(false, () => {
        local.package.restore();

        const message = logSpy.warn.args[0][0],
          re = new RegExp('\\' + path.sep, 'g'),
          messageWithSlashesOnPath = message.replace(re, '/');

        expect(messageWithSlashesOnPath).to.include('Packaging -> ');
        expect(messageWithSlashesOnPath).to.include('components/hello-world/_package');
        done();
      });
    });

    describe('when packaging', () => {

      describe('when a component is not valid', () => {

        beforeEach((done) => {
          sinon.stub(local, 'package').yields('the component is not valid');
          execute(false, done);
        });

        afterEach(() => {
          local.package.restore();
        });

        it('should show an error', () => {
          expect(logSpy.err.args[0][0]).to.equal('An error happened when creating the package: the component is not valid');
        });
      });

      describe('when a component is valid', () => {

        beforeEach(() => {
          sinon.stub(local, 'package').yields(null, {
            name: 'hello-world',
            version: '1.0.0'
          });
        });

        afterEach(() => {
          local.package.restore();
        });

        it('should package and show success message', (done) => {
          execute(false, () => {
            const warnMessage = logSpy.warn.args[0][0],
              okMessage = logSpy.ok.args[0][0],
              re = new RegExp('\\' + path.sep, 'g'),
              warnMessageWithSlashesOnPath = warnMessage.replace(re, '/'),
              okMessageWithSlashesOnPath = okMessage.replace(re, '/');

            expect(warnMessageWithSlashesOnPath).to.include('Packaging -> ');
            expect(warnMessageWithSlashesOnPath).to.include('components/hello-world/_package');

            expect(okMessageWithSlashesOnPath).to.include('Packaged -> ');
            expect(okMessageWithSlashesOnPath).to.include('components/hello-world/_package');
            done();
          });
        });

        describe('when creating tar.gz archive', () => {

          it('should not compress when option set to false', (done) => {
            sinon.stub(local, 'compress').yields(null);

            execute(false, () => {
              local.compress.restore();
              const warnMessage = logSpy.warn.args[0][0],
                okMessage = logSpy.ok.args[0][0],
                re = new RegExp('\\' + path.sep, 'g'),
                warnMessageWithSlashesOnPath = warnMessage.replace(re, '/'),
                okMessageWithSlashesOnPath = okMessage.replace(re, '/');

              expect(warnMessageWithSlashesOnPath).to.include('Packaging -> ');
              expect(okMessageWithSlashesOnPath).to.include('Packaged -> ');
              expect(logSpy.warn.args[1]).to.be.undefined;
              done();
            });
          });

          describe('when compression is successful', () => {
            beforeEach(() => {
              sinon.stub(local, 'compress').yields(null);
            });

            afterEach(() => {
              local.compress.restore();
            });

            it('should show a message for success', (done) => {
              execute(true, () => {
                const warnMessage = logSpy.warn.args[1][0],
                  okMessage = logSpy.ok.args[1][0],
                  re = new RegExp('\\' + path.sep, 'g'),
                  warnMessageWithSlashesOnPath = warnMessage.replace(re, '/'),
                  okMessageWithSlashesOnPath = okMessage.replace(re, '/');

                expect(warnMessageWithSlashesOnPath).to.include('Compressing -> ');
                expect(warnMessageWithSlashesOnPath).to.include('components/hello-world/package.tar.gz');
                expect(okMessageWithSlashesOnPath).to.include('Compressed -> ');
                expect(okMessageWithSlashesOnPath).to.include('components/hello-world/package.tar.gz');
                done();
              });
            });
          });

          describe('when compression fails', () => {

            beforeEach(() => {
              sinon.stub(local, 'compress').yields('error while compressing');
            });

            afterEach(() => {
              local.compress.restore();
            });

            it('should show a message for failure', (done) => {
              execute(true, () => {
                const warnMessage = logSpy.warn.args[1][0],
                  errorMessage = logSpy.err.args[0][0],
                  re = new RegExp('\\' + path.sep, 'g'),
                  warnMessageWithSlashesOnPath = warnMessage.replace(re, '/');

                expect(warnMessageWithSlashesOnPath).to.include('Compressing -> ');
                expect(warnMessageWithSlashesOnPath).to.include('components/hello-world/package.tar.gz');
                expect(errorMessage).to.equal('An error happened when creating the package: error while compressing');
                done();
              });
            });
          });
        });
      });
    });
  });
});


text:
const utils = require('../testing-utils.js');
const root = '../../';

jest.useFakeTimers();

describe('cloze', function(){

	beforeEach(function(){
		require(root + 'jspsych.js');
		require(root + 'plugins/jspsych-cloze');
	});

	test('loads correctly', function(){
		expect(typeof window.jsPsych.plugins['cloze']).not.toBe('undefined');
	});

	test('displays cloze', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
		}

		jsPsych.init({
			timeline: [trial]
		});

		expect(jsPsych.getDisplayElement().innerHTML).toMatch('
This is a <input type="text" id="input0" value=""> text.
');
	});

	test('displays default button text', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.'
		}

		jsPsych.init({
			timeline: [trial]
		});

		expect(jsPsych.getDisplayElement().innerHTML).toMatch(new RegExp('<button class="jspsych-html-button-response-button" type="button" id="finish_cloze_button">OK</button>'));
	});

	test('displays custom button text', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
			button_text: 'Next'
		}

		jsPsych.init({
			timeline: [trial]
		});

		expect(jsPsych.getDisplayElement().innerHTML).toMatch(new RegExp('<button class="jspsych-html-button-response-button" type="button" id="finish_cloze_button">Next</button>'));
	});

	test('ends trial on button click when using default settings, i.e. answers are not checked', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.'
		}

		jsPsych.init({
			timeline: [trial]
		});

		utils.clickTarget(document.querySelector('#finish_cloze_button'));
		expect(jsPsych.getDisplayElement().innerHTML).toBe('');
	});

	test('ends trial on button click when answers are checked and correct', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
			check_answers: true
		}

		jsPsych.init({
			timeline: [trial]
		});

		document.getElementById('input0').value = 'cloze';
		utils.clickTarget(document.querySelector('#finish_cloze_button'));
		expect(jsPsych.getDisplayElement().innerHTML).toBe('');
	});

	test('does not end trial on button click when answers are checked and not correct', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
			check_answers: true
		}

		jsPsych.init({
			timeline: [trial]
		});

		document.getElementById('input0').value = 'some wrong answer';
		utils.clickTarget(document.querySelector('#finish_cloze_button'));
		expect(jsPsych.getDisplayElement().innerHTML).not.toBe('');
	});

	test('does not call mistake function on button click when answers are checked and correct', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
			check_answers: true,
			mistake_fn: function(){called = true}
		}

		jsPsych.init({
			timeline: [trial]
		});

		var called = false;
		document.getElementById('input0').value = 'cloze';
		utils.clickTarget(document.querySelector('#finish_cloze_button'));
		expect(called).not.toBeTruthy();
	});

	test('calls mistake function on button click when answers are checked and not correct', function(){
		var trial = {
			type: 'cloze',
			text: 'This is a %cloze% text.',
			check_answers: true,
			mistake_fn: function(){called = true}
		}

		jsPsych.init({
			timeline: [trial]
		});

		var called = false;
		document.getElementById('input0').value = 'some wrong answer';
		utils.clickTarget(document.querySelector('#finish_cloze_button'));
		expect(called).toBeTruthy();
	});

});