text:
'''
This file contains parsers with no added help that can be inherited by
other parsers, as well as utility functions for parsing the input to
those parsers.
'''

from __future__ import print_function, unicode_literals, division, absolute_import

import argparse, json
from .. import config
from ..utils.printing import fill
from ..utils.pretty_print import format_table
from ..utils.resolver import split_unescaped
from ..utils.completer import InstanceTypesCompleter
from ..exceptions import (DXError, DXCLIError)
from ..compat import basestring

class DXParserError(DXError):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

all_arg = argparse.ArgumentParser(add_help=False)
all_arg.add_argument('-a', '--all', help=fill('Apply to all results with the same name without prompting', width_adjustment=-24), action='store_true')

no_color_arg = argparse.ArgumentParser(add_help=False)
no_color_arg.add_argument('--color',
                          help=fill('Set when color is used (color=auto is used when stdout is a TTY)', width_adjustment=-24),
                          choices=['off', 'on', 'auto'], default='auto')

delim_arg = argparse.ArgumentParser(add_help=False)
delim_arg.add_argument('--delimiter', '--delim',
                       dest='delimiter',
                       help=fill('Always use exactly one of DELIMITER to separate fields to be printed; if no delimiter is provided with this flag, TAB will be used', width_adjustment=-24),
                       nargs='?',
                       const="\t")

json_arg = argparse.ArgumentParser(add_help=False)
json_arg.add_argument('--json', help='Display return value in JSON', action='store_true')

stdout_args = argparse.ArgumentParser(add_help=False)
stdout_args_gp = stdout_args.add_mutually_exclusive_group()
stdout_args_gp.add_argument('--brief', help=fill('Display a brief version of the return value; for most commands, prints a DNAnexus ID per line', width_adjustment=-24), action='store_true')
stdout_args_gp.add_argument('--verbose', help='If available, displays extra verbose output',
                            action='store_true')

parser_dataobject_args = argparse.ArgumentParser(add_help=False)
parser_dataobject_args_gp = parser_dataobject_args.add_argument_group('metadata arguments')
parser_dataobject_args_gp.add_argument('--visibility', choices=['hidden', 'visible'], dest='hidden', default='visible', help='Whether the object is hidden or not')
parser_dataobject_args_gp.add_argument('--property', dest='properties', metavar='KEY=VALUE', help=fill('Key-value pair to add as a property; repeat as necessary,', width_adjustment=-24) + '\n' + fill('e.g. "--property key1=val1 --property key2=val2"', width_adjustment=-24, initial_indent=' ', subsequent_indent=' ', break_on_hyphens=False), action='append')
parser_dataobject_args_gp.add_argument('--type', metavar='TYPE', dest='types', help=fill('Type of the data object; repeat as necessary,', width_adjustment=-24) + '\n' + fill('e.g. "--type type1 --type type2"', width_adjustment=-24, break_on_hyphens=False, initial_indent=' ', subsequent_indent=' '), action='append')
parser_dataobject_args_gp.add_argument('--tag', metavar='TAG', dest='tags', help=fill('Tag of the data object; repeat as necessary,', width_adjustment=-24) + '\n' + fill('e.g. "--tag tag1 --tag tag2"', width_adjustment=-24, break_on_hyphens=False, initial_indent=' ', subsequent_indent=' '), action='append')
parser_dataobject_args_gp.add_argument('--details', help='JSON to store as details')
parser_dataobject_args_gp.add_argument('-p', '--parents', help='Create any parent folders necessary', action='store_true')

parser_single_dataobject_output_args = argparse.ArgumentParser(add_help=False)
parser_single_dataobject_output_args.add_argument('-o', '--output', help=argparse.SUPPRESS)
parser_single_dataobject_output_args.add_argument('path', help=fill('DNAnexus path for the new data object (default uses current project and folder if not provided)', width_adjustment=-24), nargs='?')

find_by_properties_and_tags_args = argparse.ArgumentParser(add_help=False)
find_by_properties_and_tags_args.add_argument('--property', dest='properties',
                                              metavar='KEY[=VALUE]',
                                              help=fill('Key-value pair of a property or simply a property key; if only a key is provided, matches a result that has the key with any value; repeat as necessary, e.g. "--property key1=val1 --property key2"', width_adjustment=-24),
                                              action='append')
find_by_properties_and_tags_args.add_argument('--tag',
                                              help=fill('Tag to match; repeat as necessary, e.g. "--tag tag1 --tag tag2" will require both tags', width_adjustment=-24),
                                              action='append')

find_executions_args = argparse.ArgumentParser()
find_executions_args.add_argument('--id', help=fill('Show only the job tree or job containing this job ID', width_adjustment=-24))
find_executions_args.add_argument('--name', help=fill('Restrict the search by job name (accepts wildcards "*" and "?")', width_adjustment=-24))
find_executions_args.add_argument('--user', help=fill('Username who launched the job (use "self" to ask for your own jobs)', width_adjustment=-24))
find_executions_args.add_argument('--project', help=fill('Project context (output project), default is current project if set', width_adjustment=-24))
find_executions_args.add_argument('--all-projects', '--allprojects', help=fill('Extend search to all projects', width_adjustment=-24), action='store_true')
find_executions_args.add_argument('--app', '--applet', '--executable', dest='executable', help=fill('Applet or App ID that job is running', width_adjustment=-24))
find_executions_args.add_argument('--state', help=fill('State of the job, e.g. \"done\", \"failed\"', width_adjustment=-24))
find_executions_args.add_argument('--origin', help=fill('Job ID of the top-level job', width_adjustment=-24)) # Redundant but might as well
find_executions_args.add_argument('--parent', help=fill('Job ID of the parent job; implies --all-jobs', width_adjustment=-24))
find_executions_args.add_argument('--created-after', help=fill('Date (e.g. 2012-01-01) or integer timestamp after which the job was last created (negative number means ms in the past, or use suffix s, m, h, d, w, M, y)', width_adjustment=-24))
find_executions_args.add_argument('--created-before', help=fill('Date (e.g. 2012-01-01) or integer timestamp before which the job was last created (negative number means ms in the past, or use suffix s, m, h, d, w, M, y)', width_adjustment=-24))
find_executions_args.add_argument('--no-subjobs', help=fill('Do not show any subjobs', width_adjustment=-24), action='store_true')
find_executions_args.add_argument('--root-execution', '--root', help=fill('Execution ID of the top-level (user-initiated) job or analysis', width_adjustment=-24))
find_executions_args.add_argument('-n', '--num-results', metavar='N', type=int, help=fill('Max number of results (trees or jobs, as according to the search mode) to return (default 10)', width_adjustment=-24), default=10)
find_executions_args.add_argument('-o', '--show-outputs', help=fill('Show job outputs in results', width_adjustment=-24), action='store_true')

def add_find_executions_search_gp(parser):
    find_executions_search_gp = parser.add_argument_group('Search mode')
    find_executions_search = find_executions_search_gp.add_mutually_exclusive_group()
    find_executions_search.add_argument('--trees', help=fill('Show entire job trees for all matching results (default)', width_adjustment=-24), action='store_true')
    find_executions_search.add_argument('--origin-jobs', help=fill('Search and display only top-level origin jobs', width_adjustment=-24), action='store_true')
    find_executions_search.add_argument('--all-jobs', help=fill('Search for jobs at all depths matching the query (no tree structure shown)', width_adjustment=-24), action='store_true')

def process_properties_args(args):
    # Properties
    properties = None
    if args.properties is not None:
        properties = {}
        for keyeqval in args.properties:
            substrings = split_unescaped('=', keyeqval, include_empty_strings=True)
            if len(substrings) != 2:
                raise DXParserError('Property key-value pair must be given using syntax "property_key=property_value"')
            elif substrings[0] == '':
                raise DXParserError('Property keys must be nonempty strings')
            else:
                properties[substrings[0]] = substrings[1]
    args.properties = properties

def process_find_by_property_args(args):
    properties = None
    if args.properties is not None:
        properties = {}
        for keyeqval in args.properties:
            substrings = split_unescaped('=', keyeqval, include_empty_strings=True)
            if len(substrings) > 2:
                raise DXParserError('Property value must be given using syntax "property_key" or "property_key=property_value"')
            elif substrings[0] == '':
                raise DXParserError('Property keys must be nonempty strings')
            elif len(substrings) == 1:
                properties[keyeqval] = True
            else:
                properties[substrings[0]] = substrings[1]

    args.properties = properties

def process_dataobject_args(args):
    process_properties_args(args)

    # Visibility
    args.hidden = (args.hidden == 'hidden')

    # Details
    if args.details is not None:
        try:
            args.details = json.loads(args.details)
        except:
            raise DXParserError('Error: details could not be parsed as JSON')

def process_single_dataobject_output_args(args):
    if args.path is not None and args.output is not None:
        raise DXParserError('Error: Cannot provide both the positional PATH and -o/--output arguments')
    elif args.output is None:
        args.output = args.path

_env_args = argparse.ArgumentParser(add_help=False, prog='dx command ...')
_env_args.add_argument('--apiserver-host', help='API server host')
_env_args.add_argument('--apiserver-port', help='API server port')
_env_args.add_argument('--apiserver-protocol', help='API server protocol (http or https)')
_env_args.add_argument('--project-context-id', help='Default project or project context ID')
_env_args.add_argument('--workspace-id', help='Workspace ID (for jobs only)')
_env_args.add_argument('--security-context', help='JSON string of security context')
_env_args.add_argument('--auth-token', help='Authentication token')

class EnvHelpAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        _env_args.print_help()
        parser.exit(0)

