text:
function vmag = compute_mag(vec, n, nt)
% Compute vector magnitude per frame for each entry in the sample.
% Input:
%   vec = [nt x 3 x n] matrix with the vectors in the sample.
%   n = number of vectors in the sample.
%   nt = maximum number of time points available.
% Output:
%   vmag = [nt x n] matrix with the vector magnitude per frame.
%
% Author: A. Luchici, 2015

% Initialize output
vmag = zeros(nt, n);

% Compute magnitude of each vector in the sample at each available
% timepoint.
for i = 1:n
    for k = 1:nt
        vmag(k,i) = norm(vec(k,:,i));
    end
end


text:
package org.lilyproject.indexer.model.indexerconf;

import java.io.IOException;

import org.lilyproject.repository.api.RepositoryException;

public interface FollowCallback {
    public void call() throws RepositoryException, IOException, InterruptedException;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once('../Config/DBConnection.php');

//enable cross origin resources sharing (CORS)
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

//create a user follow user relation

$getUser = htmlspecialchars($_GET['userID']);
$getDislikeInterest = strtoupper(htmlspecialchars($_GET['interest']));

$queryString = "Match (a:Person),(b:Interest) WHERE a.userID = '" . $getUser . "' AND b.interest = '" . $getDislikeInterest . "' CREATE UNIQUE (a)-[r:Dislikes { name : a.userID + '<->' + b.interest }]->(b) RETURN r";

$client->sendCypherQuery($queryString);

$result = $client->getRows();

header("Content-type: application/json");

$JSON_RETURN = json_encode($result);

echo $JSON_RETURN;
?>


text:
from google.cloud import aiplatform_v1

async def sample_delete_model_deployment_monitoring_job():
    # Create a client
    client = aiplatform_v1.JobServiceAsyncClient()

    # Initialize request argument(s)
    request = aiplatform_v1.DeleteModelDeploymentMonitoringJobRequest(
        name="name_value",
    )

    # Make the request
    operation = client.delete_model_deployment_monitoring_job(request=request)

    print("Waiting for operation to complete...")

    response = await operation.result()

    # Handle the response
    print(response)

# [END aiplatform_v1_generated_JobService_DeleteModelDeploymentMonitoringJob_async]


text:
require "subscribem/constraints/subdomain_required"

Subscribem::Engine.routes.draw do
  constraints(Subscribem::Constraints::SubdomainRequired) do
    scope :module => "account" do
      root :to => "dashboard#index", :as => :account_root
    end
  end

  root 'dashboard#index'

  get "/sign_up", :to => "accounts#new", :as => :sign_up
  post "/accounts", :to => "accounts#create", :as => :accounts
end


text:
'use strict';

var Q = require( 'q' );
var utils = require( '../lib/utils' );
var transformer = require( 'enketo-transformer' );
var prefix = 'ca:';
var expiry = 30 * 24 * 60 * 60;
var config = require( './config-model' ).server;
var client = require( 'redis' ).createClient( config.redis.cache.port, config.redis.cache.host, {
    auth_pass: config.redis.cache.password
} );
var debug = require( 'debug' )( 'cache-model' );

// in test environment, switch to different db
if ( process.env.NODE_ENV === 'test' ) {
    client.select( 15 );
}

/**
 * Gets an item from the cache.
 *
 * @param  {{openRosaServer: string, openRosaId: string }} survey [description]
 * @return {[type]}        [description]
 */
function getSurvey( survey ) {
    var key, error,
        deferred = Q.defer();

    if ( !survey || !survey.openRosaServer || !survey.openRosaId ) {
        error = new Error( 'Bad Request. Survey information to perform cache lookup is not complete.' );
        error.status = 400;
        deferred.reject( error );
    } else {
        key = _getKey( survey );

        client.hgetall( key, function( error, cacheObj ) {
            if ( error ) {
                deferred.reject( error );
            } else if ( !cacheObj ) {
                deferred.resolve( null );
            } else {
                // form is 'actively used' so we're resetting the cache expiry
                debug( 'cache is up to date and used, resetting expiry' );
                client.expire( key, expiry );
                survey.form = cacheObj.form;
                survey.model = cacheObj.model;
                survey.formHash = cacheObj.formHash;
                survey.mediaHash = cacheObj.mediaHash;
                survey.xslHash = cacheObj.xslHash;
                deferred.resolve( survey );
            }
        } );
    }

    return deferred.promise;
}

/**
 * Gets the hashes of an item from the cache.
 *
 * @param  {{openRosaServer: string, openRosaId: string }} survey [description]
 * @return {[type]}        [description]
 */
function getSurveyHashes( survey ) {
    var key, error,
        deferred = Q.defer();

    if ( !survey || !survey.openRosaServer || !survey.openRosaId ) {
        error = new Error( 'Bad Request. Survey information to perform cache lookup is not complete.' );
        error.status = 400;
        deferred.reject( error );
    } else {
        key = _getKey( survey );

        client.hmget( key, [ 'formHash', 'mediaHash', 'xslHash' ], function( error, hashArr ) {
            if ( error ) {
                deferred.reject( error );
            } else if ( !hashArr ) {
                deferred.resolve( null );
            } else {
                deferred.resolve( {
                    formHash: hashArr[ 0 ],
                    mediaHash: hashArr[ 1 ],
                    xslHash: hashArr[ 2 ]
                } );
            }
        } );
    }

    return deferred.promise;
}

/**
 * Checks if cache is present and up to date
 *
 * @param  {{openRosaServer: string, openRosaId: string, info: {hash: string }}} survey [description]
 * @return {Boolean}        [description]
 */
function isCacheUpToDate( survey ) {
    var key, error,
        deferred = Q.defer();

    if ( !survey || !survey.openRosaServer || !survey.openRosaId || !survey.info.hash ) {
        error = new Error( 'Bad Request. Survey information to perform cache check is not complete.' );
        error.status = 400;
        deferred.reject( error );
    } else {
        // clean up the survey object to make sure no artefacts of cached survey are present
        survey = {
            openRosaServer: survey.openRosaServer,
            openRosaId: survey.openRosaId,
            info: {
                hash: survey.info.hash
            },
            manifest: survey.manifest
        };

        key = _getKey( survey );

        client.hgetall( key, function( error, cacheObj ) {
            if ( error ) {
                deferred.reject( error );
            } else if ( !cacheObj ) {
                debug( 'cache is missing' );
                deferred.resolve( null );
            } else {
                // Adding the hashes to the referenced survey object can be efficient, since this object
                // is passed around. The hashes may therefore already have been calculated
                // when setting the cache later on.
                // mediaHash can be "null" in Redis and null in reality so it is cast to a string
                _addHashes( survey );
                if ( cacheObj.formHash !== survey.formHash || cacheObj.mediaHash !== String( survey.mediaHash ) || cacheObj.xslHash !== survey.xslHash ) {
                    debug( 'cache is obsolete' );
                    deferred.resolve( false );
                } else {
                    deferred.resolve( true );
                }
            }
        } );
    }

    return deferred.promise;
}

/**
 * Adds an item to the cache
 *
 * @param {[type]} survey [description]
 */
function setSurvey( survey ) {
    var obj, key, error,
        deferred = Q.defer();

    if ( !survey || !survey.openRosaServer || !survey.openRosaId || !survey.info.hash || !survey.form || !survey.model ) {
        error = new Error( 'Bad Request. Survey information to cache is not complete.' );
        error.status = 400;
        deferred.reject( error );
    } else {
        _addHashes( survey );
        obj = {
            formHash: survey.formHash,
            mediaHash: survey.mediaHash,
            xslHash: survey.xslHash,
            form: survey.form,
            model: survey.model
        };

        key = _getKey( survey );

        client.hmset( key, obj, function( error ) {
            if ( error ) {
                deferred.reject( error );
            } else {
                debug( 'cache has been updated' );
                // expire in 30 days
                client.expire( key, expiry );
                deferred.resolve( survey );
            }
        } );
    }

    return deferred.promise;
}

/**
 * Flushes the cache of a single survey
 *
 * @param {[type]} survey [description]
 */
function flushSurvey( survey ) {
    var obj, key, error,
        deferred = Q.defer();

    if ( !survey || !survey.openRosaServer || !survey.openRosaId ) {
        error = new Error( 'Bad Request. Survey information to cache is not complete.' );
        error.status = 400;
        deferred.reject( error );
    } else {
        key = _getKey( survey );
        client.del( key, function( error ) {
            if ( error ) {
                deferred.reject( error );
            } else {
                delete survey.form;
                delete survey.model;
                delete survey.formHash;
                delete survey.xlsHash;
                delete survey.mediaHash;
                deferred.resolve( survey );
            }
        } );

        return deferred.promise;
    }
}

/**
 * Completely empties the cache
 * @return {[type]} [description]
 */
function flushAll() {
    var deferred = Q.defer();

    client.keys( prefix + '*', function( error, keys ) {
        if ( error ) {
            deferred.reject( error );
        }
        keys.forEach( function( key ) {
            client.del( key, function( error ) {
                if ( error ) {
                    deferred.reject( error );
                } else {
                    deferred.resolve();
                }
            } );
        } );

        deferred.resolve( true );
    } );

    return deferred.promise;
}

/**
 * Gets the key used for the cache item
 * @param  {{openRosaServer: string, openRosaId: string}} survey [description]
 * @return {string}        [description]
 */
function _getKey( survey ) {
    var openRosaKey = utils.getOpenRosaKey( survey, prefix );
    return ( openRosaKey ) ? openRosaKey : null;
}

/**
 * Adds the 3 relevant hashes to the survey object if they haven't been added already.
 * @param {[type]} survey [description]
 */
function _addHashes( survey ) {
    survey.formHash = survey.formHash || survey.info.hash;
    survey.mediaHash = survey.mediaHash || ( ( survey.manifest && survey.manifest.length > 0 ) ? utils.md5( JSON.stringify( survey.manifest ) ) : null );
    survey.xslHash = survey.xslHash || transformer.version;
}

module.exports = {
    get: getSurvey,
    getHashes: getSurveyHashes,
    set: setSurvey,
    check: isCacheUpToDate,
    flush: flushSurvey,
    flushAll: flushAll
};


text:
"""Converter from ProofLog proto to a tf Example."""

from __future__ import absolute_import
from __future__ import division
# Import Type Annotations
from __future__ import print_function
import tensorflow as tf
from tf import logging
from typing import Dict, Iterable, List, Optional, Text, Tuple
from deepmath.deephol import deephol_pb2
from deepmath.deephol import io_util
from deepmath.deephol import theorem_fingerprint as fp
from deepmath.deephol.deephol_loop import options_pb2
from deepmath.proof_assistant import proof_assistant_pb2

BYTES_FEATURE_ENCODING = 'utf-8'

class ProofLogToTFExample(object):
  """TFExampleFormat.HOLPARAM conversion to TFExamples."""