env_args = argparse.ArgumentParser(add_help=False)
env_args.add_argument('--apiserver-host', help=argparse.SUPPRESS)
env_args.add_argument('--apiserver-port', help=argparse.SUPPRESS)
env_args.add_argument('--apiserver-protocol', help=argparse.SUPPRESS)
env_args.add_argument('--project-context-id', help=argparse.SUPPRESS)
env_args.add_argument('--workspace-id', help=argparse.SUPPRESS)
env_args.add_argument('--security-context', help=argparse.SUPPRESS)
env_args.add_argument('--auth-token', help=argparse.SUPPRESS)
env_args.add_argument('--env-help', help=fill('Display help message for overriding environment variables', width_adjustment=-24), action=EnvHelpAction, nargs=0)

def set_env_from_args(args):
    ''' Sets the environment variables for this process from arguments (argparse.Namespace)
    and calls dxpy._initialize() to reset any values that it has already set.
    '''
    args = vars(args)

    if args.get('apiserver_host') is not None:
        config['DX_APISERVER_HOST'] = args['apiserver_host']
    if args.get('apiserver_port') is not None:
        config['DX_APISERVER_PORT'] = args['apiserver_port']
    if args.get('apiserver_protocol') is not None:
        config['DX_APISERVER_PROTOCOL'] = args['apiserver_protocol']
    if args.get('project_context_id') is not None:
        config['DX_PROJECT_CONTEXT_ID'] = args['project_context_id']
    if args.get('workspace_id') is not None:
        config['DX_WORKSPACE_ID'] = args['workspace_id']
    if args.get('cli_wd') is not None:
        config['DX_CLI_WD'] = args['cli_wd']
    if args.get('security_context') is not None:
        config['DX_SECURITY_CONTEXT'] = args['security_context']
    if args.get('auth_token') is not None:
        config['DX_SECURITY_CONTEXT'] = json.dumps({"auth_token": args['auth_token'],
                                                    "auth_token_type": "Bearer"})

extra_args = argparse.ArgumentParser(add_help=False)
extra_args.add_argument('--extra-args', help=fill("Arguments (in JSON format) to pass to the underlying API method, overriding the default settings", width_adjustment=-24))

def process_extra_args(args):
    if args.extra_args is not None:
        try:
            args.extra_args = json.loads(args.extra_args)
        except:
            raise DXParserError('Value given for --extra-args could not be parsed as JSON')

exec_input_args = argparse.ArgumentParser(add_help=False)
exec_input_args.add_argument('-i', '--input', help=fill('An input to be added using "<input name>[:<class>]=<input value>" (provide "class" if there is no input spec; it can be any job IO class, e.g. "string", "array:string", or "array"; if "class" is "array" or not specified, the value will be attempted to be parsed as JSON and is otherwise treated as a string)', width_adjustment=-24), action='append')
exec_input_args.add_argument('-j', '--input-json', help=fill('The full input JSON (keys=input field names, values=input field values)', width_adjustment=-24))
exec_input_args.add_argument('-f', '--input-json-file', dest='filename', help=fill('Load input JSON from FILENAME ("-" to use stdin)'))

class PrintInstanceTypeHelp(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print("Help: Specifying instance types for " + parser.prog)
        print()
        print(fill('A single instance type can be requested to be used by all entry points by providing the instance type name.  Different instance types can also be requested for different entry points of an app or applet by providing a JSON string mapping from function names to instance types, e.g.'))
        print()
        print('    {"main": "mem2_hdd2_x2", "other_function": "mem2_hdd2_x1"}')
        if parser.prog == 'dx run':
            print()
            print(fill('If running a workflow, different stages can have different instance type ' +
                       'requests by prepending the request with "<stage identifier>=" (where a ' +
                       'stage identifier is an ID, a numeric index, or a unique stage name) and ' +
                       'repeating the argument for as many stages as desired.  If no stage ' +
                       'identifier is provided, the value is applied as a default for all stages.'))
            print()
            print(fill('The following example runs all entry points of the first stage with ' +
                       'mem2_hdd2_x2, the stage named "BWA" with mem2_hdd2_x1, and all other ' +
                       'stages with mem2_hdd2_x4'))
            print()
            print('    Example: dx run workflow --instance-type 0=mem2_hdd2_x2 \\')
            print('               --instance-type BWA=mem2_hdd2_x1 --instance-type mem2_hdd2_x4')
        print()
        print('Available instance types:')
        print()
        print(format_table(InstanceTypesCompleter.instance_types.values(),
                           column_names=InstanceTypesCompleter.instance_types.values()[0]._fields))
        parser.exit(0)

instance_type_arg = argparse.ArgumentParser(add_help=False)
instance_type_arg.add_argument('--instance-type',
                               metavar='INSTANCE_TYPE_OR_MAPPING',
                               help=fill('Specify instance type(s) for jobs this executable will run; see --instance-type-help for more details', width_adjustment=-24),
                               action='append').completer = InstanceTypesCompleter()
instance_type_arg.add_argument('--instance-type-help',
                               nargs=0,
                               help=fill('Print help for specifying instance types'),
                               action=PrintInstanceTypeHelp)

property_args = argparse.ArgumentParser(add_help=False)
property_args.add_argument('--property', dest='properties', metavar='KEY=VALUE',
                           help=(fill('Key-value pair to add as a property; repeat as necessary,',
                                      width_adjustment=-24) + '\n' +
                                 fill('e.g. "--property key1=val1 --property key2=val2"',
                                      width_adjustment=-24, initial_indent=' ', subsequent_indent=' ',
                                      break_on_hyphens=False)),
                           action='append')

tag_args = argparse.ArgumentParser(add_help=False)
tag_args.add_argument('--tag', metavar='TAG', dest='tags',
                      help=fill('Tag for the resulting execution; repeat as necessary,', width_adjustment=-24) + '\n' +
                      fill('e.g. "--tag tag1 --tag tag2"', width_adjustment=-24,
                           break_on_hyphens=False, initial_indent=' ', subsequent_indent=' '),
                      action='append')

contains_phi = argparse.ArgumentParser(add_help=False)
contains_phi.add_argument('--phi', dest='containsPHI', choices=["true", "false"],
                          help='If set to true, only projects that contain PHI data will be retrieved. ' +
                          'If set to false, only projects that do not contain PHI data will be retrieved.')

def _parse_inst_type(thing):
    if thing.strip().startswith('{'):
        try:
            return json.loads(thing)
        except ValueError:
            raise DXCLIError("Error while parsing JSON value for --instance-type")
    else:
        return thing

def process_instance_type_arg(args, for_workflow=False):
    if args.instance_type:
        if for_workflow:
            args.stage_instance_types = {}
            new_inst_type_val = {}
            for inst_type_req in args.instance_type:
                if '=' in inst_type_req:
                    index_of_eql = inst_type_req.rfind('=')
                    args.stage_instance_types[inst_type_req[:index_of_eql]] = _parse_inst_type(
                        inst_type_req[index_of_eql + 1:]
                    )
                else:
                    new_inst_type_val = _parse_inst_type(inst_type_req)
            args.instance_type = new_inst_type_val
        elif not isinstance(args.instance_type, basestring):
            args.instance_type = _parse_inst_type(args.instance_type[-1])
        else:
            # is a string
            args.instance_type = _parse_inst_type(args.instance_type)

def get_update_project_args(args):
    input_params = {}
    if args.name is not None:
        input_params["name"] = args.name
    if args.summary is not None:
        input_params["summary"] = args.summary
    if args.description is not None:
        input_params["description"] = args.description
    if args.protected is not None:
        input_params["protected"] = True if args.protected == 'true' else False
    if args.restricted is not None:
        input_params["restricted"] = True if args.restricted == 'true' else False
    if args.containsPHI is not None:
        input_params["containsPHI"] = True if args.containsPHI == 'true' else False
    if args.bill_to is not None:
        input_params["billTo"] = args.bill_to
    return input_params

def process_phi_param(args):
    if args.containsPHI is not None:
        if args.containsPHI == "true":
            args.containsPHI = True
        elif args.containsPHI == "false":
            args.containsPHI = False


text:
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Twig_' => array($vendorDir . '/twig/twig/lib'),
    'Symfony\\Component\\Validator\\' => array($vendorDir . '/symfony/validator'),
    'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
    'Symfony\\Component\\Locale\\' => array($vendorDir . '/symfony/locale'),
    'Symfony\\Component\\Form\\' => array($vendorDir . '/symfony/form'),
    'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
    'Symfony\\Bridge\\Twig\\' => array($vendorDir . '/symfony/twig-bridge'),
    'Pimple' => array($vendorDir . '/pimple/pimple/lib'),
    'Doctrine\\DBAL\\' => array($vendorDir . '/doctrine/dbal/lib'),
    'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib'),
    'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
    'Doctrine\\Common\\Collections\\' => array($vendorDir . '/doctrine/collections/lib'),
    'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib'),
    'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib'),
    'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib'),
    '' => array($baseDir . '/src'),
);

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.databasemigrationservice.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteFleetAdvisorDatabasesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The IDs of the databases that the operation deleted.
     *

     */
    private java.util.List<String> databaseIds;

    /**
     *

     * The IDs of the databases that the operation deleted.
     *

     *
     * @return The IDs of the databases that the operation deleted.
     */

    public java.util.List<String> getDatabaseIds() {
        return databaseIds;
    }

    /**
     *

     * The IDs of the databases that the operation deleted.
     *

     *
     * @param databaseIds
     *        The IDs of the databases that the operation deleted.
     */

    public void setDatabaseIds(java.util.Collection<String> databaseIds) {
        if (databaseIds == null) {
            this.databaseIds = null;
            return;
        }

        this.databaseIds = new java.util.ArrayList<String>(databaseIds);
    }

    /**
     *

     * The IDs of the databases that the operation deleted.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setDatabaseIds(java.util.Collection)} or {@link #withDatabaseIds(java.util.Collection)} if you want to
     * override the existing values.
     *

     *
     * @param databaseIds
     *        The IDs of the databases that the operation deleted.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DeleteFleetAdvisorDatabasesResult withDatabaseIds(String... databaseIds) {
        if (this.databaseIds == null) {
            setDatabaseIds(new java.util.ArrayList<String>(databaseIds.length));
        }
        for (String ele : databaseIds) {
            this.databaseIds.add(ele);
        }
        return this;
    }

    /**
     *

     * The IDs of the databases that the operation deleted.
     *

     *
     * @param databaseIds
     *        The IDs of the databases that the operation deleted.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DeleteFleetAdvisorDatabasesResult withDatabaseIds(java.util.Collection<String> databaseIds) {
        setDatabaseIds(databaseIds);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDatabaseIds() != null)
            sb.append("DatabaseIds: ").append(getDatabaseIds());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DeleteFleetAdvisorDatabasesResult == false)
            return false;
        DeleteFleetAdvisorDatabasesResult other = (DeleteFleetAdvisorDatabasesResult) obj;
        if (other.getDatabaseIds() == null ^ this.getDatabaseIds() == null)
            return false;
        if (other.getDatabaseIds() != null && other.getDatabaseIds().equals(this.getDatabaseIds()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDatabaseIds() == null) ? 0 : getDatabaseIds().hashCode());
        return hashCode;
    }

    @Override
    public DeleteFleetAdvisorDatabasesResult clone() {
        try {
            return (DeleteFleetAdvisorDatabasesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
define(
  'tinymce.plugins.lists.core.TextBlock',
  [
    'tinymce.core.dom.DOMUtils',
    'tinymce.core.Env',
    'tinymce.plugins.lists.core.NodeType'
  ],
  function (DOMUtils, Env, NodeType) {
    var DOM = DOMUtils.DOM;

    var createNewTextBlock = function (editor, contentNode, blockName) {
      var node, textBlock, fragment = DOM.createFragment(), hasContentNode;
      var blockElements = editor.schema.getBlockElements();

      if (editor.settings.forced_root_block) {
        blockName = blockName || editor.settings.forced_root_block;
      }

      if (blockName) {
        textBlock = DOM.create(blockName);

        if (textBlock.tagName === editor.settings.forced_root_block) {
          DOM.setAttribs(textBlock, editor.settings.forced_root_block_attrs);
        }

        if (!NodeType.isBlock(contentNode.firstChild, blockElements)) {
          fragment.appendChild(textBlock);
        }
      }

      if (contentNode) {
        while ((node = contentNode.firstChild)) {
          var nodeName = node.nodeName;

          if (!hasContentNode && (nodeName !== 'SPAN' || node.getAttribute('data-mce-type') !== 'bookmark')) {
            hasContentNode = true;
          }

          if (NodeType.isBlock(node, blockElements)) {
            fragment.appendChild(node);
            textBlock = null;
          } else {
            if (blockName) {
              if (!textBlock) {
                textBlock = DOM.create(blockName);
                fragment.appendChild(textBlock);
              }

              textBlock.appendChild(node);
            } else {
              fragment.appendChild(node);
            }
          }
        }
      }

      if (!editor.settings.forced_root_block) {
        fragment.appendChild(DOM.create('br'));
      } else {
        // BR is needed in empty blocks on non IE browsers
        if (!hasContentNode && (!Env.ie || Env.ie > 10)) {
          textBlock.appendChild(DOM.create('br', { 'data-mce-bogus': '1' }));
        }
      }

      return fragment;
    };

    return {
      createNewTextBlock: createNewTextBlock
    };
  }
);


text:
import java.util.ArrayList;
import java.util.Collection;

public class ExtractVariableSample {

    public static void main(String[] args) {
        Collection<String> strings = new ArrayList<>();
        new Object() {
            public void foo(String s) {
                System.out.println( s.hashCode());
            }
        };

        for (String s : strings) {
            int j = s.hashCode();
            System.out.println(j);
        }
    }

}


text:
package org.apache.flink.table.functions;

import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.table.catalog.FunctionLanguage;
import org.apache.flink.table.functions.python.utils.PythonFunctionUtils;

/**
 * A util to instantiate {@link FunctionDefinition} in the default way.
 */
public class FunctionDefinitionUtil {

	public static FunctionDefinition createFunctionDefinition(String name, String className) {
		return createJavaFunctionDefinition(name, className);
	}

	public static FunctionDefinition createFunctionDefinition(
			String name,
			String className,
			FunctionLanguage functionLanguage,
			ReadableConfig config) {
		if (functionLanguage == FunctionLanguage.PYTHON) {
			return createFunctionDefinitionInternal(
				name,
				(UserDefinedFunction) PythonFunctionUtils.getPythonFunction(className, config));
		} else {
			return createJavaFunctionDefinition(name, className);
		}
	}

	private static FunctionDefinition createJavaFunctionDefinition(
			String name,
			String className) {
		Object func;
		try {
			func = Thread.currentThread().getContextClassLoader().loadClass(className).newInstance();
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			throw new IllegalStateException(
				String.format("Failed instantiating '%s'", className), e);
		}

		return createFunctionDefinitionInternal(name, (UserDefinedFunction) func);
	}

	private static FunctionDefinition createFunctionDefinitionInternal(String name, UserDefinedFunction udf) {
		if (udf instanceof ScalarFunction || udf instanceof TableFunction) {
			// table and scalar function use the new type inference
			// once the other functions have been updated, this entire class will not be necessary
			// anymore and can be replaced with UserDefinedFunctionHelper.instantiateFunction
			return udf;
		} else if (udf instanceof AggregateFunction) {
			AggregateFunction a = (AggregateFunction) udf;

			return new AggregateFunctionDefinition(
				name,
				a,
				UserDefinedFunctionHelper.getReturnTypeOfAggregateFunction(a),
				UserDefinedFunctionHelper.getAccumulatorTypeOfAggregateFunction(a)
			);
		} else if (udf instanceof TableAggregateFunction) {
			TableAggregateFunction a = (TableAggregateFunction) udf;

			return new TableAggregateFunctionDefinition(
				name,
				a,
				UserDefinedFunctionHelper.getReturnTypeOfAggregateFunction(a),
				UserDefinedFunctionHelper.getAccumulatorTypeOfAggregateFunction(a)
			);
		} else {
			throw new UnsupportedOperationException(
				String.format("Function %s should be of ScalarFunction, TableFunction, AggregateFunction, or "
					+ "TableAggregateFunction", udf.getClass().getName())
			);
		}
	}
}


text:
using System;
using System.Collections.Immutable;
using Abp.Dependency;

namespace Abp.ObjectComparators
{
    public abstract class ObjectComparatorBase : IObjectComparator, ITransientDependency
    {
        public abstract Type ObjectType { get; }

        public abstract ImmutableList<string> CompareTypes { get; }

        public abstract bool Compare(object baseObject, object compareObject, string compareType);

        public abstract bool CanCompare(Type baseObjectType, string compareType);
    }

    public abstract class ObjectComparatorBase<TBaseType> : ObjectComparatorBase
    {
        public sealed override Type ObjectType => typeof(TBaseType);

        private readonly bool _isNullable = false;

        protected ObjectComparatorBase()
        {
            _isNullable = IsNullableType(typeof(TBaseType));
        }

        protected abstract bool Compare(TBaseType baseObject, TBaseType compareObject, string compareType);

        public sealed override bool Compare(object baseObject, object compareObject, string compareType)
        {
            if (!_isNullable && (baseObject == null || compareObject == null))
            {
                throw new ArgumentNullException();
            }

            TBaseType baseObjTyped;
            TBaseType compareObjTyped;

            if (baseObject == null)
            {
                baseObjTyped = default;//which is null
            }
            else
            {
                baseObjTyped = (TBaseType)baseObject;
            }

            if (compareObject == null)
            {
                compareObjTyped = default;//which is null
            }
            else
            {
                compareObjTyped = (TBaseType)compareObject;
            }

            return Compare(baseObjTyped, compareObjTyped, compareType);
        }

        protected virtual bool CanCompare(string compareType)
        {
            return CompareTypes.Contains(compareType);
        }

        public sealed override bool CanCompare(Type baseObjectType, string compareType)
        {
            return _isNullable == IsNullableType(baseObjectType) && baseObjectType.IsAssignableFrom(typeof(TBaseType)) && CanCompare(compareType);
        }

        protected static bool IsNullableType(Type type)
        {
            if (type.IsGenericType)
            {
                return type.GetGenericTypeDefinition() == typeof(Nullable<>);
            }

            return type == typeof(string);
        }
    }

    public abstract class ObjectComparatorBase<TBaseType, TEnumCompareTypes> : ObjectComparatorBase<TBaseType>
        where TEnumCompareTypes : Enum
    {
        public override ImmutableList<string> CompareTypes { get; }

        protected ObjectComparatorBase()
        {
            CompareTypes = Enum.GetNames(typeof(TEnumCompareTypes)).ToImmutableList();
        }

        protected abstract bool Compare(TBaseType baseObject, TBaseType compareObject, TEnumCompareTypes compareType);

        protected sealed override bool Compare(TBaseType baseObject, TBaseType compareObject, string compareType)
        {
            var compareTypeEnum = (TEnumCompareTypes)Enum.Parse(typeof(TEnumCompareTypes), compareType);
            return Compare(baseObject, compareObject, compareTypeEnum);
        }
    }
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Functional;

use Oro\Bundle\ApiBundle\Request\ApiActions;
use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
use Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadataInterface;
use Oro\Bundle\SecurityBundle\Owner\Metadata\OwnershipMetadataProvider;

class RestJsonApiFormValidationTest extends RestJsonApiTestCase
{

    /** @var ConfigProvider */
    protected $configProvider;

    /** @var  OwnershipMetadataProvider */
    protected $metadataProvider;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        parent::setUp();

        $this->configProvider = $this->getContainer()->get('oro_entity_config.provider.ownership');
        $this->metadataProvider = $this->getContainer()->get('oro_security.owner.ownership_metadata_provider');
    }