  def __init__(self, tactic_name_id_map: Dict[Text, int],
               theorem_database: proof_assistant_pb2.TheoremDatabase,
               options: options_pb2.ConvertorOptions):
    """Initializer.

    Arguments:
      tactic_name_id_map: mapping from tactic names to ids.
      theorem_database: database containing list of global theorems with splits
      options: options to control forbidden parameters and graph representations
    """
    if options.scrub_parameters not in [
        options_pb2.ConvertorOptions.NOTHING,
        options_pb2.ConvertorOptions.TESTING,
        options_pb2.ConvertorOptions.VALIDATION_AND_TESTING
    ]:
      raise ValueError('Unknown scrub_parameter.')

    self.tactic_name_id_map = tactic_name_id_map
    self.options = options

    self.fingerprint_conclusion_map = {
        fp.Fingerprint(theorem): theorem.conclusion
        for theorem in theorem_database.theorems
    }

    self.forbidden_parameters = set()
    for theorem in theorem_database.theorems:
      if (theorem.tag not in [
          proof_assistant_pb2.Theorem.DEFINITION,
          proof_assistant_pb2.Theorem.TYPE_DEFINITION
      ] and theorem.training_split == proof_assistant_pb2.Theorem.UNKNOWN):
        raise ValueError('need training split information in theorem database.')

      scrub_testsplit_parameters = options.scrub_parameters in [
          options_pb2.ConvertorOptions.TESTING,
          options_pb2.ConvertorOptions.VALIDATION_AND_TESTING
      ]
      scrub_validsplit_parameters = (
          options.scrub_parameters ==
          options_pb2.ConvertorOptions.VALIDATION_AND_TESTING)

      if ((theorem.training_split == proof_assistant_pb2.Theorem.TESTING and
           scrub_testsplit_parameters) or
          (theorem.training_split == proof_assistant_pb2.Theorem.VALIDATION and
           scrub_validsplit_parameters)):
        self.forbidden_parameters.add(fp.Fingerprint(theorem))

  def _int64_feature(self, ints):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=ints))

  def _bytes_feature(self, strings: Iterable[Text]):
    return tf.train.Feature(
        bytes_list=tf.train.BytesList(
            value=[s.encode(encoding=BYTES_FEATURE_ENCODING) for s in strings]))

  def _get_parameter_conclusion(self,
                                parameter: proof_assistant_pb2.Theorem) -> Text:
    """Get conclusion from fingerprint (prioritized), or one in theorem."""
    if (parameter.HasField('fingerprint') and
        parameter.fingerprint in self.fingerprint_conclusion_map):
      conclusion = self.fingerprint_conclusion_map[parameter.fingerprint]
      if (parameter.HasField('conclusion') and
          conclusion != parameter.conclusion):
        raise ValueError('conclusion doesn\'t match that in database')
      return conclusion
    if parameter.HasField('conclusion'):
      return parameter.conclusion
    raise ValueError('Neither conclusion present, nor fingerprint %d found'
                     ' in theorem database.' % parameter.fingerprint)

  def _extract_theorem_parameters(
      self, tactic_application: deephol_pb2.TacticApplication
  ) -> Tuple[List[Text], List[Text]]:
    """Extracts parameters of type theorem from a tactic application, if any.

    Note: it might be misleading to call these theorems. If the source is from
    an assumption, the theorem is of the form x |- x. We return x in this case.

    Arguments:
      tactic_application: tactic application to extract the parameters from.

    Returns:
      A pair of (parameters, hard_negatives), where parameters are the
      conclusions of the parameters and hard_negatives are those selected
      parameters that did not contribute to the final outcome. Both are
      preprocessed.
    """
    theorems = []
    hard_negatives = []
    for parameter in tactic_application.parameters:
      if parameter.theorems and not (
          parameter.parameter_type == deephol_pb2.Tactic.THEOREM or
          parameter.parameter_type == deephol_pb2.Tactic.THEOREM_LIST):
        raise ValueError('Unexpected theorem parameters or incorrect type.')

      theorems += [
          self._get_parameter_conclusion(theorem)
          for theorem in parameter.theorems
          if fp.Fingerprint(theorem) not in self.forbidden_parameters
      ]
      hard_negatives += [
          self._get_parameter_conclusion(theorem)
          for theorem in parameter.hard_negative_theorems
          if fp.Fingerprint(theorem) not in self.forbidden_parameters
      ]
    return theorems, hard_negatives

  def _get_thm_features(self, theorem_parameters: List[Text]
                       ) -> Dict[Text, tf.train.Feature]:
    """Constructs the features for the theorem parameters.

    Args:
      theorem_parameters: A list of sexpressions that represents the theorem
        arguments.

    Returns:
      A dictionary that maps the names of the features to tf.train.Feature
      objects.
    """
    thm_features = {
        # theorem parameters in tactic application
        'thms': self._bytes_feature(theorem_parameters),
    }
    return thm_features

  def _proof_step_features(self, goal_proto: proof_assistant_pb2.Theorem,
                           tactic_application: deephol_pb2.TacticApplication
                          ) -> Dict[Text, tf.train.Feature]:
    """Compute the basic features of a proof step (goal, tactic, and args)."""
    # preprocessed goal's conclusion's features
    features = {'goal': self._bytes_feature([goal_proto.conclusion])}
    tactic_id = self.tactic_name_id_map[tactic_application.tactic]
    theorem_parameters, hard_negatives = self._extract_theorem_parameters(
        tactic_application)
    features.update(self._get_thm_features(theorem_parameters))
    features.update({
        # preprocessed goal's hypotheses
        'goal_asl': self._bytes_feature(goal_proto.hypotheses),
        # tactic id of tactic application
        'tac_id': self._int64_feature([tactic_id]),
        # Hard (high scoring) negative examples for the parameters that were
        # selected specifically to train against.
        'thms_hard_negatives': self._bytes_feature(hard_negatives),
    })
    return features

  def process_proof_step(self, goal_proto: proof_assistant_pb2.Theorem,
                         tactic_application: deephol_pb2.TacticApplication
                        ) -> Optional[tf.train.Example]:
    """Convert goal,tactic pair to TFExample (for closed goal) or None."""
    if not tactic_application.closed:
      return None
    features = self._proof_step_features(goal_proto, tactic_application)
    return tf.train.Example(features=tf.train.Features(feature=features))

  def process_proof_node(self, proof_node: deephol_pb2.ProofNode):
    for tactic_application in proof_node.proofs:
      tfexample = self.process_proof_step(proof_node.goal, tactic_application)
      if tfexample is not None:
        yield tfexample

  def process_proof_log(self, proof_log: deephol_pb2.ProofLog):
    for proof_node in proof_log.nodes:
      for example in self.process_proof_node(proof_node):
        yield example

  def process_proof_logs(self, proof_logs):
    for proof_log in proof_logs:
      for example in self.process_proof_log(proof_log):
        yield example

  def to_negative_example(self, negative_theorem: proof_assistant_pb2.Theorem
                         ) -> tf.train.Example:
    raise NotImplementedError(
        'to_negative_example not implemented for base class.')

def create_processor(
    options: options_pb2.ConvertorOptions,
    theorem_database: Optional[proof_assistant_pb2.TheoremDatabase] = None,
    tactics: Optional[List[deephol_pb2.Tactic]] = None) -> ProofLogToTFExample:
  """Factory function for ProofLogToTFExample."""

  if theorem_database and options.theorem_database_path:
    raise ValueError(
        'Both thereom database as well as a path to load it from file '
        'provided. Only provide one.')
  if not theorem_database:
    theorem_database = io_util.load_theorem_database_from_file(
        str(options.theorem_database_path))

  if tactics and options.tactics_path:
    raise ValueError('Both tactics as well as a path to load it from '
                     'provided. Only provide one.')
  if not tactics:
    tactics = io_util.load_tactics_from_file(str(options.tactics_path), None)
  tactics_name_id_map = {tactic.name: tactic.id for tactic in tactics}

  if options.replacements_hack:
    logging.warning('Replacments hack is enabled.')
    tactics_name_id_map.update({
        'GEN_TAC': 8,
        'MESON_TAC': 11,
        'CHOOSE_TAC': 34,
    })
  if options.format != options_pb2.ConvertorOptions.HOLPARAM:
    raise ValueError('Unknown options_pb2.ConvertorOptions.TFExampleFormat.')
  return ProofLogToTFExample(tactics_name_id_map, theorem_database, options)


text:
/**
 * This package contains an Annotation Processor that will turn AST Node templates into the actual AST Node source files.
 * This package is only required to process the source files; it should not be included in the runtime distribution of {@code lombok.ast}.
 *

 * To create an AST Node template for a hypothetical node named {@code If}, create a class annotated with {@link GenerateAstNode} whose name
 * ends in {@code Template}. Each field then represents an AST field and will automatically be treated as such. Methods are normally ignored
 * unless you annotate them with one of the annotations in this package. Specifically:
 *

 *
{@link lombok.ast.template.CopyMethod}

 *
A wrapper method will be generated in the AST Node class that calls this method. It has the same name. Annotated method must be static,
 * and the first parameter must be the generated type, e.g. {@code @CopyMethod public static boolean foo(If self, int someOtherParam) ...}.

 *
{@link lombok.ast.template.InitialValue}

 *
Use to specify a default initial value for the field. By default there is no initial value (JVM default of null).

 *
{@link lombok.ast.template.NotChildOfNode}

 *
Use to specify a field does not contain an AST Node but a terminal, such as for example the name of an identifier node.

 *
{@link lombok.ast.template.SyntaxCheck}

 *
Annotates a method to indicate it must be called to check if the node is syntactically valid. Can also be put on a type to indicate all methods in it are syntax checks.

 *
{@link lombok.ast.template.Mandatory}

 *
Indicates the field would not be {@code null} in a syntactically valid AST tree.

 *

 * See the javadoc of each annotation for more detailed information about how to use them.
 *
 * Examples can be found in {@code src/main/lombok/ast/Templates.java}.
 */
package lombok.ast.template;


text:
import tweepy

import os
from flask import Flask, make_response, jsonify

CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']

app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)

@app.route('/twitter/avatar/<username>', methods=['GET'])
def get_user_avatar(username):
    try:
        user = api.get_user(username)
    except tweepy.TweepError:
        return make_response(jsonify({'error': 'no username %s' % (username)}), 404)
    else:
        json_data = {'avatar': user.profile_image_url}
        return make_response(jsonify(json_data), 200)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8888, debug=True)


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<event category="STEP" id="0">
  <actions>
    <action id="603" library="1">
      <!--action name: Code-->
      <kind>CODE</kind>
      <allowRelative>false</allowRelative>
      <question>false</question>
      <canApplyTo>true</canApplyTo>
      <actionType>CODE</actionType>
      <functionName/>
      <relative>false</relative>
      <not>false</not>
      <appliesTo>.self</appliesTo>
      <arguments>
        <argument kind="STRING">if !instance_number(oTrain)
{
    winDelay -= 1
    if winDelay <= 0
    {
        winTime += 1
    }
    if winTime = 200
    {
        sound_play(soPiece)
        piece = instance_create(176, 144, oBookPiece)
        piece.target = rTown
        oPlayer.x = 192
        oPlayer.y = 224
    }
}

</argument>
      </arguments>
    </action>
  </actions>
</event>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<form action="" method="post" onsubmit="check()">
    用户名:<input type="text" name="username" id="username"/>

    密码:<input type="password" name="password" id="password"/>

    邮箱:<input type="text" name="email" id="email"/>

    <input type="submit" value="注册"/>

</form>


text:
#ifndef LWM2M_OBJ_ACCESS_CONTROL_H
#define LWM2M_OBJ_ACCESS_CONTROL_H
#include "lwm2m_engine.h"
#include "lwm2m_object.h"

/**
 * @brief Main access control logic. Checks if the server with instance id @p server_obj_inst are
 * allowed to do @p operation on the object instance of object id @p obj_id
 * and object instance id @p obj_inst_id. If access control is enabled, this should
 * be called before every operation to test access.
 *
 * @param obj_id object id of the object instance having its rights checked.
 * @param obj_inst_id object instance id of the object instance having its rights checked.
 * @param server_obj_inst object instance id of the server attempting to do the operation.
 * @param operation lwm2m operation / permission (like LWM2M_OP_READ)
 * @param bootstrap_mode 1/0. Bootstrap servers should have complete access during bootstrap.
 * @return int to signal access:
 *		 0		- server has access
 *		-EACCES	- unauthorized
 *		-EPERM	- method not allowed
 */
int access_control_check_access(uint16_t obj_id, uint16_t obj_inst_id, uint16_t server_obj_inst,
				uint16_t operation, bool bootstrap_mode);

/**
 * @brief Creates an access control object instance. Should be called every
 * time an object instance is created.
 *
 * @param obj_id object id of the object instance getting an access control.
 * @param obj_inst_id object instance id of the object instance getting access control.
 * @param server_obj_inst_id object instance id of the server creating the object instance.
 */
void access_control_add(uint16_t obj_id, uint16_t obj_inst_id, int server_obj_inst_id);

/**
 * @brief Creates an access control object instance for objects. Should be called if servers should
 * have access to create object instances of object id @p obj_id.
 *
 * @param obj_id object id of the object getting access control.
 * @param server_obj_inst_id object instance id of the server creating the access control
 * object instance.
 */
void access_control_add_obj(uint16_t obj_id, int server_obj_inst_id);

/**
 * @brief Removes the access control instance that contains the access rights concerning
 * the object instance of object id @p obj_id and object instance id @p obj_inst_id.
 * Does nothing if obj_id == 2 (i.e. object id for access control). Should be called
 * automatically any time an object instance is unregistered/deleted.
 *
 * @param obj_id object id of the object instance getting removed.
 * @param obj_inst_id object instance id of the object instance getting removed.
 */
void access_control_remove(uint16_t obj_id, uint16_t obj_inst_id);

/**
 * @brief Removes the access control instance that contains the access rights concerning
 * the object with object id @p obj_id.
 *
 * @param obj_id object id of the object gettting removed.
 */
void access_control_remove_obj(uint16_t obj_id);

#endif


text:
@implementation SpiralGalaxy1

+ (SpiralGalaxy1*)group:(SKNode*)targetNode {
    SpiralGalaxy1 *group = (SpiralGalaxy1*)[super group:targetNode];

    group.oscillator.angularVelocity = M_PI_2 * 1.45;
    [group addArm];
    [group addArm];
    [group addArm];

    group.xScale = 3.75;
    group.yScale = 0.75;
    return group;
}

- (SpiralArmEmitter*)addArm {
    SpiralArmEmitter *arm = [SpiralArmEmitter emitter];
    arm.targetNode = self.targetNode;
    arm.particleBirthRate = 40;
    arm.particleLifetime = 5.0;
    arm.particleLifetimeRange = 0.0;//arm.particleLifetime * 0.25;
    arm.particleSpeed = 50;
    arm.particleSpeedRange = arm.particleSpeed * 0.25;
    arm.particleScale = 0.5;
    arm.particleScaleSpeed = 0.4;
    arm.particleAlpha = 1.0;
    arm.particleAlphaRange = 0.2;
    arm.particleAlphaSpeed = -0.25;
    arm.emissionAngle = 0;
    arm.emissionAngleRange = randomValueInRange(0.0, 1.0); // 0.0;

    arm.alpha = randomValueInRange(0.85, 1.0);
    [self addChild:arm];
    return arm;
}

@end


text:
using System.Threading.Tasks;
using Orleans;
using UnitTests.GrainInterfaces;

namespace UnitTests.Grains
{
    /// <summary>
    /// A simple grain that allows to set two arguments and then multiply them.
    /// </summary>
    public class AsyncSimpleGrain : SimpleGrain, ISimpleGrainWithAsyncMethods
    {
        TaskCompletionSource<int> resolver;

        public async Task<int> GetAxB_Async()
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            return await GetAxB();
        }

        public async Task<int> GetAxB_Async(int a, int b)
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            return await GetAxB(a, b);
        }
        public async Task SetA_Async(int a)
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            await SetA(a);
        }
        public async Task SetB_Async(int b)
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            await SetB(b);
        }

        public async Task IncrementA_Async()
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            await IncrementA();
        }

        public async Task<int> GetA_Async()
        {
            await Task.Delay(1000); // just to delay resolution of the promise for testing purposes
            return await GetA();
        }

        public Task<int> GetX()
        {
            resolver = new TaskCompletionSource<int>();
            return resolver.Task;
        }

        public Task SetX(int x)
        {
            resolver.SetResult(x);
            return Task.CompletedTask;
        }
    }
}


text:
package rickover

import (
	"context"
	"fmt"
	"os"
	"os/signal"

	log "github.com/inconshreveable/log15"
	"github.com/kevinburke/rickover/config"
	"github.com/kevinburke/rickover/dequeuer"
	"github.com/kevinburke/rickover/metrics"
	"github.com/kevinburke/rickover/models/db"
	"github.com/kevinburke/rickover/services"
	"golang.org/x/sys/unix"
)

var dbConns int
var downstreamUrl string
var downstreamPassword string

func init() {
	var err error
	dbConns, err = config.GetInt("PG_WORKER_POOL_SIZE")
	if err != nil {
		log.Info("Error getting database pool size: %s. Defaulting to 20", err)
		dbConns = 20
	}

	downstreamPassword = os.Getenv("DOWNSTREAM_WORKER_AUTH")
}

func Example_dequeuer() {
	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		sigterm := make(chan os.Signal, 1)
		signal.Notify(sigterm, unix.SIGINT, unix.SIGTERM)
		sig := <-sigterm
		fmt.Printf("Caught signal %v, shutting down...\n", sig)
		cancel()
	}()

	logger := log.New()
	downstreamUrl = config.GetURLOrBail("DOWNSTREAM_URL").String()
	jp := services.NewJobProcessor(services.NewDownstreamHandler(logger, downstreamUrl, downstreamPassword))

	go metrics.Run(context.TODO(), metrics.LibratoConfig{
		Namespace: "rickover.dequeuer",
		Source:    "worker",
		Email:     "TODO@example.com",
	})

	srv, err := dequeuer.New(ctx, dequeuer.Config{
		Connector:       db.DefaultConnection,
		Processor:       jp,
		NumConns:        10,
		StuckJobTimeout: dequeuer.DefaultStuckJobTimeout,
	})
	if err != nil {
		log.Info("could not start dequeuer", "err", err)
	}
	// Run will:
	//
	// - start all worker pools
	// - start a daemon to "fail" stuck jobs after 7 minutes
	// - start metrics to monitor in progress jobs, active queries against the
	// database, and the depth of the queue.
	if err := srv.Run(ctx); err != nil && err != context.Canceled {
		log.Error("error running dequeuer", "err", err)
		os.Exit(2)
	}
	log.Info("All pools shut down. Quitting.")
}


text:
using System;
using System.IO;
using Newtonsoft.Json;
using System.Text;

namespace Prosegur.Processo.BuscarLatLong.Comum
{
    public static class Funcoes
    {
        public static string MontarTextoEndereco(System.Data.DataRow pLinha)
        {
            //Montar a string de endereço.
            Log.AddLog("Montando string de endereço.", Enum.ETipoLog.Info);

            StringBuilder sbEndereco = new StringBuilder();
            sbEndereco.Append(pLinha["DES_TIPO_CALLE"].ToString() + " ");
            sbEndereco.Append(pLinha["DES_CALLE"].ToString() + " ");
            sbEndereco.Append(pLinha["NUM_NRO"].ToString().Trim() + " ");
            //sbEndereco.Append(pLinha["DES_BARRIO"].ToString() + " ");
            sbEndereco.Append(pLinha["COD_CODIGO_POSTAL"].ToString() + " ");
            sbEndereco.Append(pLinha["DES_CIUDAD"].ToString() + " ");
            sbEndereco.Append(pLinha["COD_ESTADO"].ToString() + " ");
            sbEndereco.Append(pLinha["DES_PAIS"].ToString() + " ");

            Log.AddLog($"Endereço: {sbEndereco.ToString()}", Enum.ETipoLog.Info);

            return sbEndereco.ToString();
        }

        public static void GravarJSON(string pCaminho, ChamadasAPI pChamadas)
        {
            String nomeArquivo;
            nomeArquivo = pCaminho + Constantes.NomeJSONControleExecucoes;

            // serialize JSON to a string and then write string to a file
            //File.WriteAllText(nomeArquivo, JsonConvert.SerializeObject(pChamadas));

            // serialize JSON directly to a file
            using (StreamWriter file = File.CreateText(nomeArquivo))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, pChamadas);
            }
        }

        public static ChamadasAPI LerJSON(string pCaminho)
        {
            ChamadasAPI Chamadas;
            String nomeArquivo;
            nomeArquivo = pCaminho + Constantes.NomeJSONControleExecucoes;

            // deserialize JSON directly from a file
            using (StreamReader file = File.OpenText(nomeArquivo))
            {
                JsonSerializer serializador = new JsonSerializer();
                Chamadas = (ChamadasAPI)serializador.Deserialize(file, typeof(ChamadasAPI));
            }
            return Chamadas;
        }
    }
}