    /**
     * @param string   $entityClass
     * @param string[] $excludedActions
     *
     * @dataProvider getEntities
     */
    public function testCreateRequests($entityClass, $excludedActions)
    {
        if (in_array(ApiActions::CREATE, $excludedActions, true)) {
            return;
        }

        $entityType = $this->getEntityType($entityClass);

        $response = $this->request(
            'POST',
            $this->getUrl('oro_rest_api_post', ['entity' => $entityType]),
            ['data' => ['type' => $entityType, 'attributes' => ['notExistingField' => null]]]
        );
        $this->assertApiResponseStatusCodeEquals($response, [400, 403, 405], $entityType, 'post');

        // Make sure Entity can be created without setting Owner or Organization
        // Owner and or Organization will be set from context for configurable entities
        if ($this->configProvider->hasConfig($entityClass)) {
            $content = json_decode($response->getContent(), true);
            if (isset($content['errors'])) {
                /** @var OwnershipMetadataInterface $classMetadata */
                $classMetadata = $this->metadataProvider->getMetadata($entityClass);
                foreach ($content['errors'] as $error) {
                    if (isset($error['source']['pointer'])) {
                        $this->assertNotEquals(
                            "/data/relationships/{$classMetadata->getOwnerFieldName()}/data",
                            $error['source']['pointer'],
                            "Entity {$entityClass} should not have '{$error['title']}' constraint for 'Owner'"
                        );
                        $this->assertNotEquals(
                            "/data/relationships/{$classMetadata->getGlobalOwnerFieldName()}/data",
                            $error['source']['pointer'],
                            "Entity {$entityClass} should not have '{$error['title']}' constraint for 'Organization'"
                        );
                    }
                }
            }
        }
    }

    /**
     * @param string   $entityClass
     * @param string[] $excludedActions
     *
     * @dataProvider getEntities
     */
    public function testUpdateRequests($entityClass, $excludedActions)
    {
        if (in_array(ApiActions::UPDATE, $excludedActions, true)) {
            return;
        }

        $entityType = $this->getEntityType($entityClass);

        $response = $this->request(
            'PATCH',
            $this->getUrl('oro_rest_api_patch', ['entity' => $entityType, 'id' => '1']),
            ['data' => ['type' => $entityType, 'id' => '1', 'attributes' => ['notExistingField' => null]]]
        );
        $this->assertApiResponseStatusCodeEquals($response, [400, 403, 405], $entityType, 'post');
    }
}


text:
<?php

namespace Vladimino\Geo\Service;

use Vladimino\Geo\Entity\Result;

/**
 * Class ResultFactory
 * Creates Result object from given components
 *
 * @package Vladimino\Geo\Service
 * @author vladimino
 */
class ResultFactory
{

    /**
     * Creates a new Result Entity object
     *
     * @param array $components
     * @return \Vladimino\Geo\Entity\Result
     */
    public static function make(array $components)
    {
        return new Result($components[0], $components[1], $components[2], $components[3], $components[4]);
    }
}


text:
using Backend.Constants;
using Commons.Models;
using Commons.Models.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Backend.Utils {
    public class LogUtils {

        public static void Info(string message) {
            CommandUtils.QueueCommand(new LogCommand() {
                Id = (int)Commands.OUT.WRITE_LOG,
                Log = new Log {
                    Message = message,
                    Level = LogLevel.INFO
                }
            });
        }

        public static void Warn(string message) {
            CommandUtils.QueueCommand(new LogCommand() {
                Id = (int)Commands.OUT.WRITE_LOG,
                Log = new Log {
                    Message = message,
                    Level = LogLevel.WARN
                }
            });
        }

        public static void Error(string message) {
            CommandUtils.QueueCommand(new LogCommand() {
                Id = (int)Commands.OUT.WRITE_LOG,
                Log = new Log {
                    Message = message,
                    Level = LogLevel.ERROR
                }
            });
        }

        public static void Error(string message, Exception e) {
            CommandUtils.QueueCommand(new LogCommand() {
                Id = (int)Commands.OUT.WRITE_LOG,
                Log = new Log {
                    Message = message,
                    Payload = e.ToString(),
                    Level = LogLevel.ERROR
                }
            });
        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
    /// Represents the state of compilation of one particular type.
    /// This includes, for example, a collection of synthesized methods created during lowering.
    /// </summary>
    /// <remarks>
    /// WARNING: Note that the collection class is not thread-safe and will
    /// need to be revised if emit phase is changed to support multithreading when
    /// translating a particular type.
    /// </remarks>
    internal sealed class TypeCompilationState
    {
        /// <summary> Synthesized method info </summary>
        internal struct MethodWithBody
        {
            public readonly MethodSymbol Method;
            public readonly BoundStatement Body;
            public readonly ImportChain ImportChainOpt;

            internal MethodWithBody(MethodSymbol method, BoundStatement body, ImportChain importChainOpt)
            {
                Debug.Assert(method != null);
                Debug.Assert(body != null);

                this.Method = method;
                this.Body = body;
                this.ImportChainOpt = importChainOpt;
            }
        }

        /// <summary> Flat array of created methods, non-empty if not-null </summary>
        private ArrayBuilder<MethodWithBody> _synthesizedMethods;

        /// <summary>
        /// Map of wrapper methods created for base access of base type virtual methods from
        /// other classes (like those created for lambdas...); actually each method symbol will
        /// only need one wrapper to call it non-virtually.
        /// </summary>
        private Dictionary<MethodSymbol, MethodSymbol> _wrappers;

        /// <summary>
        /// Type symbol being compiled, or null if we compile a synthesized type that doesn't have a symbol (e.g. PrivateImplementationDetails).
        /// </summary>
        private readonly NamedTypeSymbol _typeOpt;

        /// <summary>
        /// The builder for generating code, or null if not in emit phase.
        /// </summary>
        public readonly PEModuleBuilder ModuleBuilderOpt;

        /// <summary>
        /// Any generated methods that don't suppress debug info will use this
        /// list of debug imports.
        /// </summary>
        public ImportChain CurrentImportChain;

        public readonly CSharpCompilation Compilation;

        public LambdaFrame StaticLambdaFrame;

        /// <summary>
        /// A graph of method->method references for this(...) constructor initializers.
        /// Used to detect and report initializer cycles.
        /// </summary>
        private SmallDictionary<MethodSymbol, MethodSymbol> _constructorInitializers;

        public TypeCompilationState(NamedTypeSymbol typeOpt, CSharpCompilation compilation, PEModuleBuilder moduleBuilderOpt)
        {
            this.Compilation = compilation;
            _typeOpt = typeOpt;
            this.ModuleBuilderOpt = moduleBuilderOpt;
        }

        /// <summary>
        /// The type for which this compilation state is being used.
        /// </summary>
        public NamedTypeSymbol Type
        {
            get
            {
                // NOTE: currently it can be null if only private implementation type methods are compiled
                Debug.Assert((object)_typeOpt != null);
                return _typeOpt;
            }
        }

        /// <summary>
        /// The type passed to the runtime binder as context.
        /// </summary>
        public NamedTypeSymbol DynamicOperationContextType
        {
            get
            {
                var moduleBuilder = this.ModuleBuilderOpt;
                if (moduleBuilder == null)
                {
                    return null;
                }

                return moduleBuilder.DynamicOperationContextType ?? this.Type;
            }
        }

        public bool Emitting
        {
            get { return ModuleBuilderOpt != null; }
        }

        public ArrayBuilder<MethodWithBody> SynthesizedMethods
        {
            get { return _synthesizedMethods; }
            set
            {
                Debug.Assert(_synthesizedMethods == null);
                _synthesizedMethods = value;
            }
        }

        /// <summary>
        /// Add a 'regular' synthesized method.
        /// </summary>
        public void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
        {
            if (_synthesizedMethods == null)
            {
                _synthesizedMethods = ArrayBuilder<MethodWithBody>.GetInstance();
            }

            _synthesizedMethods.Add(new MethodWithBody(method, body, CurrentImportChain));
        }

        /// <summary>
        /// Add a 'wrapper' synthesized method and map it to the original one so it can be reused.
        /// </summary>
        /// <remarks>
        /// Wrapper methods are created for base access of base type virtual methods from
        /// other classes (like those created for lambdas...).
        /// </remarks>
        public void AddMethodWrapper(MethodSymbol method, MethodSymbol wrapper, BoundStatement body)
        {
            this.AddSynthesizedMethod(wrapper, body);

            if (_wrappers == null)
            {
                _wrappers = new Dictionary<MethodSymbol, MethodSymbol>();
            }

            _wrappers.Add(method, wrapper);
        }

        /// <summary> The index of the next wrapped method to be used </summary>
        public int NextWrapperMethodIndex
        {
            get { return _wrappers == null ? 0 : _wrappers.Count; }
        }

        /// <summary>
        /// Get a 'wrapper' method for the original one.
        /// </summary>
        /// <remarks>
        /// Wrapper methods are created for base access of base type virtual methods from
        /// other classes (like those created for lambdas...).
        /// </remarks>
        public MethodSymbol GetMethodWrapper(MethodSymbol method)
        {
            MethodSymbol wrapper = null;
            return _wrappers != null && _wrappers.TryGetValue(method, out wrapper) ? wrapper : null;
        }

        /// <summary> Free resources allocated for this method collection </summary>
        public void Free()
        {
            if (_synthesizedMethods != null)
            {
                _synthesizedMethods.Free();
                _synthesizedMethods = null;
            }

            _wrappers = null;
            _constructorInitializers = null;
        }

        /// <summary>
        /// Report an error if adding the edge (method1, method2) to the ctor-initializer
        /// graph would add a new cycle to that graph.
        /// </summary>
        /// <param name="method1">a calling ctor</param>
        /// <param name="method2">the chained-to ctor</param>
        /// <param name="syntax">where to report a cyclic error if needed</param>
        /// <param name="diagnostics">a diagnostic bag for receiving the diagnostic</param>
        internal void ReportCtorInitializerCycles(MethodSymbol method1, MethodSymbol method2, SyntaxNode syntax, DiagnosticBag diagnostics)
        {
            // precondition and postcondition: the graph _constructorInitializers is acyclic.
            // If adding the edge (method1, method2) would induce a cycle, we report an error
            // and do not add it to the set of edges. If it would not induce a cycle we add
            // it to the set of edges and return.

            if (method1 == method2)
            {
                // direct recursion is diagnosed elsewhere
                throw ExceptionUtilities.Unreachable;
            }

            if (_constructorInitializers == null)
            {
                _constructorInitializers = new SmallDictionary<MethodSymbol, MethodSymbol>();
                _constructorInitializers.Add(method1, method2);
                return;
            }

            MethodSymbol next = method2;
            while (true)
            {
                if (_constructorInitializers.TryGetValue(next, out next))
                {
                    Debug.Assert((object)next != null);
                    if (method1 == next)
                    {
                        // We found a (new) cycle containing the edge (method1, method2). Report an
                        // error and do not add the edge.
                        diagnostics.Add(ErrorCode.ERR_IndirectRecursiveConstructorCall, syntax.Location, method1);
                        return;
                    }
                }
                else
                {
                    // we've reached the end of the path without finding a cycle. Add the new edge.
                    _constructorInitializers.Add(method1, method2);
                    return;
                }
            }
        }
    }
}


text:
"""Contrail Security namespace package

Contrail Project

This is a setuptools namespace_package.  DO NOT place any other
code in this file!  There is no guarantee that it will be installed
with easy_install.  See:

http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages

... for details.
"""
__author__ = "P J Kershaw"
__date__ = "23/10/12"
__copyright__ = "(C) 2012 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "Philip.Kershaw@stfc.ac.uk"
__revision__ = '$Id$'
__import__('pkg_resources').declare_namespace(__name__)


text:
using System;

namespace Aranasoft.Cobweb.Data {
    /// <summary>
    ///     Base class for objects to be persisted in a relational database. Equates on reference or non-default identifier
    ///     value
    /// </summary>
    /// <typeparam name="TEntity">Derived entity type</typeparam>
    /// <typeparam name="TIdentifier">Itentifier-property type, such as Int32 or Guid</typeparam>
    public abstract class Entity<TEntity, TIdentifier> : IEntity<TEntity>
        where TEntity : Entity<TEntity, TIdentifier>, IEquatable<TEntity>
        where TIdentifier : IComparable, IComparable<TIdentifier>, IEquatable<TIdentifier> {
        public virtual TIdentifier Id { get; set; }

        public override int GetHashCode() {
            unchecked {
                return GetType().GetHashCode() * 29 * Id.GetHashCode();
            }
        }

        public virtual bool Equals(TEntity other) {
            if (ReferenceEquals(null, other)) {
                return false;
            }

            if (ReferenceEquals(this, other)) {
                return true;
            }

            if (Id == null || Id.Equals(default(TIdentifier))) {
                return false;
            }

            return Id.Equals(other.Id);
        }

        public override bool Equals(object obj) {
            var other = obj as TEntity;
            return other != null && Equals(other);
        }

        public static bool operator ==(Entity<TEntity, TIdentifier> entity1, Entity<TEntity, TIdentifier> entity2) {
            return Equals(entity1, null) ? Equals(entity2, null) : entity1.Equals(entity2);
        }

        public static bool operator !=(Entity<TEntity, TIdentifier> entity1, Entity<TEntity, TIdentifier> entity2) {
            return !(entity1 == entity2);
        }
    }
}


text:
class CreateProperties < ActiveRecord::Migration
  def change
    create_table :properties do |t|
      t.string :name, null: false
      t.string :colour
      t.integer :board_position, null: false
      t.integer :price, null: false
      t.integer :rent, null: false
      t.timestamps null: false
    end
  end
end


text:
* Download from the latest release from [here](https://github.com/cpragadeesh/codeforces-cli/releases).
* Unpack the file.
* Run the following command:

  `python setup.py install`

 *NOTE: You need to be root to do this. Switch to root or use sudo.*

## How to use:
1. Save your source file in the following format:

    >ContestIDProblemID.extension

    *Examples: 608a.cpp, 608b.cpp, 604b.py, 602.java*

    *NOTE: Contest ID is found in the URL of the problem. Contest ID is not same as Round Number.*

2. Testing your program:

    Run the following command:

      `cfcli -t <compiler> <path-to-file> [<compiler_options>]`

   *Example:*

      `cfcli -t g++ ~/Codes/608a.cpp -std=c++14`

Get more usage info by using the -h option

  `cfcli -h`


text:
CREATE TABLE `nodejsstructure`.`tbl_SubCategoryMasterBhavin` (
  `pk_subCategoryId` INT(11) NOT NULL  AUTO_INCREMENT,
  `subCategory` VARCHAR(100) NULL,
  `description` VARCHAR(256) NULL,
  `imageName` VARCHAR(256) NULL,
  `isActive` TINYINT(1) NULL DEFAULT 1,
  `createdDate` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `fk_createdBy` INT(11) NULL,
  `fk_categoryId` INT(11) NULL,
  PRIMARY KEY (`pk_subCategoryId`),
  INDEX `fk_categoryId_idx` (`fk_createdBy` ASC),
  INDEX `fk_createdBy_idx` (`fk_categoryId` ASC),
  CONSTRAINT `fk_categoryId`
    FOREIGN KEY (`fk_categoryId`)
    REFERENCES `nodejsstructure`.`tbl_CategoryMaster` (`pk_categoryID`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_createdBy`
    FOREIGN KEY (`fk_createdBy`)
    REFERENCES `nodejsstructure`.`tbl_UserMaster` (`pk_userID`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION);


text:
layout: default
title: EEE'17 - Important Dates
meta: The important deadlines for EEE
keyword: electrical engineering conference, electronics conference, power systems conference, automation conference, circuits conference, control system conference, wireless network conference, robotics conference, electrical engineering, electronics, power systems, automation, circuits, control system, wireless network, robotics
---

The important dates and deadlines for the 3rd International Conference on Electrical Engineering and Electronics (EEE'17) are as follows:

    Conference Dates

        June 4 - 6, 2017

    <s>Paper Submission Deadline</s>

        Final Extended Paper Submission Deadline

        <s>December 1, 2016</s>

            March 24, 2017

    <s>Notification of Authors</s>
Final Extended Notification of Authors

    <s>February 15, 2017</s>
March 27, 2017

    <s>Final Version of Accepted Submissions Deadline</s>
Final Version of Accepted Submissions Deadline

    <s>March 1, 2017</s>
April 20, 2017

    Registration Deadline

    <s>Early Bird Registration</s>

        Final Extended Early Bird Registration

<s>March 1, 2017</s>

        April 7, 2017

        <s>Regular Registration</s>

Final Extended Regular Registration*

<s>April 15, 2017</s>
May 1, 2017

        Late Registration
After May 1, 2017

    Conference Dates
    June 4 - 6, 2017

    <s>Paper Submission Deadline</s>

Final Extended Paper Submission Deadline

        <s>December 1, 2016</s>
March 24, 2017

    <s>Notification of Authors</s>

Final Extended Notification of Authors

    <s>February 15, 2017</s>
March 27, 2017

    <s>Final Version of Accepted Submissions Deadline</s>

Final Version of Accepted Submissions Deadline
    <s>March 1, 2017</s>
April 20, 2017

    Registration Deadline
    <s>Early Bird Registration</s>
Final Extended Early Bird Registration

<s>March 1, 2017</s>
April 7, 2017

    <s>Regular Registration</s>

Final Extended Regular Registration*

<s>April 15, 2017</s>
May 1, 2017

        Late Registration

After May 1, 2017

*This is the deadline for the registration of Authors


text:
using DiscordUnity.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Text;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Collections.Generic;
using DiscordUnity.API;
using DiscordUnity.State;

namespace DiscordUnity
{
    // Finish Http Calls
    // - Extra guild calls and some others
    // Finish Internal Models
    // - AuditLogChangeKey?
    // Finish State
    // - More and better states
    // - Fill in easy access methods to Http Calls

    public static partial class DiscordAPI
    {
        private static string url;
        private static string token;
        private static string session;
        private static bool acked = false;
        private static int sequence;

        private static Task listener;
        private static ClientWebSocket socket;

        public static bool IsActive { get; private set; }
        public static ILogger Logger { get; set; }

        internal static readonly JsonSerializer JsonSerializer;
        private static readonly JsonSerializerSettings JsonSettings;
        private static readonly SemaphoreSlim sendLock;
        private static TaskCompletionSource<bool> startTask;
        private static Queue<Action> callbacks;
        internal static CancellationTokenSource CancelSource;
        internal static DiscordInterfaces interfaces;

        static DiscordAPI()
        {
            Logger = new Logger();
            interfaces = new DiscordInterfaces();
            sendLock = new SemaphoreSlim(1, 1);
            callbacks = new Queue<Action>();

            JsonSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                }
            };

            JsonSerializer = JsonSerializer.CreateDefault(JsonSettings);
        }

        public static void RegisterEventsHandler(IDiscordInterface e)
            => interfaces.AddEventHandler(e);
        public static void UnregisterEventsHandler(IDiscordInterface e)
            => interfaces.RemoveEventHandler(e);
        internal static void Sync(Action callback)
            => callbacks.Enqueue(callback);

        /// <summary> Starts DiscordUnity with a bot token. </summary>
        /// <param name="botToken">A token received by creating a bot on Discord's developer portal.</param>
        public static async Task<bool> StartWithBot(string botToken)
        {
            if (IsActive) return false;

            if (string.IsNullOrWhiteSpace(botToken))
            {
                Logger.LogError("Token is invalid!");
                return false;
            }

            token = botToken;
            IsActive = true;
            InitializeState();
            CancelSource = new CancellationTokenSource();
            Client = new HttpClient();
            Client.DefaultRequestHeaders.Add("User-Agent", $"DiscordBot ({"https://github.com/DiscordUnity/DiscordUnity"}, {"1.0"})");
            Client.DefaultRequestHeaders.Add("Authorization", $"Bot {token}");

            var gatewayResult = await GetBotGateway();

            if (!gatewayResult)
            {
                IsActive = false;
                Logger.LogError("Retrieving gateway failed: " + gatewayResult.Exception);
                Stop();
                return false;
            }

            url = gatewayResult.Data.Url + "?v=6&encoding=json";
            Logger.Log("Gateway received: " + url);

            socket = new ClientWebSocket();
            await socket.ConnectAsync(new Uri(url), CancelSource.Token);

            if (socket.State != WebSocketState.Open)
            {
                IsActive = false;
                Logger.LogError("Could not connect with Discord: " + socket.CloseStatusDescription);
                Stop();
                return false;
            }

            Logger.Log("Connected.");
            listener = Listen();

            PayloadModel<IdentityModel> identity = new PayloadModel<IdentityModel>
            {
                Op = 2,
                Data = new IdentityModel
                {
                    Token = token,
                    Properties = new Dictionary<string,string>()
                    {
                        { "$os", Environment.OSVersion.ToString() },
                        { "$browser", "DiscordUnity" },
                        { "$device", "DiscordUnity" }
                    }
                }
            };

            startTask = new TaskCompletionSource<bool>();
            await Send(JsonConvert.SerializeObject(identity, JsonSettings));
            return await startTask.Task;
        }

        /// <summary> Stops DiscordUnity. </summary>
        public static void Stop()
        {
            if (startTask != null && !startTask.Task.IsCompleted)
                Sync(() => startTask.SetResult(false));

            startTask = null;
            IsActive = false;
            url = null;
            token = null;
            session = null;
            socket?.Dispose();
            socket = null;
            Client?.Dispose();
            Client = null;
            CancelSource?.Cancel();
            CancelSource = null;
            Logger.Log("DiscordUnity stopped.");
            interfaces.OnDiscordAPIClosed();
        }

        /// <summary> Updates DiscordUnity and hooks async calls back to calling thread. Without this, DiscordUnity will not function. </summary>
        public static void Update()
        {
            while (callbacks.Count > 0)
            {
                try
                {
                    callbacks.Dequeue()();
                }

                catch (Exception e)
                {
                    Logger.LogError("Error occured in a callback.", e);
                }
            }
        }

        private static async Task Resume()
        {
            listener.Dispose();
            await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Failed heartbeat ack", CancelSource.Token);
            await socket.ConnectAsync(new Uri(url), CancelSource.Token);
            listener = Listen();

            PayloadModel<ResumeModel> resume = new PayloadModel<ResumeModel>
            {
                Op = 6,
                Data = new ResumeModel
                {
                    Token = token,
                    SessionId = session,
                    Sequence = sequence
                }
            };

            await Send(JsonConvert.SerializeObject(resume, JsonSettings));
        }

        private static async Task Listen()
        {
            byte[] buffer = new byte[8192];

            while (IsActive && socket?.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancelSource.Token);

                if (!result.EndOfMessage)
                {
                    Logger.LogWarning("Received unexpected partial message.");
                    continue;
                }

                switch (result.MessageType)
                {
                    case WebSocketMessageType.Text:
                        await OnSocketMessage(Encoding.UTF8.GetString(buffer));
                        break;

                    case WebSocketMessageType.Close:
                        Logger.LogError($"Socket closed: ({socket.CloseStatus}) {socket.CloseStatusDescription}");
                        Stop();
                        return;

                    default:
                    case WebSocketMessageType.Binary:
                        Logger.LogWarning("Received unexpected type of message: " + result.MessageType);
                        break;
                }

                buffer = new byte[8192];
            }
        }

        private static async void Heartbeat(int interval)
        {
            while (IsActive && socket?.State == WebSocketState.Open)
            {
                if (acked)
                {
                    acked = false;

                    await Send(JsonConvert.SerializeObject(new PayloadModel<int>
                    {
                        Op = 1,
                        Data = sequence
                    }, JsonSettings));

                    Logger.Log("Heartbeat");
                    await Task.Delay(interval);
                }

                else
                {
                    await Resume();
                }
            }
        }

        private static async Task Send(string message)
        {
            Logger.Log("Send Message: " + message);
            var encoded = Encoding.UTF8.GetBytes(message);
            var buffer = new ArraySegment<byte>(encoded, 0, encoded.Length);

            await sendLock.WaitAsync();

            try
            {
                await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancelSource.Token);
            }

            finally
            {
                sendLock.Release();
            }
        }

        private static async Task OnSocketMessage(string json)
        {
            try
            {
                Logger.Log("Received Message: " + json);
                PayloadModel payload = JsonConvert.DeserializeObject<PayloadModel>(json, JsonSettings);

                if (payload.Sequence.HasValue)
                    sequence = payload.Sequence.Value;

                switch (payload.Op)
                {
                    case 0: // Event Dispatch
                        break;
                    case 1: // Heartbeat
                        await Send(JsonConvert.SerializeObject(new PayloadModel<int>
                        {
                            Op = 1,
                            Data = sequence
                        }, JsonSettings));

                        Logger.Log("Heartbeat");
                        break;
                    case 7: // Reconnect
                        Logger.Log("Reconnect Requested");
                        await Resume();
                        break;
                    case 9: // Invalid Session
                        Logger.LogError("Received invalid session from discord.");
                        var resume = payload.As<bool>().Data;
                        if (resume) await Resume();
                        else Stop();
                        break;
                    case 10: // Hello
                        acked = true;
                        var heartbeat = payload.As<HeartbeatModel>().Data;
                        Heartbeat(heartbeat.HeartbeatInterval);
                        break;
                    case 11: // Heartbeat Ack
                        Logger.Log("Heatbeat Ack");
                        acked = true;
                        break;
                }

                if (!string.IsNullOrEmpty(payload.Event))
                {
                    switch (payload.Event.ToLower())
                    {
                        // ------ API ------

                        case "ready":
                            {
                                Logger.Log("Ready.");

                                var ready = payload.As<ReadyModel>().Data;

                                Sync(() =>
                                {
                                    Version = ready.Version;
                                    session = ready.SessionId;
                                    User = new DiscordUser(ready.User);

                                    foreach (var channel in ready.PrivateChannels)
                                        PrivateChannels[channel.Id] = new DiscordChannel(channel);

                                    foreach (var guild in ready.Guilds)
                                        Servers[guild.Id] = new DiscordServer(guild);

                                    startTask.SetResult(true);
                                    interfaces.OnDiscordAPIOpen();
                                });
                            }
                            break;
                        case "resumed":
                            {
                                Logger.Log("Resumed.");
                                Sync(() => interfaces.OnDiscordAPIResumed());
                            }
                            break;
                        case "reonnect":
                            {
                                Logger.Log("Reconnect.");
                                await Resume();
                            }
                            break;

                        //  ------ Channels ------

                        case "channel_create":
                            {
                                var channel = payload.As<ChannelModel>().Data;

                                Sync(() =>
                                {
                                    if (!string.IsNullOrEmpty(channel.GuildId))
                                    {
                                        Servers[channel.GuildId].Channels[channel.Id] = new DiscordChannel(channel);
                                        interfaces.OnChannelCreated(Servers[channel.GuildId].Channels[channel.Id]);
                                    }

                                    else
                                    {
                                        PrivateChannels[channel.Id] = new DiscordChannel(channel);
                                        interfaces.OnChannelCreated(Servers[channel.GuildId].Channels[channel.Id]);
                                    }
                                });
                            }
                            break;
                        case "channel_update":
                            {
                                var channel = payload.As<ChannelModel>().Data;

                                Sync(() =>
                                {
                                    if (!string.IsNullOrEmpty(channel.GuildId))
                                    {
                                        Servers[channel.GuildId].Channels[channel.Id] = new DiscordChannel(channel);
                                        interfaces.OnChannelUpdated(Servers[channel.GuildId].Channels[channel.Id]);
                                    }

                                    else
                                    {
                                        PrivateChannels[channel.Id] = new DiscordChannel(channel);
                                        interfaces.OnChannelUpdated(Servers[channel.GuildId].Channels[channel.Id]);
                                    }
                                });
                            }
                            break;
                        case "channel_delete":
                            {
                                var channel = payload.As<ChannelModel>().Data;

                                Sync(() =>
                                {
                                    if (!string.IsNullOrEmpty(channel.GuildId))
                                    {
                                        interfaces.OnChannelDeleted(Servers[channel.GuildId].Channels[channel.Id]);
                                        Servers[channel.GuildId].Channels.Remove(channel.Id);
                                    }

                                    else
                                    {
                                        interfaces.OnChannelDeleted(Servers[channel.GuildId].Channels[channel.Id]);
                                        PrivateChannels.Remove(channel.Id);
                                    }
                                });
                            }
                            break;
                        case "channel_pins_update":
                            {
                                var channelPin = payload.As<ChannelPinsModel>().Data;

                                Sync(() =>
                                {
                                    if (!string.IsNullOrEmpty(channelPin.GuildId))
                                    {
                                        Servers[channelPin.GuildId].Channels[channelPin.ChannelId].LastPinTimestamp = channelPin.LastPinTimestamp;
                                        interfaces.OnChannelPinsUpdated(Servers[channelPin.GuildId].Channels[channelPin.ChannelId], channelPin.LastPinTimestamp);
                                    }

                                    else
                                    {
                                        PrivateChannels[channelPin.ChannelId].LastPinTimestamp = channelPin.LastPinTimestamp;
                                        interfaces.OnChannelPinsUpdated(Servers[channelPin.GuildId].Channels[channelPin.ChannelId], channelPin.LastPinTimestamp);
                                    }
                                });
                            }
                            break;

                        //  ------ Servers ------

                        case "guild_create":
                            {
                                var guild = payload.As<GuildModel>().Data;

                                Sync(() =>
                                {
                                    Servers[guild.Id] = new DiscordServer(guild);
                                    interfaces.OnServerJoined(Servers[guild.Id]);
                                });
                            }
                            break;
                        case "guild_update":
                            {
                                var guild = payload.As<GuildModel>().Data;

                                Sync(() =>
                                {
                                    Servers[guild.Id] = new DiscordServer(guild);
                                    interfaces.OnServerUpdated(Servers[guild.Id]);
                                });
                            }
                            break;
                        case "guild_delete":
                            {
                                var guild = payload.As<GuildModel>().Data;

                                Sync(() =>
                                {
                                    interfaces.OnServerLeft(Servers[guild.Id]);
                                    Servers.Remove(guild.Id);
                                });
                            }
                            break;
                        case "guild_ban_add":
                            {
                                var guildBan = payload.As<GuildBanModel>().Data;

                                Sync(() =>
                                {
                                    Servers[guildBan.GuildId].Bans[guildBan.User.Id] = new DiscordUser(guildBan.User);
                                    interfaces.OnServerBan(Servers[guildBan.GuildId], Servers[guildBan.GuildId].Bans[guildBan.User.Id]);
                                });
                            }
                            break;
                        case "guild_ban_remove":
                            {
                                var guildBan = payload.As<GuildBanModel>().Data;

                                Sync(() =>
                                {
                                    interfaces.OnServerUnban(Servers[guildBan.GuildId], Servers[guildBan.GuildId].Bans[guildBan.User.Id]);
                                    Servers[guildBan.GuildId].Bans.Remove(guildBan.User.Id);
                                });
                            }
                            break;
                        case "guild_emojis_update":
                            {
                                var guildEmojis = payload.As<GuildEmojisModel>().Data;
                                Servers[guildEmojis.GuildId].Emojis = guildEmojis.Emojis.ToDictionary(x => x.Id, x => new DiscordEmoji(x));
                            }
                            break;
                        case "guild_member_add":
                            {
                                var guildMember = payload.As<GuildMemberModel>().Data;
                                Servers[guildMember.GuildId].Members[guildMember.User.Id] = new DiscordServerMember(guildMember);
                            }
                            break;
                        case "guild_member_remove":
                            {
                                var guildMember = payload.As<GuildMemberModel>().Data;
                                Servers[guildMember.GuildId].Members.Remove(guildMember.User.Id);
                            }
                            break;
                        case "guild_member_update":
                            {
                                var guildMember = payload.As<GuildMemberModel>().Data;
                                Servers[guildMember.GuildId].Members[guildMember.User.Id] = new DiscordServerMember(guildMember);
                            }
                            break;
                        case "guild_members_chunk":
                            {
                                var guildMembersChunk = payload.As<GuildMembersChunkModel>().Data;
                            }
                            break;
                        case "guild_role_create":
                            {
                                var guildRole = payload.As<GuildRoleModel>().Data;
                                Servers[guildRole.GuildId].Roles[guildRole.Role.Id] = new DiscordRole(guildRole.Role);
                            }
                            break;
                        case "guild_role_update":
                            {
                                var guildRole = payload.As<GuildRoleModel>().Data;
                                Servers[guildRole.GuildId].Roles[guildRole.Role.Id] = new DiscordRole(guildRole.Role);
                            }
                            break;
                        case "guild_role_delete":
                            {
                                var guildRoleId = payload.As<GuildRoleIdModel>().Data;
                                Servers[guildRoleId.GuildId].Roles.Remove(guildRoleId.RoleId);
                            }
                            break;

                        //  ------ Invites ------

                        case "invite_create":
                            {
                                var invite = payload.As<InviteModel>().Data;
                                Servers[invite.GuildId].Invites[invite.Code] = new DiscordInvite(invite);
                            }
                            break;
                        case "invite_delete":
                            {
                                var invite = payload.As<InviteModel>().Data;
                                Servers[invite.GuildId].Invites.Remove(invite.Code);
                            }
                            break;

                        //  ------ Messages ------

                        case "message_create":
                            {
                                var message = payload.As<MessageModel>().Data;

                                Sync(() =>
                                {
                                    interfaces.OnMessageCreated(new DiscordMessage(message));
                                });
                            }
                            break;
                        case "message_update":
                            {
                                var message = payload.As<MessageModel>().Data;

                                Sync(() =>
                                {
                                    interfaces.OnMessageUpdated(new DiscordMessage(message));
                                });
                            }
                            break;
                        case "message_delete":
                            {
                                var message = payload.As<MessageModel>().Data;

                                Sync(() =>
                                {
                                    interfaces.OnMessageDeleted(new DiscordMessage(message));
                                });
                            }
                            break;
                        case "message_delete_bulk":
                            {
                                var messageBulk = payload.As<MessageBulkModel>().Data;
                            }
                            break;
                        case "message_reaction_add":
                            {
                                var messageReaction = payload.As<MessageReactionModel>().Data;
                            }
                            break;
                        case "message_reaction_remove":
                            {
                                var messageReaction = payload.As<MessageReactionModel>().Data;
                            }
                            break;
                        case "message_reaction_remove_all":
                            {
                                var messageReaction = payload.As<MessageReactionModel>().Data;
                            }
                            break;
                        case "message_reaction_remove_emoji":
                            {
                                var messageReaction = payload.As<MessageReactionModel>().Data;
                            }
                            break;

                        //  ------ Status ------

                        case "presence_update":
                            {
                                var presence = payload.As<PresenceModel>().Data;
                            }
                            break;

                        case "typing_start":
                            {
                                var typing = payload.As<TypingModel>().Data;
                            }
                            break;

                        case "user_update":
                            {
                                var user = payload.As<UserModel>().Data;
                            }
                            break;

                        //  ------ Voice ------

                        case "voice_state_update":
                            {
                                var voiceState = payload.As<VoiceStateModel>().Data;
                            }
                            break;
                        case "voice_server_update":
                            {
                                var voiceServer = payload.As<VoiceServerModel>().Data;
                            }
                            break;

                        //  ------ Webhooks ------

                        case "webhooks_update":
                            {
                                var webhook = payload.As<ServerWebhookModel>().Data;
                            }
                            break;
                    }
                }
            }

            catch (Exception exception)
            {
                Logger.LogError("Exception occured while processing message.", exception);
            }
        }
    }
}


text:
package org.aracrown.commons.security;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.apache.commons.codec.binary.Hex;

public class Hasher {
	private static final String PBKDF2_WITH_HMAC_SHA256 = "PBKDF2WithHmacSHA256";
	private static final String PBKDF2_WITH_HMAC_SHA512 = "PBKDF2WithHmacSHA512";

	private final String password;
	private final String passwordSalt;
	private final int hashIterations;

	public Hasher(String password) {
		this.password = password;
		this.passwordSalt = "DEFAULT";
		this.hashIterations = 1;
	}

	public Hasher(String password, String passwordSalt, int hashIterations) {
		this.password = password;
		this.passwordSalt = passwordSalt;
		this.hashIterations = hashIterations;
	}

	private String hash(String algorithm, int length) {
		PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), passwordSalt.getBytes(), hashIterations, 512);
		try {
			SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
			byte[] testHash = skf.generateSecret(spec).getEncoded();
			return Hex.encodeHexString(testHash);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
			throw new HasherException(String.format("Could not generate the requested hash: %s (Length: %d)", algorithm, length), e);
		}
	}

	public String hashSha512() {
		return hash(PBKDF2_WITH_HMAC_SHA512, 512);
	}

	public String hashSha256() {
		return hash(PBKDF2_WITH_HMAC_SHA256, 256);
	}
}


text:
package handlers

import (
	"github.com/index0h/go-tracker/app/generated"
	"github.com/index0h/go-tracker/modules/flash"
	"github.com/index0h/go-tracker/modules/flash/entity"
	"github.com/index0h/go-tracker/share"
)

type FlashHandler struct {
	flashManager *flash.Manager
	uuid         share.UUIDProviderInterface
}

func NewFlashHandler(flashManager *flash.Manager, uuid share.UUIDProviderInterface) *FlashHandler {
	return &FlashHandler{flashManager: flashManager, uuid: uuid}
}

func (handler *FlashHandler) FindFlashByID(flashID string) (*generated.Flash, error) {
	result, err := handler.flashManager.FindByID(handler.uuid.FromString(flashID))
	if err != nil {
		return nil, err
	}

	return handler.flashToThrift(result), nil
}

func (handler *FlashHandler) FindFlashAll(limit int64, offset int64) ([]*generated.Flash, error) {
	result, err := handler.flashManager.FindAll(limit, offset)
	if err != nil {
		return nil, err
	}

	return handler.listFlashToThrift(result), nil
}

func (handler *FlashHandler) FindFlashAllByVisitID(visitID string) ([]*generated.Flash, error) {
	result, err := handler.flashManager.FindAllByVisitID(handler.uuid.FromString(visitID))
	if err != nil {
		return nil, err
	}

	return handler.listFlashToThrift(result), nil
}

func (handler *FlashHandler) FindFlashAllByEventID(eventID string, limit, offset int64) ([]*generated.Flash, error) {
	result, err := handler.flashManager.FindAllByEventID(handler.uuid.FromString(eventID), limit, offset)
	if err != nil {
		return nil, err
	}

	return handler.listFlashToThrift(result), nil
}

func (handler *FlashHandler) flashToThrift(input *entity.Flash) *generated.Flash {
	if input == nil {
		return nil
	}

	return &generated.Flash{
		FlashID:     handler.uuid.ToString(input.FlashID()),
		VisitID:     handler.uuid.ToString(input.VisitID()),
		EventID:     handler.uuid.ToString(input.EventID()),
		Timestamp:   input.Timestamp(),
		VisitFields: input.VisitFields(),
		EventFields: input.EventFields(),
	}
}

func (handler *FlashHandler) listFlashToThrift(input []*entity.Flash) []*generated.Flash {
	if input == nil {
		return nil
	}

	result := make([]*generated.Flash, len(input))

	for i, value := range input {
		result[i] = handler.flashToThrift(value)
	}

	return result
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Math for kids</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">

    <link href="../bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />

    <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap-theme.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                </button>
                Math for kids

© Gefei 2017


text:
package scorex.lagonaki.unit

import org.scalatest.{Matchers, FunSuite}
import scorex.crypto.encode.Base58
import scorex.wallet.Wallet

import scala.util.Random

class WalletSpecification extends FunSuite with Matchers {

  private val walletSize = 10
  val w = new Wallet(None, "cookies", Base58.decode("FQgbSAm6swGbtqA3NE8PttijPhT4N3Ufh4bHFAkyVnQz").toOption)

  test("wallet - acc creation") {
    w.generateNewAccounts(walletSize)

    w.privateKeyAccounts().size shouldBe walletSize
    w.privateKeyAccounts().map(_.address) shouldBe Seq("3MqMwwHW4v2nSEDHVWoh8RCQL8QrsWLkkeB", "3MuwVgJA8EXHukxo6rcakT5tD6FpvACtitG", "3MuAvUG4EAsG9RP9jaWjewCVmggaQD2t39B", "3MqoX4A3UGBYU7cX2JPs6BCzntNC8K8FBR4", "3N1Q9VVVQtY3GqhwHtJDEyHb3oWBcerZL8X", "3NARifVFHthMDnCwBacXijPB2szAgNTeBCz", "3N6dsnfD88j5yKgpnEavaaJDzAVSRBRVbMY", "3MufvXKZxLuNn5SHcEgGc2Vo7nLWnKVskfJ", "3Myt4tocZmj7o3d1gnuWRrnQWcoxvx5G7Ac", "3N3keodUiS8WLEw9W4BKDNxgNdUpwSnpb3K")

  }

  test("wallet - acc deletion") {

    val head = w.privateKeyAccounts().head
    w.deleteAccount(head)
    assert(w.privateKeyAccounts().size == walletSize - 1)

    w.deleteAccount(w.privateKeyAccounts().head)
    assert(w.privateKeyAccounts().size == walletSize - 2)

    w.privateKeyAccounts().foreach(w.deleteAccount)

    assert(w.privateKeyAccounts().isEmpty)
  }

  test("reopening") {

    //todo read folder from settings
    val walletFile = new java.io.File(s"/tmp/wallet${Random.nextLong()}.dat")

    val w = new Wallet(Some(walletFile), "cookies", Base58.decode("FQgbSAm6swGbtqA3NE8PttijPhT4N3Ufh4bHFAkyVnQz").toOption)
    w.generateNewAccounts(10)
    val nonce = w.nonce()
    w.close()
    assert(w.exists())

    val w2 = new Wallet(Some(walletFile), "cookies", None)
    w2.privateKeyAccounts().head.address should not be null
    w2.nonce() shouldBe nonce
  }
}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="compass" type="js.build_tools.grunt" factoryName="Grunt.js" singleton="false">
    <gruntfile value="$PROJECT_DIR$/Gruntfile.js" />
    <tasks>
      <task value="compass" />
    </tasks>
    <pass-parent-env-vars value="true" />
    <force value="false" />
    <verbose value="true" />
    <envs />
    <method />
  </configuration>
</component>


text:
package org.codehaus.groovy.runtime.metaclass;

/**
 * A stack less exception used to indicate, that the execution of a missingMethod
 * method failed with a MissingMethodException. This is used to prevent a call to
 * invokeMethod for GroovyObject implementing classes.
 */
public class MissingMethodExecutionFailed extends MissingMethodExceptionNoStack {
    private static final long serialVersionUID = -7894095278952483769L;
    private Throwable cause;
    public MissingMethodExecutionFailed(String method, Class type, Object[] arguments, boolean isStatic, Throwable cause) {
        super(method, type, arguments, isStatic);
        this.cause = cause;
    }

    @Override
    public Throwable getCause() {
        return cause;
    }
}


text:
<?php

use Consolidare\RecordFields\RecordField;
use Consolidare\Record\BlankRecord;
use Consolidare\Record\Exception\CantRevertBackFurtherException;
use Consolidare\Record\Exception\PropertyDoesNotExistException;
use Consolidare\Record\Records;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophet;

class BlankRecordTest extends TestCase
{
    public function testItImplementsRecordsInterface()
    {
        $this->assertTrue(in_array(
            Records::class,
            class_implements(new BlankRecord)
        ));
    }

    public function testRetrieveReturnsBlankArray()
    {
        $this->assertEquals(
            [],
            (new BlankRecord)->retrieve()
        );
    }

    public function testPropertyThrowsException()
    {
        $this->setExpectedException(PropertyDoesNotExistException::class);

        $prophet = new Prophet;
        $record = $prophet->prophesize(RecordField::class);
        $record->name()->willReturn('foo');

        (new BlankRecord)->field($record->reveal());
    }

    public function testRevertThrowsException()
    {
        $this->setExpectedException(CantRevertBackFurtherException::class);
        (new BlankRecord)->revert();
    }
}


text:
jsviews.com
===========

Web site for www.jsviews.com - with documentation and samples for JsViews, JsRender and JsObservable

Work in progress


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) JMTabBarController *tabBarVC;

@end


text:
class BasicTest {
public:
    BasicTest() {}
    virtual void initialize() {}
    virtual void describe() {}
    virtual bool run() = 0;
    virtual void finalize() {}
    virtual ~BasicTest() {}
};

class Tester {
private:
    std::vector<BasicTest*> tests;
public:
    Tester() {}
    void add(BasicTest* test);
    void run_all_tests();
};

#endif //LAB_2_TESTLIB_H


text:
let _ = require('ramda');
let $ = require('jquery');
let Right = require('./functor_either').Right;
let Left = require('./functor_either').Left;
let Container = require('./functor_container').Container;
let Maybe = require('./functor_maybe').Maybe;
let curry = _.curry;
let compose = _.compose;
let print = console.log;
let Task = require('data.task');
//npm install --save-dev data.task

var fs  = require('fs');
var readFile = function(filename){
    return new Task(function(reject,result){
        fs.readFile(filename,'utf-8',function(err,data){
             err?reject(err):result(data);
        })
    });
}
var l = readFile('./README.md').map(_.split('\n')).map(_.head).map(function(x){return x+'\t o(* ̄▽ ̄*)o'});
l.fork(
    function(err){
    throw err;
    },
    function(data){
        console.log(data);
    }
);
// # learn-js-webpack    o(* ̄▽ ̄*)o

var getJSON = curry(function(url,param){
    return new Task(function(reject,result){
        $.getJSON(url,param,result).fail(reject);
    })
});

var l = getJSON('/photo', { name: 'dogs' }).map(_.head).map(_.prop('title'));

var l = Task.of(3).map(function(three){
    return three +1;
});
// Task(4)
var taskPrint = function(task){
    task.fork(function (err) {
        throw err;
    }, function (data) {
        console.log(data);
    });
}

var Handlebars = function(){
        // 由于没有完整代码实例,这是模仿一下 了解原理即可
}
Handlebars.compile = function(){}
Postgres = function(){}
var blogTemplate = function(){}

// Pure Application
// blogPage :: Posts -> HTML
var blogPage = Handlebars.compile(blogTemplate);

var renderPage = compose(blogPage,_.sortBy('date'));

var blog = compose(_.map(renderPage),getJSON('/posts'));
//call Pure
//blog({}).fork(function(err){},function(data){});

var dbUrl = function(c){c.host+'5432/'+c.db
    return (c.uname&& c.pass && c.host && c.db)
    ?Right.of('db:pg://'+c.uname+':'+c.pass+'@'+c.host+'5432/'+c.db)
    :Left.of(Error('Invalid config'));
}

// connectDb :: Config -> Either Error
var connectDb = compose(_.map(Postgres.connect),dbUrl);

// getConfig :: Filename -> Task Error
var getConfig = compose(_.map(compose(connectDb,JSON.parse)),readFile);

//getConfig('db.json').fork(logError('cound"t read file'),either(console.log,map(runQuery)))

//taskPrint(l);

// 理论

var id = function(x){
    return x;
}
var f = function(){}
var g = function(){}

// Identity
_.map(id) == id;
// Composition
compose(_.map(f), _.map(g)) == _.map(compose(f,g));

(_.map(id)(Container.of(3)) == id(Container.of(3)));
// 这个 _map 跟 ramda 的 _.map 区别 在于 _map 针对容器处理
var _map = curry(function(f,container){
    return container.map(f);
});
// 但是 在这个定理条件下 两个_map 和 map 方法 都是完全适用的
var compLaw1 = compose(_map(_.concat('world')),_map(_.concat(' crul ')));
var compLaw2 = _map(compose(_.concat('world'), _.concat(' crul ')));

var l = compLaw1(Container.of('GoodBye'));
var ll = compLaw2(Container.of('GoodBye'));
print(l);
print(ll);

var topRoute1 = compose(Maybe.of,_.reverse);
var topRoute2 = compose(_map(_.reverse),Maybe.of); // 这里居然也可以将 _map 跟 _.map 替换 不可思议

print(topRoute1('hi'));
print(topRoute2('hi'));

var Compose =  function(f_g_x){
    this.getCompose = f_g_x;
}
Compose.prototype.map = function(f){
    return new Compose(_.map(_.map(f),this.getCompose));
}
var tmd = Task.of(Maybe.of('Rock over  London,'));

var ctmd = new Compose(tmd);

var l  = _.map(_.concat(',rock on , Chicago '),ctmd);

taskPrint(l.getCompose);