text:
using namespace std;
using namespace dfa;
using namespace util;

/// \brief Empty action list
const ndfa::accept_action_list ndfa::s_NoActions;

/// \brief A placeholder 'no state' representation
const state ndfa::s_NoState(-1);

/// \brief Copies an existing NDFA
ndfa::ndfa(const ndfa& copyFrom)
: m_States(new state_list())
, m_Symbols(new symbol_map(*copyFrom.m_Symbols))
, m_Accept(new accept_action_for_state())
, m_CurrentState(0)
, m_IsDeterministic(copyFrom.m_IsDeterministic) {
    // Copy the states
    for (state_list::const_iterator copyState = copyFrom.m_States->begin(); copyState != copyFrom.m_States->end(); ++copyState) {
        m_States->push_back(new state(**copyState));
    }

    // Copy the accept actions
    for (accept_action_for_state::const_iterator stateActions = copyFrom.m_Accept->begin(); stateActions != copyFrom.m_Accept->end(); ++stateActions) {
        accept_action_list& action = (*m_Accept)[stateActions->first];
        for (accept_action_list::const_iterator actionIt = stateActions->second.begin(); actionIt != stateActions->second.end(); ++actionIt) {
            action.push_back((*actionIt)->clone());
        }
    }
}

// \brief Creates a new NDFA
ndfa::ndfa()
: m_CurrentState(0)
, m_States(new state_list())
, m_Accept(new accept_action_for_state())
, m_Symbols(new symbol_map())
, m_IsDeterministic(false) {
    m_States->push_back(new state(0));
}

/// \brief Creates a new NDFA with the specified data
ndfa::ndfa(state_list* states, symbol_map* symbols, accept_action_for_state* accept)
: m_CurrentState(0)
, m_States(states)
, m_Symbols(symbols)
, m_Accept(accept)
, m_IsDeterministic(false) {
}

// \brief Destructor
ndfa::~ndfa() {
    // Destroy any accept actions that might be in this NDFA
    for (accept_action_for_state::iterator acceptState = m_Accept->begin(); acceptState != m_Accept->end(); ++acceptState) {
        for (accept_action_list::iterator actionList = acceptState->second.begin(); actionList != acceptState->second.end(); ++actionList) {
            delete *actionList;
        }
    }

    // Destroy any states
    for (state_list::iterator stateIt = m_States->begin(); stateIt != m_States->end(); ++stateIt) {
        delete *stateIt;
    }

    // Destroy the symbol map
    delete m_Symbols;
    delete m_States;
    delete m_Accept;
}

/// \brief While building an NDFA: moves to the specified state
int ndfa::goto_state(int newState) {
    // Set the current state
    m_CurrentState = newState;

    // Set the current state to 0 if an out of range state is specified
    if (m_CurrentState < 0 || m_CurrentState >= (int) m_States->size()) {
        m_CurrentState = 0;
    }

    // The current state is the return value
    return m_CurrentState;
}

/// \brief While building an NDFA: moves to the start state
int ndfa::goto_start() {
    m_CurrentState = 0;
    return m_CurrentState;
}

/// \brief Adds a new state (with no transitions), and returns the ID for that state
int ndfa::add_state() {
    int     newStateId  = (int)m_States->size();
    state*  newState    = new state(newStateId);

    m_States->push_back(newState);

    return newStateId;
}

/// \brief Adds a transition from the current to a new state, moves to the state, and returns the ID of the state
int ndfa::add_transition(const symbol_set& transition) {
    // Add a new state
    int newStateId = add_state();

    // Add a transition to this state
    add_transition(transition, newStateId);

    // Return the ID of the new state
    return newStateId;
}

/// \brief Adds a transition from the current state to the specified state, and moves to that state
void ndfa::add_transition(const symbol_set& symbols, int newState) {
    /// \brief Add the transition for this state
    add_transition(m_CurrentState, symbols, newState);

    // Update the current state
    m_CurrentState = newState;
}

/// \brief Adds a transition from the old state to the new state
void ndfa::add_transition(int oldState, const symbol_set& symbols, int newState) {
    // Nothing to do if the state ID is invalid
    if (oldState < 0 || oldState >= (int) m_States->size()) return;
    if (newState < 0 || newState >= (int) m_States->size()) return;

    // Get the ID for this symbol set
    int symbolId = m_Symbols->identifier_for_symbols(symbols);

    // Add as a transition to the current state
    (*m_States)[oldState]->add(transition(symbolId, newState));
}

/// \brief Marks the current state as an accepting state (for the specified symbol)
///
/// If eager is set, then the state is marked as an 'eager' accepting state - ie, the resulting DFA will not consider states 'following' this one
/// when it is evaluated.
void ndfa::accept(int symbol, bool eager) {
    accept(accept_action(symbol, eager));
}

/// \brief Marks the current state as an accepting state (for the specified symbol)
///
/// If eager is set, then the state is marked as an 'eager' accepting state - ie, the resulting DFA will not consider states 'following' this one
/// when it is evaluated.
void ndfa::accept(const accept_action& action) {
    accept(m_CurrentState, action);
}

/// \brief Marks the current state as an accepting state, returning the specified symbol
///
/// If eager is set, then the state is marked as an 'eager' accepting state - ie, the resulting DFA will not consider states 'following' this one
/// when it is evaluated.
void ndfa::accept(int state, const accept_action& action) {
    // Clone the action and store it
    (*m_Accept)[state].push_back(action.clone());
}

/// \brief Marks the specified state as non-accepting
void ndfa::clear_accept(int state) {
    // Remove all of the items from this state
    (*m_Accept)[state].clear();
}

/// \brief Returns the surrogate pair for a UTF-32 value
///
/// See section 3.9 of the Unicode standard.
static inline pair<int, int> surrogate_pair(int ucs32) {
    // The 'lower' range (second code point)
    int lower = 0xdc00 | (ucs32&0x3ff);

    // The 'higher' range (first code point)
    int higher1 = (ucs32 >> 10) & 0x3f;
    int higher2 = (ucs32 >> 16) - 1;
    int higher = 0xd800 | higher1 | (higher2<<6);

    // Return the pair for this character
    return pair<int, int>(higher, lower);
}

/// \brief Adds a transition for a range of surrogate symbols for the specified state
static void add_surrogate_transition(const range<int>& surrogateRange, int currentState, int targetState, ndfa* nfa) {
    // If the range is out of the range of valid surrogate characters then clip it
    if (surrogateRange.lower() >= 0x110000) return;
    if (surrogateRange.upper() > 0x110000) {
        add_surrogate_transition(range<int>(surrogateRange.lower(), 0x110000), currentState, targetState, nfa);
        return;
    }

    // Work out the range as surrogate pairs
    pair<int, int> surrogateLower   = surrogate_pair(surrogateRange.lower());
    pair<int, int> surrogateHigher  = surrogate_pair(surrogateRange.upper()-1);

    // Action depends on whether or not there are 1, 2 or more 'upper' characters
    if (surrogateLower.first == surrogateHigher.first) {
        // Transit to a state if we match the 'upper' code point
        int tmpState = nfa->add_state();
        nfa->add_transition(currentState, range<int>(surrogateLower.first, surrogateLower.first+1), tmpState);

        // Transit to the final state if we match any of the lower symbols
        nfa->add_transition(tmpState, range<int>(surrogateLower.second, surrogateHigher.second+1), targetState);
    } else {
        // Transit to a new state for the lower set of symbols
        int tmpState1 = nfa->add_state();
        nfa->add_transition(currentState, range<int>(surrogateLower.first, surrogateLower.first+1), tmpState1);

        // Transit to the final state for all the 'lower' symbols
        nfa->add_transition(tmpState1, range<int>(surrogateLower.second, 0xdc00), targetState);

        // ... do the same for the 'upper' set of symbols
        int tmpState2 = nfa->add_state();
        nfa->add_transition(currentState, range<int>(surrogateHigher.first, surrogateHigher.first+1), tmpState2);

        // Transit to the final state for all the 'lower' symbols
        nfa->add_transition(tmpState2, range<int>(0xd800, surrogateHigher.second+1), targetState);

        // If there's a middle range, then add transitions for that as well
        if (surrogateHigher.first-1 > surrogateLower.first) {
            // Transit for all of the remaining 'higher' symbols
            int tmpState3 = nfa->add_state();
            nfa->add_transition(currentState, range<int>(surrogateLower.first+1, surrogateHigher.first), tmpState3);

            // Accept for any 'lower' symbol
            nfa->add_transition(tmpState3, range<int>(0xdc00, 0xe000), targetState);
        }
    }
}

/// \brief Unicode converter
static unicode s_Unicode;

/// \brief Moves to a new state when the specified range of symbols are encountered
inline void ndfa::builder::add_with_surrogates(const symbol_set& symbols) {
    // Get the state that should be moved to by this transition
    int nextState = m_NextState;
    m_NextState = -1;

    // Use a new state if no state has been explicitly set
    if (nextState == -1) {
        nextState = m_Ndfa->add_state();
    }

    // If generate surrogates is turned on, and the symbol set ends outside the surrogate range
    if (m_GenerateSurrogates) {
        // Search to see if there are any surrogate ranges
        symbol_set surrogates;
        symbol_set nonSurrogates;

        // Look through the symbol set
        for (symbol_set::iterator syms = symbols.begin(); syms != symbols.end(); ++syms) {
            // Ignore empty ranges
            if (syms->lower() >= syms->upper()) continue;

            if (syms->upper() > 0x10000) {
                // Surrogate range
                if (syms->lower() <= 0xffff) {
                    // Split range
                    nonSurrogates   |= range<int>(syms->lower(), 0x10000);
                    surrogates      |= range<int>(0x10000, syms->upper());
                } else {
                    // Just a surrogate range
                    surrogates |= *syms;
                }
            } else {
                // Not a surrogate range
                nonSurrogates |= *syms;
            }
        }

        // See if there were any surrogate ranges
        if (!surrogates.empty()) {
            // Push before this surrogate
            push();

            if (!nonSurrogates.empty()) {
                // Just add a transition on the non-surrogate range
                m_Ndfa->add_transition(m_CurrentState, nonSurrogates, nextState);
            }

            // Add a surrogate transition for each surrogate range
            for (symbol_set::iterator syms = surrogates.begin(); syms != surrogates.end(); ++syms) {
                add_surrogate_transition(*syms, m_CurrentState, nextState, m_Ndfa);
            }

            // Update the current state
            m_PreviousState = m_CurrentState;
            m_CurrentState  = nextState;

            // Pop afterwards
            pop();

            // Done
            return;
        }
    }

    // Add the transition for these symbols
    m_Ndfa->add_transition(m_CurrentState, symbols, nextState);
    m_PreviousState = m_CurrentState;
    m_CurrentState  = nextState;
}

/// \brief Moves to a new state when the specified range of symbols are encountered
ndfa::builder& ndfa::builder::operator>>(const symbol_set& symbols) {
    // Add upper and lower-case variants of the symbols if this is set to be case insensitive
    if (m_AddLowercase || m_AddUppercase) {
        symbol_set transformed = symbols;

        if (m_AddLowercase) {
            transformed |= s_Unicode.to_lower(symbols);
        }

        if (m_AddUppercase) {
            transformed |= s_Unicode.to_upper(symbols);
        }

        add_with_surrogates(transformed);
    } else {
        // Pass straight through
        add_with_surrogates(symbols);
    }

    // Returns itself
    return *this;
}

/// \brief Pops the state on top of the stack and discards it
///
/// Returns false if the stack is empty.
/// The 'previous state' becomes the state on top of the stack.
/// If an 'or' is being constructed, this will move to the final state of the 'or' in the same way that rejoin does.
bool ndfa::builder::pop() {
    if (!m_Stack.empty()) {
        // If there's a final state, then move there from the current state
        if (m_Stack.top().second >= 0) {
            int finalState = m_Stack.top().second;
            *this >> m_Ndfa->get_state(finalState) >> epsilon();
        }

        // Set the previous state to the 'initial' state on top of the stack
        if (m_Stack.top().first >= 0) {
            m_PreviousState = m_Stack.top().first;
        }

        // Pop the state
        m_Stack.pop();
        return true;
    } else {
        return false;
    }
}

/// \brief Begins or continues an 'or' expression
void ndfa::builder::begin_or() {
    // If the stack is empty then push a fake entry
    if (m_Stack.empty()) {
        m_Stack.push(stack_entry(0, -1));
    }

    // The initial state is the state on top of the stack
    int initialState = m_Stack.top().first;

    // Remember the previous state (in case we change it)
    int previousState = m_PreviousState;

    if (m_Stack.top().second < 0) {
        // Create a 'final state' for the various alternatives by adding an epsilon transition
        *this >> epsilon();

        // Set this on the stack
        m_Stack.top().second = m_CurrentState;

        // Preserve the previous state
        m_PreviousState = previousState;
    } else {
        // Create a transition from the current state to the final state
        m_Ndfa->add_transition(m_CurrentState, epsilon(), m_Stack.top().second);
    }

    // Move back to the 'initial state' (the point where the or expression starts)
    m_CurrentState = initialState;
}

/// \brief Moves to the state after the current 'or' expression, if there is one
void ndfa::builder::rejoin() {
    // Nothing to do if the top of the stack isn't building an 'or' expression
    if (m_Stack.empty() || m_Stack.top().second < 0) return;

    // Move to the final state
    int finalState = m_Stack.top().second;
    *this >> m_Ndfa->get_state(finalState) >> epsilon();

    // Unset the final state
    m_Stack.top().second = -1;

    // Pop the top stack entry if it was added by an or operation
    if (m_Stack.top().first == -1) {
        m_Stack.pop();
    }
}

/// \brief Internal method: computes the closure of the specified set of states (modifies the set to include
/// all states reachable by epsilon transitions)
void ndfa::closure(set<int>& states) const {
    /// Set of states that need to be checked for epsilon transitions
    set<int> newStates = states;

    // Get the symbol ID of the epsilon set
    int epsSymbol = m_Symbols->identifier_for_symbols(epsilon());
    if (epsSymbol == -1) return;

    // Iterate until we've added no new states
    while (!newStates.empty()) {
        // Create a set of states we're going to add
        set<int> addedStates;

        for (set<int>::iterator stateIt = newStates.begin(); stateIt != newStates.end(); ++stateIt) {
            // Find any epsilon transitions in this state
            const state& thisState = get_state(*stateIt);

            for (state::iterator transIt = thisState.begin(); transIt != thisState.end(); ++transIt) {
                // Ignore non-epsilon transitions
                if (transIt->symbol_set() != epsSymbol) continue;

                // Ignore this state if it's already in the set
                int newState = transIt->new_state();
                if (states.find(newState) != states.end()) continue;

                // Add this state (and process it for further epsilons the next time through)
                states.insert(newState);
                addedStates.insert(newState);
            }
        }

        // The new states for the next iteration are the states we added in this iterator
        newStates = addedStates;
    }
}

/// \brief Checks the symbol map to see if there are any overlapping ranges. Returns true if overlapping ranges exist.
///
/// This is a slow check to deal with cases where symbol ranges aren't sorting correctly. This should be true for
/// NDFAs returned by to_ndfa_with_unique_symbols() and to_dfa()
bool ndfa::verify_no_symbol_overlap() const {
    // Iterate through all of the symbols in the map
    return !m_Symbols->has_duplicates();
}

/// \brief Checks all of the states in this NDFA and returns true if there are no epsilon transitions and at most one
/// transition per symbol.
bool ndfa::verify_is_dfa() const {
    // Get the symbol ID representing 'epsilon'
    int epsSymbol = m_Symbols->identifier_for_symbols(epsilon());

    // Iterate through the states in this NDFA
    for (state_list::const_iterator nextState = m_States->begin(); nextState != m_States->end(); ++nextState) {
        // Verify that there are no duplicate transitions in this state, and no epsilon transitions
        set<int> usedSymbols;

        // Count 'epsilon' as used right away, so it always generates a conflict
        usedSymbols.insert(epsSymbol);

        // Iterate through the transitions
        for (state::iterator nextTrans = (*nextState)->begin(); nextTrans != (*nextState)->end(); ++nextTrans) {
            // Verify that this symbol isn't already used
            if (usedSymbols.find(nextTrans->symbol_set()) != usedSymbols.end()) {
                return false;
            }

            // Add this symbol set
            usedSymbols.insert(nextTrans->symbol_set());
        }
    }

    // Looks good
    return true;
}

/// \brief Copies the values from the specified NDFA into this one (replacing any values it might already contain)
ndfa& ndfa::operator=(const ndfa& assignFrom) {
    // Nothing to do if we're trying to assign to ourselves
    if (&assignFrom == this) return *this;

    // Destroy any accept actions that might be in this NDFA
    for (accept_action_for_state::iterator acceptState = m_Accept->begin(); acceptState != m_Accept->end(); ++acceptState) {
        for (accept_action_list::iterator actionList = acceptState->second.begin(); actionList != acceptState->second.end(); ++actionList) {
            delete *actionList;
        }
    }

    m_Accept->clear();

    // Destroy any states
    for (state_list::iterator stateIt = m_States->begin(); stateIt != m_States->end(); ++stateIt) {
        delete *stateIt;
    }

    m_States->clear();

    // Copy the states from the target NDFA
    for (int stateId=0; stateId < assignFrom.count_states(); ++stateId) {
        m_States->push_back(new state(assignFrom.get_state(stateId)));
    }

    // Copy the symbol map for this NDFA
    *m_Symbols = assignFrom.symbols();

    // Copy the accepting states for this NDFA
    for (accept_action_for_state::const_iterator acceptAct = assignFrom.m_Accept->begin(); acceptAct != assignFrom.m_Accept->end(); ++acceptAct) {
        // Begin creating a new action list
        accept_action_list& newActions = (*m_Accept)[acceptAct->first];

        // Iterate through the list of actions for this state
        for (accept_action_list::const_iterator copyAction = acceptAct->second.begin(); copyAction != acceptAct->second.end(); ++copyAction) {
            // Ignore NULL actions
            if (!*copyAction) continue;

            // Clone this action
            newActions.push_back((*copyAction)->clone());
        }
    }

    // Copy the remaining parameters
    m_IsDeterministic   = assignFrom.m_IsDeterministic;
    m_CurrentState      = assignFrom.m_CurrentState;

    // Done
    return *this;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/flow.iml" filepath="$PROJECT_DIR$/.idea/modules/flow.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/flow-build.iml" filepath="$PROJECT_DIR$/.idea/modules/flow-build.iml" />
    </modules>
  </component>
</project>


text:
package me.coley.recaf.parse.javadoc;

import java.util.List;

/**
 * Base javadoc member wrapper.
 *
 * @author Matt
 */
public class DocMember {
	private List<String> modifiers;
	private String name;
	private String description;

	/**
	 * @param modifiers
	 * 		Member's access modifiers.
	 * @param name
	 * 		Member's name.
	 * @param description
	 * 		Member's purpose.
	 */
	DocMember(List<String> modifiers, String name, String description) {
		this.modifiers = modifiers;
		this.name = name;
		this.description = description;
	}

	/**
	 * @return Member's name.
	 */
	public String getName() {
		return name;
	}

	/**
	 * @return Member's purpose.
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * @return Access modifiers of the member.
	 */
	public List<String> getModifiers() {
		return modifiers;
	}
}


text:
package org.axonframework.commandhandling.distributed;

import org.axonframework.common.AxonException;

/**
 * Exception indicating that an error has occurred while trying to dispatch a command to another (potentially remote)
 * segment of the CommandBus.
 * <p/>
 * The dispatcher of the command may assume that the Command has never reached its destination, and has not been
 * handled.
 *
 * @author Allard Buijze
 * @since 2.0
 */
public class CommandDispatchException extends AxonException {

    private static final long serialVersionUID = 4587368927394283730L;

    /**
     * Initializes the exception using the given {@code message}.
     *
     * @param message The message describing the exception
     */
    public CommandDispatchException(String message) {
        super(message);
    }

    /**
     * Initializes the exception using the given {@code message} and {@code cause}.
     *
     * @param message The message describing the exception
     * @param cause   The underlying cause of the exception
     */
    public CommandDispatchException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
mTw_404.md

***
[back to TOC](../docs/DOCS-TOC.md)

The new QR-Scanner is now here: [https://mytokenwallet.com/qr-scan-app.html](https://mytokenwallet.com/qr-scan-app.html)


text:
package org.jbpm.console.ng.ht.client.editors.taskcomments;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;

import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.ActionCell.Delegate;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.FormLabel;
import org.gwtbootstrap3.client.ui.Label;
import org.gwtbootstrap3.client.ui.TextArea;
import org.gwtbootstrap3.client.ui.constants.ButtonSize;
import org.gwtbootstrap3.client.ui.gwt.DataGrid;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jbpm.console.ng.ht.client.i18n.Constants;
import org.jbpm.console.ng.ht.model.CommentSummary;
import org.uberfire.workbench.events.NotificationEvent;

@Dependent
@Templated(value = "TaskCommentsViewImpl.html")
public class TaskCommentsViewImpl extends Composite implements TaskCommentsPresenter.TaskCommentsView {

    private Constants constants = GWT.create( Constants.class );

    private TaskCommentsPresenter presenter;

    @Inject
    @DataField
    public FormLabel commentsAccordionLabel;

    @Inject
    @DataField
    public TextArea newTaskCommentTextArea;

    @Inject
    @DataField
    public Label newTaskCommentLabel;

    @Inject
    @DataField
    public Button addCommentButton;

    @Inject
    @DataField
    public DataGrid<CommentSummary> commentsListGrid;

    @Inject
    @DataField
    public SimplePager pager;

    @Inject
    @DataField
    public FlowPanel listContainer;

    @Inject
    private Event<NotificationEvent> notification;

    private ListHandler<CommentSummary> sortHandler;

    private static final int COMMENTS_PER_PAGE = 6;

    @Override
    public void clearCommentInput() {
        newTaskCommentTextArea.setText( "" );
    }

    @Override
    public void redrawDataGrid() {
        commentsListGrid.redraw();
    }

    @Override
    public void init( TaskCommentsPresenter presenter ) {
        this.presenter = presenter;
        listContainer.add( commentsListGrid );
        listContainer.add( pager );
        commentsAccordionLabel.setText( constants.Add_Comment() );
        commentsListGrid.setHeight( "350px" );
        commentsListGrid.setEmptyTableWidget( new HTMLPanel( constants.No_Comments_For_This_Task() ) );
        // Attach a column sort handler to the ListDataProvider to sort the list.
        sortHandler = new ListHandler<CommentSummary>( presenter.getDataProvider().getList() );
        commentsListGrid.addColumnSortHandler( sortHandler );
        initTableColumns();
        presenter.addDataDisplay( commentsListGrid );
        // Create a Pager to control the table.
        pager.setDisplay( commentsListGrid );
        pager.setPageSize( COMMENTS_PER_PAGE );
        adjustDisplayForListOfSize( 1 );

        newTaskCommentTextArea.setWidth( "300px" );
        addCommentButton.setText( constants.Add_Comment() );
        newTaskCommentLabel.setText( constants.Comment() );
    }

    @Override
    public void adjustDisplayForListOfSize( int size ) {
        if ( size > COMMENTS_PER_PAGE ) {
            pager.setVisible( true );
        } else {
            pager.setVisible( false );
        }
    }

    @EventHandler("addCommentButton")
    public void addCommentButton( ClickEvent e ) {
        presenter.addTaskComment( newTaskCommentTextArea.getText() );
    }

    @Override
    public void displayNotification( String text ) {
        notification.fire( new NotificationEvent( text ) );
    }

    private void initTableColumns() {
        // addedBy
        Column<CommentSummary, String> addedByColumn = new Column<CommentSummary, String>( new TextCell() ) {
            @Override
            public String getValue( CommentSummary c ) {
                // for some reason the username comes in format [User:'<name>'], so parse just the <name>
                int first = c.getAddedBy().indexOf( '\'' );
                int last = c.getAddedBy().lastIndexOf( '\'' );
                return c.getAddedBy().substring( first + 1, last );
            }
        };
        addedByColumn.setSortable( false );
        commentsListGrid.addColumn( addedByColumn, constants.Added_By() );
        commentsListGrid.setColumnWidth( addedByColumn, "100px" );

        // date
        Column<CommentSummary, String> addedAtColumn = new Column<CommentSummary, String>( new TextCell() ) {
            @Override
            public String getValue( CommentSummary c ) {
                DateTimeFormat format = DateTimeFormat.getFormat( "dd/MM/yyyy HH:mm" );
                return format.format( c.getAddedAt() );
            }
        };
        addedAtColumn.setSortable( true );
        addedAtColumn.setDefaultSortAscending( true );
        commentsListGrid.addColumn( addedAtColumn, constants.At() );
        sortHandler.setComparator( addedAtColumn, new Comparator<CommentSummary>() {
            @Override
            public int compare( CommentSummary o1,
                                CommentSummary o2 ) {
                return o1.getAddedAt().compareTo( o2.getAddedAt() );
            }
        } );

        // comment text
        Column<CommentSummary, String> commentTextColumn = new Column<CommentSummary, String>( new TextCell() ) {
            @Override
            public String getValue( CommentSummary object ) {
                return object.getText();
            }
        };
        addedByColumn.setSortable( false );
        commentsListGrid.addColumn( commentTextColumn, constants.Comment() );

        List<HasCell<CommentSummary, ?>> cells = new LinkedList<HasCell<CommentSummary, ?>>();

        cells.add( new DeleteCommentActionHasCell( constants.Delete(), new Delegate<CommentSummary>() {
            @Override
            public void execute( CommentSummary comment ) {
                presenter.removeTaskComment( comment.getId() );
            }
        } ) );

        CompositeCell<CommentSummary> cell = new CompositeCell<CommentSummary>( cells );
        Column<CommentSummary, CommentSummary> actionsColumn = new Column<CommentSummary, CommentSummary>(
                cell ) {
            @Override
            public CommentSummary getValue( CommentSummary object ) {
                return object;
            }
        };
        commentsListGrid.addColumn( actionsColumn, "" );
    }

    private class DeleteCommentActionHasCell implements HasCell<CommentSummary, CommentSummary> {

        private ActionCell<CommentSummary> cell;

        public DeleteCommentActionHasCell( String text,
                                           Delegate<CommentSummary> delegate ) {
            cell = new ActionCell<CommentSummary>( text, delegate ) {
                @Override
                public void render( Cell.Context context,
                                    CommentSummary value,
                                    SafeHtmlBuilder sb ) {

                    SafeHtmlBuilder mysb = new SafeHtmlBuilder();
                    mysb.appendHtmlConstant( new Button( constants.Delete() ) {{
                        setSize( ButtonSize.EXTRA_SMALL );
                    }}.getElement().toString() );
                    sb.append( mysb.toSafeHtml() );
                }
            };
        }

        @Override
        public Cell<CommentSummary> getCell() {
            return cell;
        }

        @Override
        public FieldUpdater<CommentSummary, CommentSummary> getFieldUpdater() {
            return null;
        }

        @Override
        public CommentSummary getValue( CommentSummary object ) {
            return object;
        }
    }
}


text:
package com.google.errorprone.scanner;

import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.BiMap;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugCheckerSupplier;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.ErrorProneOptions;
import com.google.errorprone.ErrorProneOptions.Severity;
import com.google.errorprone.InvalidCommandLineOptionException;
import com.google.errorprone.bugpatterns.BugChecker;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.CheckReturnValue;

/**
 * Supplies {@link Scanner}s and provides access to the backing sets of all {@link
 * BugCheckerSupplier}s and enabled {@link BugCheckerSupplier}s.
 */
public abstract class ScannerSupplier implements Supplier<Scanner> {

  /* Static factory methods and helpers */

  /**
   * Returns a {@link ScannerSupplier} with a specific list of {@link BugChecker} classes.
   */
  @SafeVarargs
  public static ScannerSupplier fromBugCheckerClasses(
      Class<? extends BugChecker>... checkerClasses) {
    return fromBugCheckerClasses(Arrays.asList(checkerClasses));
  }

  /**
   * Returns a {@link ScannerSupplier} with a specific list of {@link BugChecker} classes.
   */
  public static ScannerSupplier fromBugCheckerClasses(
      Iterable<Class<? extends BugChecker>> checkerClasses) {
    ImmutableBiMap.Builder<String, BugCheckerSupplier> builder = ImmutableBiMap.builder();
    for (Class<? extends BugChecker> checkerClass : checkerClasses) {
      BugCheckerSupplier supplier = BugCheckerSupplier.fromClass(checkerClass);
      builder.put(supplier.canonicalName(), supplier);
    }
    ImmutableBiMap<String, BugCheckerSupplier> allChecks = builder.build();
    return new ScannerSupplierImpl(allChecks, allChecks.values());
  }

  /**
   * Returns a {@link ScannerSupplier} built from a list of {@link BugChecker} instances.
   */
  public static ScannerSupplier fromBugCheckers(BugChecker... checkers) {
    return fromBugCheckers(Arrays.asList(checkers));
  }

  /**
   * Returns a {@link ScannerSupplier} built from a list of {@link BugChecker} instances.
   */
  public static ScannerSupplier fromBugCheckers(Iterable<? extends BugChecker> checkers) {
    ImmutableBiMap.Builder<String, BugCheckerSupplier> builder = ImmutableBiMap.builder();
    for (BugChecker checker : checkers) {
      BugCheckerSupplier supplier = BugCheckerSupplier.fromInstance(checker);
      builder.put(supplier.canonicalName(), supplier);
    }
    ImmutableBiMap<String, BugCheckerSupplier> allChecks = builder.build();
    return new ScannerSupplierImpl(allChecks, allChecks.values());
  }

  /**
   * Returns a {@link ScannerSupplier} that just returns the {@link Scanner} that was passed in.
   * Used mostly for testing.  Does not implement any method other than
   * {@link ScannerSupplier#get()}.
   */
  public static ScannerSupplier fromScanner(Scanner scanner) {
    return new InstanceReturningScannerSupplierImpl(scanner);
  }

  /* Instance methods */

  /**
   * Returns a map of check name to {@link BugCheckerSupplier} for all {@link BugCheckerSupplier}s
   * in this {@link ScannerSupplier}, including disabled ones.
   */
  protected abstract ImmutableBiMap<String, BugCheckerSupplier> getAllChecks();

  /**
   * Returns the set of {@link BugCheckerSupplier}s that are enabled in this {@link
   * ScannerSupplier}.
   */
  protected abstract ImmutableSet<BugCheckerSupplier> getEnabledChecks();

  /**
   * Applies an override map (from command-line options) to this {@link ScannerSupplier} and
   * returns the resulting {@link ScannerSupplier}.  The overrides may do any of the following:
   *

   *
Enable a check that is currently off

   *
Disable a check that is currently on

   *
Change the severity of a check that is on, promoting a warning to an error or demoting
   * an error to a warning

   *

   *
   * @param errorProneOptions an {@link ErrorProneOptions} object that encapsulates the overrides
   * for this compilation
   * @throws InvalidCommandLineOptionException if the override map attempts to disable a check
   * that may not be disabled
   */
  @CheckReturnValue
  public ScannerSupplier applyOverrides(ErrorProneOptions errorProneOptions)
      throws InvalidCommandLineOptionException {
    Map<String, Severity> severityMap = errorProneOptions.getSeverityMap();
    if (severityMap.isEmpty()) {
      return this;
    }

    // Initialize result allChecks map and enabledChecks set with current state of this Supplier.
    // We use mutable data structures here so that (1) we can replace existing BugCheckerSuppliers
    // with new ones to override the severity of a check, and (2) we can remove checks from
    // enabledChecks if they are overridden to off.
    BiMap<String, BugCheckerSupplier> allChecks = HashBiMap.create(getAllChecks());
    Set<BugCheckerSupplier> enabledChecks = new HashSet<>(getEnabledChecks());

    // Process overrides
    for (Entry<String, Severity> entry : severityMap.entrySet()) {
      BugCheckerSupplier supplier = forName(entry.getKey());
      BugCheckerSupplier newSupplier;
      if (supplier == null) {
        if (errorProneOptions.ignoreUnknownChecks()) {
          continue;
        }
        throw new InvalidCommandLineOptionException(
            entry.getKey() + " is not a valid checker name");
      }
      switch (entry.getValue()) {
        case OFF:
          if (!supplier.suppressibility().disableable()) {
            throw new InvalidCommandLineOptionException(
                supplier.canonicalName() + " may not be disabled");
          }
          enabledChecks.remove(supplier);
          break;
        case DEFAULT:
          enabledChecks.add(supplier);
          break;
        case WARN:
          // Demoting an enabled check from an error to a warning is a form of disabling
          if (enabledChecks.contains(supplier)
              && !supplier.suppressibility().disableable()
              && supplier.severity() == SeverityLevel.ERROR) {
            throw new InvalidCommandLineOptionException(supplier.canonicalName()
                + " is not disableable and may not be demoted to a warning");
          }

          // When the severity of a check is overridden, a new BugCheckerSupplier is produced.
          // The old BugCheckerSupplier must be removed from allChecks and enabledChecks,
          // and the new BugCheckerSupplier must be added.
          newSupplier = supplier.overrideSeverity(SeverityLevel.WARNING);
          enabledChecks.remove(supplier);
          allChecks.put(newSupplier.canonicalName(), newSupplier);
          enabledChecks.add(newSupplier);
          break;
        case ERROR:
          // When the severity of a check is overridden, a new BugCheckerSupplier is produced.
          // The old BugCheckerSupplier must be removed from allChecks and enabledChecks,
          // and the new BugCheckerSupplier must be added.
          newSupplier = supplier.overrideSeverity(SeverityLevel.ERROR);
          enabledChecks.remove(supplier);
          allChecks.put(newSupplier.canonicalName(), newSupplier);
          enabledChecks.add(newSupplier);
          break;
        default:
          throw new IllegalStateException("Unexpected severity level: " + entry.getValue());
      }
    }

    return new ScannerSupplierImpl(ImmutableBiMap.copyOf(allChecks),
        ImmutableSet.copyOf(enabledChecks));
  }

  /**
   * Composes this {@link ScannerSupplier} with the {@code other} {@link ScannerSupplier}.  The
   * set of checks that are turned on is the union of the set of checks on in {@code this} and
   * {@code other}.
   */
  @CheckReturnValue
  public ScannerSupplier plus(ScannerSupplier other) {
    ImmutableBiMap<String, BugCheckerSupplier> combinedAllChecks =
        ImmutableBiMap.<String, BugCheckerSupplier>builder()
            .putAll(this.getAllChecks())
            .putAll(other.getAllChecks())
            .build();
    ImmutableSet<BugCheckerSupplier> combinedEnabledChecks =
        ImmutableSet.<BugCheckerSupplier>builder()
            .addAll(this.getEnabledChecks())
            .addAll(other.getEnabledChecks())
            .build();
    return new ScannerSupplierImpl(combinedAllChecks, combinedEnabledChecks);
  }

  /**
   * Filters this {@link ScannerSupplier} based on the provided predicate.  Returns a
   * {@link ScannerSupplier} with only the checks enabled that satisfy the predicate.
   */
  @CheckReturnValue
  public ScannerSupplier filter(Predicate<? super BugCheckerSupplier> predicate) {
    return new ScannerSupplierImpl(getAllChecks(),
        FluentIterable.from(getEnabledChecks()).filter(predicate).toSet());
  }

  /**
   * Searches the checkers in this {@link ScannerSupplier} and returns the {@link
   * BugCheckerSupplier} with the given {@code name}.  Returns null if no checker is found with
   * that name.
   */
  private BugCheckerSupplier forName(String name) {
    return getAllChecks().get(name);
  }
}


text:
import re
from multiprocessing import cpu_count
from multiprocessing.pool import ThreadPool
import threading
import logging

import boto
from clint.textui import progress

from s3opt.analyser import DecoratorAnalyser

__author__ = 'binhle'

class Pipeline(object):
    """
    A pipeline of multiple processors to process S3 objects.
    """

    def __init__(self, access_key=None, secret_key=None, dry_run=False, threads=None):
        self._pipeline = []
        self.access_key = access_key
        self.secret_key = secret_key
        self.dry_run = dry_run
        self.threads = threads
        self.pool = ThreadPool(threads)
        self.thread_local_buckets = threading.local()

    def append(self, analyser, pattern, ignore_case=True):
        if ignore_case:
            pattern = re.compile(pattern, flags=re.IGNORECASE)
        else:
            pattern = re.compile(pattern)
        self._pipeline.append((pattern, analyser))

    def analyse(self, pattern, ignore_case=True):
        def decorator(func):
            self.append(DecoratorAnalyser(func.__name__, func), pattern, ignore_case)
            return func

        return decorator

    def connect_s3(self):
        if self.access_key is not None and self.secret_key is not None:
            return boto.connect_s3(aws_access_key_id=self.access_key,
                                   aws_secret_access_key=self.secret_key)
        else:
            return boto.connect_s3()

    def get_bucket(self, name):
        if getattr(self.thread_local_buckets, name, None) is None:
            logging.debug('Create new connection to S3 from thread %s', threading.currentThread())
            conn = self.connect_s3()
            bucket = conn.get_bucket(name)
            setattr(self.thread_local_buckets, name, bucket)
        return getattr(self.thread_local_buckets, name)

    def run(self, bucket, prefix='', show_progress=True):
        self.pre_run()

        bucket = self.get_bucket(bucket)
        keys = bucket.list(prefix)
        chunk_size = self.threads if self.threads is not None else cpu_count()
        it = self.pool.imap(self.analyse_key, keys, chunksize=chunk_size)
        if show_progress:
            list(progress.dots(it, label='Analysing bucket "%s"' % bucket.name))
        else:
            list(it)

        self.post_run()

    def pre_run(self):
        for _, analyser in self._pipeline:
            analyser.start()

    def post_run(self):
        for _, analyser in self._pipeline:
            analyser.finish()

    def analyse_key(self, key):
        bucket = self.get_bucket(key.bucket.name)
        for pattern, analyser in self._pipeline:
            if pattern.match(key.key):
                # update key metadata since last analyser might already modified it
                key = bucket.get_key(key.key)
                analyser.analyse(key, dry_run=self.dry_run)


text:
package com.base.util;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import org.lwjgl.util.vector.Vector3f;

public class ObjectHandler {
	private FloatBuffer matrix44Buffer;
	private MatrixHandler modelMatrix;
	private boolean shadow;
	private int vbo;
	private int ibo;
	private int abo;
	private int size;

	public ObjectHandler(Vertex[] vertices, int[] indices, boolean hasShadow) {
		matrix44Buffer = BufferTools.reserveFloatData(16);
		modelMatrix = new MatrixHandler();
		shadow = hasShadow;
		vbo = glGenBuffers();
		ibo = glGenBuffers();
		abo = glGenVertexArrays();
		size = 0;

		addVertices(vertices, indices);
		setUp();
	}

	private void setUp() {
		glBindVertexArray(abo);
		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		glEnableVertexAttribArray(0);
		glEnableVertexAttribArray(1);
		glEnableVertexAttribArray(2);

		glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0);
		glVertexAttribPointer(1, 3, GL_FLOAT, false, Vertex.SIZE * 4, 12);
		glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex.SIZE * 4, 24);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

		glBindVertexArray(0);
		glDisableVertexAttribArray(0);
		glDisableVertexAttribArray(1);
		glDisableVertexAttribArray(2);

		if (shadow)
			setUpShadowBuffer();
	}

	public void draw(int shaderProgram, int modelMatrixID) {
		glUseProgram(shaderProgram);

		modelMatrix.store(matrix44Buffer);
		matrix44Buffer.flip();
		glUniformMatrix4(modelMatrixID, false, matrix44Buffer);

		glBindVertexArray(abo);
		glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		glUseProgram(0);
	}

	private void addVertices(Vertex[] vertices, int[] indices) {
		size = indices.length;

		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		glBufferData(GL_ARRAY_BUFFER, createFlippedBuffer(vertices), GL_STATIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, createFlippedBuffer(indices), GL_STATIC_DRAW);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	}

	private static FloatBuffer createFlippedBuffer(Vertex[] vertices) {
		FloatBuffer buffer = BufferTools.reserveFloatData(vertices.length * Vertex.SIZE);

		for (int i = 0; i < vertices.length; i++) {
			buffer.put(vertices[i].getPos().getX());
			buffer.put(vertices[i].getPos().getY());
			buffer.put(vertices[i].getPos().getZ());
			buffer.put(vertices[i].getColor().getX());
			buffer.put(vertices[i].getColor().getY());
			buffer.put(vertices[i].getColor().getZ());
			buffer.put(vertices[i].getNormal().getX());
			buffer.put(vertices[i].getNormal().getY());
			buffer.put(vertices[i].getNormal().getZ());
		}

		buffer.flip();

		return buffer;
	}

	private static IntBuffer createFlippedBuffer(int[] indices) {
		IntBuffer buffer = BufferTools.reserveIntData(indices.length);

		buffer.put(indices);

		buffer.flip();

		return buffer;
	}

	public void setUpShadowBuffer() {
		if (shadow) {
			glBindVertexArray(abo);

			glBindBuffer(GL_ARRAY_BUFFER, vbo);
			glEnableVertexAttribArray(0);
			glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

			glBindVertexArray(0);
		}
	}

	public void updateShadowBuffer(int shadowShaderProgram, int depthModelMatrixID) {
		if (shadow) {
			glUseProgram(shadowShaderProgram);
			modelMatrix.store(matrix44Buffer);
			matrix44Buffer.flip();
			glUniformMatrix4(depthModelMatrixID, false, matrix44Buffer);

			glBindVertexArray(abo);
			glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);
			glBindVertexArray(0);

			glUseProgram(0);
		}
	}

	public void setPosition(Vector3f position) {
		modelMatrix.setPosition(position);
	}

	public void rotate(Vector3f angle) {
		modelMatrix.setAngle(angle);
	}

	public MatrixHandler getModelMatrix() {
		return modelMatrix;
	}
}


text:
package io.lettuce.core.commands;

import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;

import java.util.Arrays;

import javax.inject.Inject;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;

import io.lettuce.core.RedisCommandExecutionException;
import io.lettuce.core.TestSupport;
import io.lettuce.core.TransactionResult;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.output.StatusOutput;
import io.lettuce.core.output.VoidOutput;
import io.lettuce.core.protocol.AsyncCommand;
import io.lettuce.core.protocol.Command;
import io.lettuce.core.protocol.CommandArgs;
import io.lettuce.core.protocol.CommandType;
import io.lettuce.core.protocol.ProtocolKeyword;
import io.lettuce.core.protocol.RedisCommand;
import io.lettuce.test.LettuceExtension;
import io.lettuce.test.TestFutures;

/**
 * Integration tests for {@link RedisCommands#dispatch}.
 *
 * @author Mark Paluch
 */
@ExtendWith(LettuceExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CustomCommandIntegrationTests extends TestSupport {

    private final RedisCommands<String, String> redis;

    @Inject
    CustomCommandIntegrationTests(StatefulRedisConnection<String, String> connection) {
        this.redis = connection.sync();
    }

    @BeforeEach
    void setUp() {
        this.redis.flushall();
    }

    @Test
    void dispatchSet() {

        String response = redis.dispatch(MyCommands.SET, new StatusOutput<>(StringCodec.UTF8), new CommandArgs<>(
                StringCodec.UTF8).addKey(key).addValue(value));

        assertThat(response).isEqualTo("OK");
    }

    @Test
    void dispatchWithoutArgs() {

        String response = redis.dispatch(MyCommands.INFO, new StatusOutput<>(StringCodec.UTF8));

        assertThat(response).contains("connected_clients");
    }

    @Test
    void dispatchFireAndForget() {
        redis.set(key, value);
        redis.dispatch(CommandType.LLEN, VoidOutput.create(), new CommandArgs<>(StringCodec.UTF8).addKey(key));
    }

    @Test
    void dispatchNoOutputButError() {

        redis.set(key, value);

        assertThatExceptionOfType(RedisCommandExecutionException.class).isThrownBy(
                () -> redis.dispatch(CommandType.LLEN, new VoidOutput<>(), new CommandArgs<>(StringCodec.UTF8).addKey(key)))
                .withMessageStartingWith("WRONGTYPE");
    }

    @Test
    void dispatchShouldFailForWrongDataType() {

        redis.hset(key, key, value);
        assertThatThrownBy(
                () -> redis.dispatch(CommandType.GET, new StatusOutput<>(StringCodec.UTF8),
                        new CommandArgs<>(StringCodec.UTF8).addKey(key))).isInstanceOf(RedisCommandExecutionException.class);
    }

    @Test
    void dispatchTransactions() {

        redis.multi();
        String response = redis.dispatch(CommandType.SET, new StatusOutput<>(StringCodec.UTF8), new CommandArgs<>(
                StringCodec.UTF8).addKey(key).addValue(value));

        TransactionResult exec = redis.exec();

        assertThat(response).isNull();
        assertThat(exec).hasSize(1).contains("OK");
    }

    @Test
    void dispatchMulti() {
        String response = redis.dispatch(CommandType.MULTI, new StatusOutput<>(StringCodec.UTF8));
        assertThat(response).isEqualTo("OK");
        TransactionResult exec = redis.exec();
        assertThat(exec).isEmpty();
    }

    @Test
    void standaloneAsyncPing() {

        RedisCommand<String, String, String> command = new Command<>(MyCommands.PING, new StatusOutput<>(StringCodec.UTF8),
                null);

        AsyncCommand<String, String, String> async = new AsyncCommand<>(command);
        getStandaloneConnection().dispatch(async);

        assertThat(TestFutures.getOrTimeout(async.toCompletableFuture())).isEqualTo("PONG");
    }

    @Test
    void standaloneAsyncBatchPing() {

        RedisCommand<String, String, String> command1 = new Command<>(MyCommands.PING, new StatusOutput<>(StringCodec.UTF8),
                null);

        RedisCommand<String, String, String> command2 = new Command<>(MyCommands.PING, new StatusOutput<>(StringCodec.UTF8),
                null);

        AsyncCommand<String, String, String> async1 = new AsyncCommand<>(command1);
        AsyncCommand<String, String, String> async2 = new AsyncCommand<>(command2);
        getStandaloneConnection().dispatch(Arrays.asList(async1, async2));

        assertThat(TestFutures.getOrTimeout(async1.toCompletableFuture())).isEqualTo("PONG");
        assertThat(TestFutures.getOrTimeout(async2.toCompletableFuture())).isEqualTo("PONG");
    }

    @Test
    void standaloneAsyncBatchTransaction() {

        RedisCommand<String, String, String> multi = new Command<>(CommandType.MULTI, new StatusOutput<>(StringCodec.UTF8));

        RedisCommand<String, String, String> set = new Command<>(CommandType.SET, new StatusOutput<>(StringCodec.UTF8),
                new CommandArgs<>(StringCodec.UTF8).addKey("key").add("value"));

        RedisCommand<String, String, TransactionResult> exec = new Command<>(CommandType.EXEC, null);

        AsyncCommand<String, String, String> async1 = new AsyncCommand<>(multi);
        AsyncCommand<String, String, String> async2 = new AsyncCommand<>(set);
        AsyncCommand<String, String, TransactionResult> async3 = new AsyncCommand<>(exec);
        getStandaloneConnection().dispatch(Arrays.asList(async1, async2, async3));

        assertThat(TestFutures.getOrTimeout(async1.toCompletableFuture())).isEqualTo("OK");
        assertThat(TestFutures.getOrTimeout(async2.toCompletableFuture())).isEqualTo("OK");

        TransactionResult transactionResult = TestFutures.getOrTimeout(async3.toCompletableFuture());
        assertThat(transactionResult.wasDiscarded()).isFalse();
        assertThat(transactionResult.<String> get(0)).isEqualTo("OK");
    }

    @Test
    void standaloneFireAndForget() {

        RedisCommand<String, String, String> command = new Command<>(MyCommands.PING, new StatusOutput<>(StringCodec.UTF8),
                null);
        getStandaloneConnection().dispatch(command);
        assertThat(command.isCancelled()).isFalse();

    }

    private StatefulRedisConnection<String, String> getStandaloneConnection() {

        assumeTrue(redis.getStatefulConnection() instanceof StatefulRedisConnection);
        return redis.getStatefulConnection();
    }

    public enum MyCommands implements ProtocolKeyword {
        PING, SET, INFO;

        private final byte name[];

        MyCommands() {
            // cache the bytes for the command name. Reduces memory and cpu pressure when using commands.
            name = name().getBytes();
        }

        @Override
        public byte[] getBytes() {
            return name;
        }
    }
}


text:
package org.uva.sea.ql.checker.exception.error;

import org.uva.sea.ql.ast.expr.Expr;
import org.uva.sea.ql.ast.type.Type;

public abstract class IllegalTypeError extends TypeError {

	private static final long serialVersionUID = 1L;

	protected Expr expr;
	protected Type given;

	public IllegalTypeError(Expr expr, Type given) {
		this.expr = expr;
		this.given = given;
	}

}


text:
<?php

namespace Models;

class Course
{
    /** @var  string */
    private $name;

    public function __construct(string $name)
    {
        $this->setName($name);
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return Course
     */
    public function setName(string $name): Course
    {
        $this->name = $name;
        return $this;
    }
}


text:
//---------------------------------------------------------------------------
#ifndef MediaInfo_File_MpegaH
#define MediaInfo_File_MpegaH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Tag/File__Tags.h"
#include <map>
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Class File_Mpega
//***************************************************************************

class File_Mpega : public File__Analyze, public File__Tags_Helper
{
public :
    //In
    int64u Frame_Count_Valid;
    bool   FrameIsAlwaysComplete;
    bool   CalculateDelay;

    //Constructor/Destructor
    File_Mpega();

private :
    //Streams management
    void Streams_Fill();
    void Streams_Finish();

    //Buffer - File header
    bool FileHeader_Begin();

    //Buffer - Synchro
    bool Synchronize();
    bool Synched_Test();

    //Buffer - Demux
    bool Demux_UnpacketizeContainer_Test();

    //Buffer - Per element
    void Header_Parse();
    void Data_Parse();
    void Data_Parse_Fill();
    void audio_data_Layer3();

    //Element
    bool Header_Xing();
    bool Header_VBRI();
    bool Header_Encoders();
    void Header_Encoders_Lame();
    void Encoded_Library_Guess();

    //Temp
    Ztring BitRate_Mode;
    Ztring BitRate_Nominal;
    Ztring BitRate_Minimum;
    Ztring Encoded_Library;
    Ztring Encoded_Library_Settings;
    std::map<int16u, size_t> BitRate_Count;
    std::map<int8u, size_t> sampling_frequency_Count;
    std::map<int8u, size_t> mode_Count;
    size_t Surround_Frames;
    size_t Block_Count[3]; //long, short, mixed
    size_t Channels_Count[4]; //Stereo, Join Stereo, Dual mono, mono
    size_t Extension_Count[4]; //No, IS, MS, IS+MS
    size_t Emphasis_Count[4]; //No, 50/15ms, Reserved, CCITT
    size_t Scfsi; //Total
    size_t Scalefac; //Total
    size_t Reservoir; //Total
    int64u LastSync_Offset;
    int64u VBR_FileSize;
    int32u VBR_Frames;
    int32u Reservoir_Max;
    int32u Xing_Scale;
    int32u BitRate; //Average
    int8u  ID;
    int8u  layer;
    int8u  bitrate_index;
    int8u  sampling_frequency;
    int8u  mode;
    int8u  mode_extension;
    int8u  emphasis;
    bool   protection_bit;
    bool   padding_bit;
    bool   copyright;
    bool   original_home;
    size_t MpegPsPattern_Count;

    //Helpers
    bool Element_Name_IsOK();

    #if MEDIAINFO_DEMUX
        #if MEDIAINFO_ADVANCED
            int8u sampling_frequency_Frame0;
            int8u mode_Frame0;
            bool  File_Demux_Unpacketize_StreamLayoutChange_Skip;
        #endif //MEDIAINFO_ADVANCED
    #endif //MEDIAINFO_DEMUX
};

} //NameSpace

#endif