text:
'''
This script aims to be the most generic and the most explicit possible.
It works with OWASP ZAP API Python client.
To use it, you have to load the Python API client module and start ZAP

Before starting this script for the first time: Open ZAP, go to
Tools -> Options -> API -> Generate random Key, copy and paste the key in the
variable "apiKey" of the configuration area

This script is divided into two parts : a configuration area, where you have to
change variables according to your needs, and the part with API calls.

Author : aine-rb on Github, from Sopra Steria
'''

import time
from pprint import pprint
from zapv2 import ZAPv2

#######################################
### BEGINNING OF CONFIGURATION AREA ###
#######################################
## The user only needs to change variable values bellow to make the script
## work according to his/her needs. MANDATORY parameters must not be empty

# MANDATORY. Define the API key generated by ZAP and used to verify actions.
apiKey='qiiutul4utrfub1b8veqs50bk0'

# MANDATORY. Define the listening address of ZAP instance
localProxy = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}

# MANDATORY. True to create another ZAP session (overwrite the former if the
# same name already exists), False to use an existing one
isNewSession = True
# MANDATORY. ZAP Session name
sessionName = 'WebgoatSession'

# Define the list of global exclude URL regular expressions. List can be empty.
# The expressions must follow the java.util.regex.Pattern class syntax
# The following example excludes every single URL except http://localhost:8081
globalExcludeUrl = ['^(?:(?!http:\/\/localhost:8081).*).$']

# MANDATORY. Define if an outgoing proxy server is used
useProxyChain = False
# MANDATORY only if useProxyChain is True, ignored otherwise.
# Outgoing proxy address and port
proxyAddress = 'my.corp.proxy'
proxyPort = '8080'
# Define the addresses to skip in case useProxyChain is True. Ignored
# otherwise. List can be empty.
skipProxyAddresses = ('127.0.0.1;'
                      'localhost')
# MANDATORY only if useProxyChain is True. Ignored otherwise.
# Define if proxy server needs authentication
useProxyChainAuth = False
# MANDATORY only if useProxyChainAuth is True. Ignored otherwise
proxyUsername = ''
proxyPassword = ''
proxyRealm = ''

# MANDATORY. Determine if a proxy script must be loaded. Proxy scripts are
# executed for every request traversing ZAP
useProxyScript = False
# MANDATORY only if useProxyScript is True. Ignored otherwise
proxyScriptName = 'proxyScript.js'
# Script engine values: "Oracle Nashorn" for Javascript,
# "jython" for python, "JSR 223 JRuby Engine" for ruby
proxyScriptEngine = 'Oracle Nashorn'
# Asolute local path
proxyScriptFileName = '/zap/scripts/proxy/proxyScript.js'
proxyScriptDescription = 'This is a description'

# MANDATORY. Determine if context must be configured then used during scans.
# You have to set this parameter to True if you want that ZAP performs scans
# from the point of view of a specific user
useContextForScan = True

# MANDATORY only if useContextForScan is True. Ignored otherwise. Set value to
# True to define a new context. Set value to False to use an existing one.
defineNewContext = True
# MANDATORY only if defineNewContext is True. Ignored otherwise
contextName = 'WebGoat_script-based'
# MANDATORY only if defineNewContext is False. Disregarded otherwise.
# Corresponds to the ID of the context to use
contextId = 0
# Define Context Include URL regular expressions. Ignored if useContextForScan
# is False. You have to put the URL you want to test in this list.
contextIncludeURL = ['http://localhost:8081.*']
# Define Context Exclude URL regular expressions. Ignored if useContextForScan
# is False. List can be empty.
contextExcludeURL = ['http://localhost:8081/WebGoat/j_spring_security_logout',
                     'http://localhost:8081/WebGoat/logout.mvc']

# MANDATORY only if useContextForScan is True. Ignored otherwise. Define the
# session management method for the context. Possible values are:
# "cookieBasedSessionManagement"; "httpAuthSessionManagement"
sessionManagement = 'cookieBasedSessionManagement'

# MANDATORY only if useContextForScan is True. Ignored otherwise. Define
# authentication method for the context. Possible values are:
# "manualAuthentication"; "scriptBasedAuthentication"; "httpAuthentication";
# "formBasedAuthentication"
authMethod = 'scriptBasedAuthentication'

# MANDATORY only if authMethod is set to scriptBasedAuthentication.
# Ignored otherwise
authScriptName = 'TwoStepAuthentication.js'
# Script engine values: Oracle Nashorn for Javascript
# jython for python, JSR 223 JRuby Engine for ruby
authScriptEngine = 'Oracle Nashorn'
# Absolute local path
authScriptFileName = '/zap/scripts/authentication/TwoStepAuthentication.js'
authScriptDescription = 'This is a description'

# MANDATORY only if useContextForScan is True. Ignored otherwise. Each
# name/value pair of authParams are expected to be "x-www-form-urlencoded"
# Here is an example for scriptBasedAuthentication method:
authParams = ('scriptName=' + authScriptName + '&'
              'Submission Form URL=http://localhost:8081/WebGoat/j_spring_security_check&'
              'Username field=username&'
              'Password field=password&'
              'Target URL=http://localhost:8081/WebGoat/welcome.mvc')
## Here is an example for formBasedAuthentication method:
#authParams = ('loginUrl=http://localhost:8081/WebGoat/j_spring_security_check&'
#              'loginRequestData=username%3D%7B%25username%25%7D%26'
#              'password%3D%7B%25password%25%7D')
##Here is an example for httpAuthentication method:
#authParams = ('hostname=http://www.example.com&'
#              'realm=CORP\\administrator&'
#              'port=80')

# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Set the value to True if a loggedin indicator must be used. False if it's a
# logged out indicator that must be used
isLoggedInIndicator = False
# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Define either a loggedin or a loggedout indicator regular expression.
# It allows ZAP to see if the user is always authenticated during scans.
indicatorRegex = '\QLocation: http://localhost:8081/WebGoat/login.mvc\E'

# MANDATORY only if useContextForScan is True. Ignored otherwise.
# Set value to True to create new users, False otherwise
createUser = True
# MANDATORY only if createUser is True. Ignored otherwise. Define the list of
# users, with name and credentials (in x-www-form-urlencoded format)
## Here is an example with the script NashornTwoStepAuthentication.js:
userList = [
    {'name': 'guest', 'credentials': 'Username=guest&Password=guest'},
    {'name': 'webgoat', 'credentials': 'Username=webgoat&Password=webgoat'}
]
## Here is an example with formBasedAuthentication:
#userList = [
#    {'name': 'guest', 'credentials': 'username=guest&password=guest'},
#    {'name': 'webgoat', 'credentials': 'username=webgoat&password=webgoat'}
#]

# MANDATORY only if useContextForScan is True. Ignored otherwise. List can be
# empty. Define the userid list. Created users will be added to this list later
userIdList = []

# MANDATORY. Define the target site to test
target = 'http://localhost:8081/WebGoat'

# You can specify other URL in order to help ZAP discover more site locations
# List can be empty
applicationURL = ['http://localhost:8081/WebGoat/start.mvc',
                  'http://localhost:8081/WebGoat/welcome.mvc',
                  'http://localhost:8081/WebGoat/attack']

# MANDATORY. Set value to True if you want to customize and use a scan policy
useScanPolicy = True
# MANDATORY only if useScanPolicy is True. Ignored otherwise. Set a policy name
scanPolicyName = 'SQL Injection and XSS'
# MANDATORY only if useScanPolicy is True. Ignored otherwise.
# Set value to True to disable all scan types except the ones set in ascanIds,
# False to enable all scan types except the ones set in ascanIds..
isWhiteListPolicy = True
# MANDATORY only if useScanPolicy is True. Ignored otherwise. Set the scan IDs
# to use with the policy. Other scan types will be disabled if
# isWhiteListPolicy is True, enabled if isWhiteListPolicy is False.
# Use zap.ascan.scanners() to list all ascan IDs.
## In the example bellow, the first line corresponds to SQL Injection scan IDs,
## the second line corresponds to some XSS scan IDs
ascanIds = [40018, 40019, 40020, 40021, 40022, 40024, 90018,
            40012, 40014, 40016, 40017]
# MANDATORY only if useScanPolicy is True. Ignored otherwise. Set the alert
# Threshold and the attack strength of enabled active scans.
# Currently, possible values are:
# Low, Medium and High for alert Threshold
# Low, Medium, High and Insane for attack strength
alertThreshold = 'Medium'
attackStrength = 'Low'

# MANDATORY. Set True to use Ajax Spider, False otherwise.
useAjaxSpider = True

# MANDATORY. Set True to shutdown ZAP once finished, False otherwise
shutdownOnceFinished = False

#################################
### END OF CONFIGURATION AREA ###
#################################

# Connect ZAP API client to the listening address of ZAP instance
zap = ZAPv2(proxies=localProxy, apikey=apiKey)

# Start the ZAP session
core = zap.core
if isNewSession:
    pprint('Create ZAP session: ' + sessionName + ' -> ' +
            core.new_session(name=sessionName, overwrite=True))
else:
    pprint('Load ZAP session: ' + sessionName + ' -> ' +
            core.load_session(name=sessionName))

# Configure ZAP global Exclude URL option
print('Add Global Exclude URL regular expressions:')
for regex in globalExcludeUrl:
    pprint(regex + ' ->' + core.exclude_from_proxy(regex=regex))

# Configure ZAP outgoing proxy server connection option
pprint('Enable outgoing proxy chain: ' + str(useProxyChain) + ' -> ' +
        core.set_option_use_proxy_chain(boolean=useProxyChain))
if useProxyChain:
    pprint('Set outgoing proxy name: ' + proxyAddress + ' -> ' +
            core.set_option_proxy_chain_name(string=proxyAddress))
    pprint('Set outgoing proxy port: ' + proxyPort + ' -> ' +
            core.set_option_proxy_chain_port(integer=proxyPort))
    pprint('Skip names for outgoing proxy: ' + skipProxyAddresses + ' -> ' +
            core.set_option_proxy_chain_skip_name(string=skipProxyAddresses))

    # Configure ZAP outgoing proxy server authentication
    pprint('Set outgoing proxy chain authentication: ' +
            str(useProxyChainAuth) + ' -> ' +
            core.set_option_use_proxy_chain_auth(boolean=useProxyChainAuth))
    if useProxyChainAuth:
        pprint('Set outgoing proxy username -> ' +
                core.set_option_proxy_chain_user_name(string=proxyUsername))
        pprint('Set outgoing proxy password -> ' +
                core.set_option_proxy_chain_password(string=proxyPassword))
        pprint('Set outgoing proxy realm: ' + proxyRealm + ' -> ' +
                core.set_option_proxy_chain_realm(string=proxyRealm))

if useProxyScript:
    script = zap.script
    script.remove(scriptname=proxyScriptName)
    pprint('Load proxy script: ' + proxyScriptName + ' -> ' +
            script.load(scriptname=proxyScriptName, scripttype='proxy',
                scriptengine=proxyScriptEngine,
                filename=proxyScriptFileName,
                scriptdescription=proxyScriptDescription))
    pprint('Enable proxy script: ' + proxyScriptName + ' -> ' +
            script.enable(scriptname=proxyScriptName))

if useContextForScan:
    # Define the ZAP context
    context = zap.context
    if defineNewContext:
        contextId = context.new_context(contextname=contextName)
    pprint('Use context ID: ' + contextId)

    # Include URL in the context
    print('Include URL in context:')
    for url in contextIncludeURL:
        pprint(url + ' -> ' +
                context.include_in_context(contextname=contextName,
                                           regex=url))

    # Exclude URL in the context
    print('Exclude URL from context:')
    for url in contextExcludeURL:
        pprint(url + ' -> ' +
                context.exclude_from_context(contextname=contextName,
                                             regex=url))

    # Setup session management for the context.
    # There is no methodconfigparams to provide for both current methods
    pprint('Set session management method: ' + sessionManagement + ' -> ' +
            zap.sessionManagement.set_session_management_method(
                contextid=contextId, methodname=sessionManagement,
                methodconfigparams=None))

    ## In case we use the scriptBasedAuthentication method, load the script
    if authMethod == 'scriptBasedAuthentication':
        script = zap.script
        script.remove(scriptname=authScriptName)
        pprint('Load script: ' + authScriptName + ' -> ' +
                script.load(scriptname=authScriptName,
                            scripttype='authentication',
                            scriptengine=authScriptEngine,
                            filename=authScriptFileName,
                            scriptdescription=authScriptDescription))

    # Define an authentication method with parameters for the context
    auth = zap.authentication
    pprint('Set authentication method: ' + authMethod + ' -> ' +
            auth.set_authentication_method(contextid=contextId,
                                           authmethodname=authMethod,
                                           authmethodconfigparams=authParams))
    # Define either a loggedin indicator or a loggedout indicator regexp
    # It allows ZAP to see if the user is always authenticated during scans
    if isLoggedInIndicator:
        pprint('Define Loggedin indicator: ' + indicatorRegex + ' -> ' +
                auth.set_logged_in_indicator(contextid=contextId,
                                        loggedinindicatorregex=indicatorRegex))
    else:
        pprint('Define Loggedout indicator: ' + indicatorRegex + ' -> ' +
                auth.set_logged_out_indicator(contextid=contextId,
                                        loggedoutindicatorregex=indicatorRegex))

    # Define the users
    users = zap.users
    if createUser:
        for user in userList:
            userName = user.get('name')
            print('Create user ' + userName + ':')
            userId = users.new_user(contextid=contextId, name=userName)
            userIdList.append(userId)
            pprint('User ID: ' + userId + '; username -> ' +
                    users.set_user_name(contextid=contextId, userid=userId,
                                        name=userName) +
                    '; credentials -> ' +
                    users.set_authentication_credentials(contextid=contextId,
                        userid=userId,
                        authcredentialsconfigparams=user.get('credentials')) +
                    '; enabled -> ' +
                    users.set_user_enabled(contextid=contextId, userid=userId,
                                           enabled=True))

# Enable all passive scanners (it's possible to do a more specific policy by
# setting needed scan ID: Use zap.pscan.scanners() to list all passive scanner
# IDs, then use zap.scan.enable_scanners(ids) to enable what you want
pprint('Enable all passive scanners -> ' +
        zap.pscan.enable_all_scanners())

ascan = zap.ascan
# Define if a new scan policy is used
if useScanPolicy:
    ascan.remove_scan_policy(scanpolicyname=scanPolicyName)
    pprint('Add scan policy ' + scanPolicyName + ' -> ' +
            ascan.add_scan_policy(scanpolicyname=scanPolicyName))
    for policyId in range(0, 5):
        # Set alert Threshold for all scans
        ascan.set_policy_alert_threshold(id=policyId,
                                         alertthreshold=alertThreshold,
                                         scanpolicyname=scanPolicyName)
        # Set attack strength for all scans
        ascan.set_policy_attack_strength(id=policyId,
                                         attackstrength=attackStrength,
                                         scanpolicyname=scanPolicyName)
    if isWhiteListPolicy:
        # Disable all active scanners in order to enable only what you need
        pprint('Disable all scanners -> ' +
                ascan.disable_all_scanners(scanpolicyname=scanPolicyName))
        # Enable some active scanners
        pprint('Enable given scan IDs -> ' +
                ascan.enable_scanners(ids=ascanIds,
                                      scanpolicyname=scanPolicyName))
    else:
        # Enable all active scanners
        pprint('Enable all scanners -> ' +
                ascan.enable_all_scanners(scanpolicyname=scanPolicyName))
        # Disable some active scanners
        pprint('Disable given scan IDs -> ' +
                ascan.disable_scanners(ids=ascanIds,
                                       scanpolicyname=scanPolicyName))
else:
    print('No custom policy used for scan')
    scanPolicyName = None

# Open URL inside ZAP
pprint('Access target URL ' + target)
core.access_url(url=target, followredirects=True)
for url in applicationURL:
    pprint('Access URL ' + url)
    core.access_url(url=url, followredirects=True)
# Give the sites tree a chance to get updated
time.sleep(2)

# Launch Spider, Ajax Spider (if useAjaxSpider is set to true) and
# Active scans, with a context and users or not
forcedUser = zap.forcedUser
spider = zap.spider
ajax = zap.ajaxSpider
scanId = 0
print('Starting Scans on target: ' + target)
if useContextForScan:
    for userId in userIdList:
        print('Starting scans with User ID: ' + userId)

        # Spider the target and recursively scan every site node found
        scanId = spider.scan_as_user(contextid=contextId, userid=userId,
                url=target, maxchildren=None, recurse=True, subtreeonly=None)
        print('Start Spider scan with user ID: ' + userId +
                '. Scan ID equals: ' + scanId)
        # Give the spider a chance to start
        time.sleep(2)
        while (int(spider.status(scanId)) < 100):
            print('Spider progress: ' + spider.status(scanId) + '%')
            time.sleep(2)
        print('Spider scan for user ID ' + userId + ' completed')

        if useAjaxSpider:
            # Prepare Ajax Spider scan
            pprint('Set forced user mode enabled -> ' +
                    forcedUser.set_forced_user_mode_enabled(boolean=True))
            pprint('Set user ID: ' + userId + ' for forced user mode -> ' +
                        forcedUser.set_forced_user(contextid=contextId,
                            userid=userId))
            # Ajax Spider the target URL
            pprint('Ajax Spider the target with user ID: ' + userId + ' -> ' +
                        ajax.scan(url=target, inscope=None))
            # Give the Ajax spider a chance to start
            time.sleep(10)
            while (ajax.status != 'stopped'):
                print('Ajax Spider is ' + ajax.status)
                time.sleep(5)
            for url in applicationURL:
                # Ajax Spider every url configured
                pprint('Ajax Spider the URL: ' + url + ' with user ID: ' +
                        userId + ' -> ' +
                        ajax.scan(url=url, inscope=None))
                # Give the Ajax spider a chance to start
                time.sleep(10)
                while (ajax.status != 'stopped'):
                    print('Ajax Spider is ' + ajax.status)
                    time.sleep(5)
            pprint('Set forced user mode disabled -> ' +
                    forcedUser.set_forced_user_mode_enabled(boolean=False))
            print('Ajax Spider scan for user ID ' + userId + ' completed')

        # Launch Active Scan with the configured policy on the target url
        # and recursively scan every site node
        scanId = ascan.scan_as_user(url=target, contextid=contextId,
                userid=userId, recurse=True, scanpolicyname=scanPolicyName,
                method=None, postdata=True)
        print('Start Active Scan with user ID: ' + userId +
                '. Scan ID equals: ' + scanId)
        # Give the scanner a chance to start
        time.sleep(2)
        while (int(ascan.status(scanId)) < 100):
            print('Active Scan progress: ' + ascan.status(scanId) + '%')
            time.sleep(2)
        print('Active Scan for user ID ' + userId + ' completed')

else:
    # Spider the target and recursively scan every site node found
    scanId = spider.scan(url=target, maxchildren=None, recurse=True,
            contextname=None, subtreeonly=None)
    print('Scan ID equals ' + scanId)
    # Give the Spider a chance to start
    time.sleep(2)
    while (int(spider.status(scanId)) < 100):
        print('Spider progress ' + spider.status(scanId) + '%')
        time.sleep(2)
    print('Spider scan completed')

    if useAjaxSpider:
        # Ajax Spider the target URL
        pprint('Start Ajax Spider -> ' + ajax.scan(url=target, inscope=None))
        # Give the Ajax spider a chance to start
        time.sleep(10)
        while (ajax.status != 'stopped'):
            print('Ajax Spider is ' + ajax.status)
            time.sleep(5)
        for url in applicationURL:
            # Ajax Spider every url configured
            pprint('Ajax Spider the URL: ' + url + ' -> ' +
                    ajax.scan(url=url, inscope=None))
            # Give the Ajax spider a chance to start
            time.sleep(10)
            while (ajax.status != 'stopped'):
                print('Ajax Spider is ' + ajax.status)
                time.sleep(5)
        print('Ajax Spider scan completed')

    # Launch Active scan with the configured policy on the target url and
    # recursively scan every site node
    scanId = zap.ascan.scan(url=target, recurse=True, inscopeonly=None,
        scanpolicyname=scanPolicyName, method=None, postdata=True)
    print('Start Active scan. Scan ID equals ' + scanId)
    while (int(ascan.status(scanId)) < 100):
        print('Active Scan progress: ' + ascan.status(scanId) + '%')
        time.sleep(5)
    print('Active Scan completed')

# Give the passive scanner a chance to finish
time.sleep(5)

# If you want to retrieve alerts:
## pprint(zap.core.alerts(baseurl=target, start=None, count=None))

# To retrieve ZAP report in XML or HTML format
## print('XML report')
## core.xmlreport()
print('HTML report:')
pprint(core.htmlreport())

if shutdownOnceFinished:
    # Shutdown ZAP once finished
    pprint('Shutdown ZAP -> ' + core.shutdown())


text: "use strict"; (function f(arguments) {});

redpajama_set_name: RedPajamaGithub


text:
#ifndef __TBB_info_H
#define __TBB_info_H

#include "tbb_config.h"

#if __TBB_NUMA_SUPPORT

#include <vector>

namespace tbb {
    namespace internal {
        namespace numa_topology {
            unsigned nodes_count();
            void fill(int* indexes_array);
            int default_concurrency(int node_id);
        } //namespace numa_topology
    } // namespace internal

    typedef int numa_node_id;

    namespace info {
        inline std::vector<numa_node_id> numa_nodes() {
            std::vector<numa_node_id> nodes_indexes(tbb::internal::numa_topology::nodes_count());
            internal::numa_topology::fill(&nodes_indexes.front());
            return nodes_indexes;
        }

        inline int default_concurrency(numa_node_id id = -1) {
            return internal::numa_topology::default_concurrency(id);
        }
    } // namespace info
} // namespace tbb

#endif /*__TBB_NUMA_SUPPORT*/

#endif /*__TBB_info_H*/


text:
package CTBNCToolkit;

import java.util.*;

/**
 * @author Daniele Codecasa <codecasa.job@gmail.com>
 *
 * Class that implement a Continuous Time Bayesian Network Classifier.
 *
 * Note: the trajectory generated are sampled starting from an uniform
 * distribution. Only the class variable follow its prior all the others
 * nodes have not prior and so the uniform distribution is used (i.e. the
 * Bayesian Network that represent the prior is not implemented).
 *
 * Note: the nodes embedded the graphical structure. It is not the class
 * responsibility to check that all the node in the structure are inserted
 * in the model. This must checked outside!
 */
public class CTBNClassifier extends DiscreteModel<Double,CTDiscreteNode> implements ICTClassifier<Double, CTDiscreteNode> {

	private int nGeneratedTrajectories = 0;
	private String ext = ".csv";

	/**
	 * Base constructor
	 *
	 * @param nodeIndexing global node indexing
	 * @param modelName model name
	 * @throws IllegalArgumentException in case of illegal arguments
	 */
	public CTBNClassifier(NodeIndexing nodeIndexing, String modelName) throws IllegalArgumentException {
		super(nodeIndexing, modelName);
	}

	/**
	 * Constructor that allow to set the nodes.
	 *
	 * @param nodeIndexing global node indexing
	 * @param modelName model name
	 * @param nodesSet node set
	 * @throws IllegalArgumentException in case of illegal arguments
	 */
	public CTBNClassifier(NodeIndexing nodeIndexing, String modelName, Set<CTDiscreteNode> nodesSet) throws IllegalArgumentException {
		super(nodeIndexing, modelName, nodesSet);
	}

	@Override
	public ITrajectory<Double> generateTrajectory(double T) throws RuntimeException {

		if( T <= 0)
			throw new IllegalArgumentException("Error: illegal time value");
		if( this.getNodeIndexing().getClassIndex() == -1)
			throw new IllegalStateException("Error: class node doesn't set");

		List<Double> times = new Vector<Double>();
		List<String[]> values = new Vector<String[]>();
		// Initial state sampling
		generateInitialState(times, values);
		// Trajectory sampling
		generateTrajectory(times, values, T);

		CTTrajectory<Double> trj = new CTTrajectory<Double>(this.getNodeIndexing(), times, values);
		++nGeneratedTrajectories;
		trj.setName(this.getName() + "-trj" + nGeneratedTrajectories + this.ext);
		return trj;
	}

	/**
	 * Generate the initial state and update
	 * the trajectory information.
	 * The class is sampled using its prior,
	 * the other nodes are sampled using the
	 * uniform distribution.
	 *
	 * @param times time stamp for the trajectory
	 * @param values list of values for the trajectory
	 */
	private void generateInitialState(List<Double> times, List<String[]> values) {

		NodeIndexing nodeIndexing = this.getNodeIndexing();
		String[] s0 = new String[nodeIndexing.getNodesNumber()];
		times.add(0.0);													// generate the time stamp

		// Class sampling
		int classIndex = nodeIndexing.getClassIndex();
		CTDiscreteNode clNode = this.getClassNode();
		clNode.setEvidence(clNode.sampleState());						// sample the class
		s0[classIndex] = clNode.getCurrentState();						// add the state to the trajectory

		// Uniform sampling for the not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				CTDiscreteNode node = this.getNode(i);
				if( node == null)
					throw new RuntimeException("Error: not all the nodes defined in the general indexing are set");

				double[] pDistr = new double[node.getStatesNumber()];	// sample the initial state
				for(int j = 0; j < pDistr.length; ++j)
					pDistr[j] = 1.0 / pDistr.length;

				node.setEvidence(DiscreteModel.sample(pDistr));			// set the initial state
				s0[i] = node.getCurrentState();							// add the state to the trajectory
			}

		values.add(s0);													// add the first set of values
	}

	/**
	 * Generate a trajectory till the time T given
	 * the initial state and the class.
	 *
	 * @param times list of time jumps for the generated trajectory
	 * @param values list of value map for the generated trajectory
	 * @param T the maximum length of the trajectory
	 */
	private void generateTrajectory(List<Double> times, List<String[]> values, double T) {

		NodeIndexing nodeIndexing = this.getNodeIndexing();
		int classIndex = nodeIndexing.getClassIndex();
		LinkedList<Integer> sortedNodes = new LinkedList<Integer>();
		LinkedList<Double> sortedTimes = new LinkedList<Double>();
		LinkedList<Integer> noTimeNodes = new LinkedList<Integer>();

		// Initialize the nodes without time
		for(int i = 0; i < nodeIndexing.getNodesNumber(); ++i) {
			if( i != classIndex)
				noTimeNodes.add( i);
		}

		CTDiscreteNode tmpNode;
		double currentTime = 0.0;
		while( currentTime < T) {
			// Sample the time for the nodes without time
			while( !noTimeNodes.isEmpty()) {
				// Calculate transition time
				int tmpNodeIndex = noTimeNodes.getFirst();
				tmpNode = this.getNode( tmpNodeIndex);
				double newTime = tmpNode.sampleTransitionTime() + currentTime;
				// Sort the node using the transition time
				int index;									// find the index
				for( index = sortedTimes.size() - 1; index >= 0 && newTime < sortedTimes.get(index); --index); ++index;

				// Lists update
				sortedNodes.add(index, tmpNodeIndex);
				sortedTimes.add(index, newTime);
				noTimeNodes.removeFirst();
			}

			currentTime = sortedTimes.getFirst();
			if( currentTime > T)
				break;

			// Sample the new transition
			int tmpNodeIndex = sortedNodes.getFirst();
			tmpNode = this.getNode(tmpNodeIndex);
			int nextState = tmpNode.sampleState();
			tmpNode.setEvidence(nextState);

			// Update the trajectory
			times.add(currentTime);
			String[] newValues = new String[nodeIndexing.getNodesNumber()];
			for( int iNode = 0; iNode < nodeIndexing.getNodesNumber(); ++iNode)
				newValues[iNode] = this.getNode(iNode).getCurrentState();
			values.add(newValues);

			// Update the lists
			sortedTimes.removeFirst();							// node update
			sortedNodes.removeFirst();
			noTimeNodes.add(tmpNodeIndex);
			for(int i = 0; i < sortedNodes.size(); ++i) 		// child update
				if( tmpNode.getChildIndex( this.getNode(sortedNodes.get(i)).getName()) != null) {
					noTimeNodes.add(sortedNodes.get(i));
					sortedNodes.remove(i);
					sortedTimes.remove(i);
					--i;
				}
		}

		// Add the ending time
		String[] newValues = new String[nodeIndexing.getNodesNumber()];
		for( int iNode = 0; iNode < nodeIndexing.getNodesNumber(); ++iNode) {
			newValues[iNode] = this.getNode(iNode).getCurrentState();
			tmpNode = this.getNode( iNode);
			tmpNode.retractEvidence();
		}
		times.add(T);
		values.add(newValues);

	}

	@Override
	public CTDiscreteNode getClassNode() {

		return this.getNode(this.getNodeIndexing().getClassIndex());
	}

	@Override
	public IClassificationResult<Double> classify(IClassifyAlgorithm<Double, CTDiscreteNode> algorithm, ITrajectory<Double> trajectory) throws Exception {

		return algorithm.classify(this, trajectory);
	}

	@Override
	public IClassificationResult<Double> classify(IClassifyAlgorithm<Double, CTDiscreteNode> algorithm, ITrajectory<Double> trajectory, Double samplingInterval) throws Exception {

		return algorithm.classify(this, trajectory, samplingInterval);
	}

	@Override
	public IClassificationResult<Double> classify(IClassifyAlgorithm<Double, CTDiscreteNode> algorithm, ITrajectory<Double> trajectory, Vector<Double> timeStream) throws Exception {

		return algorithm.classify(this, trajectory, timeStream);
	}

	@Override
	public IModel<Double, CTDiscreteNode> clone() {

		NodeIndexing nodeIndexing = this.getNodeIndexing();

		CTBNClassifier clonedModel = new CTBNClassifier(nodeIndexing, this.getName());
		for(int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			clonedModel.addNode((CTDiscreteNode) this.getNode(i).clone());

		clonedModel.setStructure(this.getAdjMatrix());

		for(int i = 0; i < nodeIndexing.getNodesNumber(); ++i) {
			CTDiscreteNode node = this.getNode(i);
			CTDiscreteNode clonedNode = clonedModel.getNode(i);
			// CIM update
			for(int pE = 0; pE < clonedNode.getNumberParentsEntries(); ++pE)
				clonedNode.setCIM(pE, node.getCIM(pE).clone());
			if( node.validatedCIMs())
				clonedNode.checkCIMs();
		}

		return clonedModel;
	}

	/**
	 * Print the model in string.
	 *
	 * @return the representation of the model
	 */
	public String toString() {

		double[][] cim;
		CTDiscreteNode node;
		StringBuilder strBuilder = new StringBuilder(100000);
		NodeIndexing nodeIndexing = this.getNodeIndexing();

		// Introdution
		strBuilder.append( "-----------------------\n");
		strBuilder.append( "BAYESIAN NETWORK\n");
		strBuilder.append( "-----------------------\n");
		strBuilder.append( "BBNodes " + nodeIndexing.getNodesNumber() + "\n");

		// States
		strBuilder.append( "-----------------------\n");
		// class node
		int classIndex = nodeIndexing.getClassIndex();
		node = this.getNode(classIndex);
		strBuilder.append( node.getName() + "\t" + node.getStatesNumber() + "\n");
		// not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				node = this.getNode(i);
				strBuilder.append( node.getName() + "\t" + node.getStatesNumber() + "\n");
			}

		// T=0 structure (disconnected)
		strBuilder.append( "-----------------------\n");
		// class node
		node = this.getNode(classIndex);
		strBuilder.append( node.getName() + " 0\n");
		// not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				node = this.getNode(i);
				strBuilder.append( node.getName() + " 0\n");
			}

		// T=0 distribution (uniform distributed)
		strBuilder.append( "-----------------------\n");
		// class node
		node = this.getNode(classIndex);
		strBuilder.append( node.getName() + "\n");
		for(int s = 0; s < node.getStatesNumber(); ++s)
			strBuilder.append( 1/node.getStatesNumber() + " ");
		strBuilder.append( "\n");
		strBuilder.append( "-----------------------\n");
		// not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				node = this.getNode(i);
				strBuilder.append( node.getName() + "\n");
				for(int s = 0; s < node.getStatesNumber(); ++s)
					strBuilder.append( 1.0/node.getStatesNumber() + " ");
				strBuilder.append( "\n");
				strBuilder.append( "-----------------------\n");
			}

		// Structure (parental relation)
		strBuilder.append( "-----------------------\n");
		strBuilder.append( "DIRECTED GRAPH \n");
		strBuilder.append( "-----------------------\n");
		// class node
		node = this.getNode(classIndex);
		strBuilder.append( node.getName() + "\t");
		for( int pi = 0; pi < node.getParentsNumber(); ++pi)
			strBuilder.append( node.getParent(pi).getName() + "\t");
		strBuilder.append( "0\n");
		// not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				node = this.getNode(i);
				strBuilder.append( node.getName() + "\t");
				for( int pi = 0; pi < node.getParentsNumber(); ++pi)
					strBuilder.append( node.getParent(pi).getName() + "\t");
					strBuilder.append( "0\n");
			}
		strBuilder.append( "-----------------------\n");

		// CIMs
		strBuilder.append( "-----------------------\n");
		strBuilder.append( "CIMS\n");
		strBuilder.append( "-----------------------\n");
		// class node
		node = this.getNode(classIndex);
		strBuilder.append( node.getName() + "\n");
		for( int pE = 0; pE < node.getNumberParentsEntries(); ++pE) {
			cim = node.getCIM(pE);
			strBuilder.append( toStringCIM(cim) + "\n");
		}
		strBuilder.append( "-----------------------\n");
		// not class nodes
		for( int i = 0; i < nodeIndexing.getNodesNumber(); ++i)
			if( i != classIndex) {
				node = this.getNode(i);
				strBuilder.append( node.getName() + "\n");
				for( int pE = 0; pE < node.getNumberParentsEntries(); ++pE) {
					cim = node.getCIM(pE);
					strBuilder.append( toStringCIM(cim) + "\n");
				}
				strBuilder.append( "-----------------------\n");
			}

		return strBuilder.toString();
	}

	/**
	 * Print in a row the CIM.
	 *
	 * @param cim the CIM to print
	 * @return string of the result
	 */
	private static String toStringCIM(double[][] cim) {

		StringBuilder strBuilder = new StringBuilder(500);

		for(int i = 0; i < cim.length; ++i) {
			for(int j = 0; j < cim[0].length; ++j)
				strBuilder.append( cim[i][j] + " ");
		}

		return strBuilder.toString();
	}

}


text:
layout: page
title: "MUSC 5071: Post-tonal Theory and Analysis I Statistics"
comments: true
description: "blanks"
keywords: "MUSC,5071,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 0.43%

**Percent incomplete**: 0.51%

**Average grade** (4.0 scale): 3.64

**Standard deviation in grades** (4.0 scale): 0.12

**Average workload** (raw): 2.61

**Standard deviation in workload** (raw): 0.26

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.34

**Standard deviation in course rating** (6 point scale): 0.63

**Average instructor rating** (6 point scale): 5.49

**Standard deviation in instructor rating** (6 point scale): 0.77

**Instructors**: Philip Chang, Daphne Leong, Paul Miller

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2007, Fall 2007, Fall 2008, Fall 2009, Spring 2010, Fall 2010, Spring 2011, Fall 2011, Spring 2012, Fall 2012, Spring 2013, Fall 2013, Fall 2014, Spring 2015, Fall 2015, Spring 2016, Fall 2016

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 18

**Department**: MUSC

**College**: College of Music

**Level**: Masters

**Activity**: LEC - Lecture


text:
"""
    MiniTwit Tests
    ~~~~~~~~~~~~~~

    Tests the MiniTwit application.

    :copyright: (c) 2014 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import os
import minitwit
import unittest
import tempfile

class MiniTwitTestCase(unittest.TestCase):

    def setUp(self):
        """Before each test, set up a blank database"""
        self.db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()
        self.app = minitwit.app.test_client()
        minitwit.init_db()

    def tearDown(self):
        """Get rid of the database again after each test."""
        os.close(self.db_fd)
        os.unlink(minitwit.app.config['DATABASE'])

    # helper functions

    def register(self, username, password, password2=None, email=None):
        """Helper function to register a user"""
        if password2 is None:
            password2 = password
        if email is None:
            email = username + '@example.com'
        return self.app.post('/register', data={
            'username':     username,
            'password':     password,
            'password2':    password2,
            'email':        email,
        }, follow_redirects=True)

    def login(self, username, password):
        """Helper function to login"""
        return self.app.post('/login', data={
            'username': username,
            'password': password
        }, follow_redirects=True)

    def register_and_login(self, username, password):
        """Registers and logs in in one go"""
        self.register(username, password)
        return self.login(username, password)

    def logout(self):
        """Helper function to logout"""
        return self.app.get('/logout', follow_redirects=True)

    def add_message(self, text):
        """Records a message"""
        rv = self.app.post('/add_message', data={'text': text},
                                    follow_redirects=True)
        if text:
            assert b'Your message was recorded' in rv.data
        return rv

    # testing functions

    def test_register(self):
        """Make sure registering works"""
        rv = self.register('user1', 'default')
        assert b'You were successfully registered ' \
               b'and can login now' in rv.data
        rv = self.register('user1', 'default')
        assert b'The username is already taken' in rv.data
        rv = self.register('', 'default')
        assert b'You have to enter a username' in rv.data
        rv = self.register('meh', '')
        assert b'You have to enter a password' in rv.data
        rv = self.register('meh', 'x', 'y')
        assert b'The two passwords do not match' in rv.data
        rv = self.register('meh', 'foo', email='broken')
        assert b'You have to enter a valid email address' in rv.data

    def test_login_logout(self):
        """Make sure logging in and logging out works"""
        rv = self.register_and_login('user1', 'default')
        assert b'You were logged in' in rv.data
        rv = self.logout()
        assert b'You were logged out' in rv.data
        rv = self.login('user1', 'wrongpassword')
        assert b'Invalid password' in rv.data
        rv = self.login('user2', 'wrongpassword')
        assert b'Invalid username' in rv.data

    def test_message_recording(self):
        """Check if adding messages works"""
        self.register_and_login('foo', 'default')
        self.add_message('test message 1')
        self.add_message('<test message 2>')
        rv = self.app.get('/')
        assert b'test message 1' in rv.data
        assert b'<test message 2>' in rv.data

    def test_timelines(self):
        """Make sure that timelines work"""
        self.register_and_login('foo', 'default')
        self.add_message('the message by foo')
        self.logout()
        self.register_and_login('bar', 'default')
        self.add_message('the message by bar')
        rv = self.app.get('/public')
        assert b'the message by foo' in rv.data
        assert b'the message by bar' in rv.data

        # bar's timeline should just show bar's message
        rv = self.app.get('/')
        assert b'the message by foo' not in rv.data
        assert b'the message by bar' in rv.data

        # now let's follow foo
        rv = self.app.get('/foo/follow', follow_redirects=True)
        assert b'You are now following "foo"' in rv.data

        # we should now see foo's message
        rv = self.app.get('/')
        assert b'the message by foo' in rv.data
        assert b'the message by bar' in rv.data

        # but on the user's page we only want the user's message
        rv = self.app.get('/bar')
        assert b'the message by foo' not in rv.data
        assert b'the message by bar' in rv.data
        rv = self.app.get('/foo')
        assert b'the message by foo' in rv.data
        assert b'the message by bar' not in rv.data

        # now unfollow and check if that worked
        rv = self.app.get('/foo/unfollow', follow_redirects=True)
        assert b'You are no longer following "foo"' in rv.data
        rv = self.app.get('/')
        assert b'the message by foo' not in rv.data
        assert b'the message by bar' in rv.data

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pl.arivo</groupId>
    <artifactId>java-xml-image-generator</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>


text:
namespace hiaux {

HttpResponse::HttpResponse(int _code, const std::string &_body):
code(_code),
body(_body) {

}

void HttpResponse::setCookie(const std::string &_name, const std::string &_value) {

	headers.push_back(std::string("Set-Cookie: ") + _name + "=" + _value + "; expires=Sat, 31 Dec 2039 23:59:59 GMT");
}

void HttpResponse::addHeader(const std::string &_header) {

	headers.push_back(_header);
}

}


text:
/*	$NetBSD: asm.h,v 1.30 2019/01/27 04:52:07 dholland Exp $	*/

/*-
 * Copyright (c) 2014 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Matt Thomas of 3am Software Foundry.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _AARCH64_ASM_H_
#define _AARCH64_ASM_H_

#define _C_LABEL(x) x

#define EXPORT(x)                                                              \
  .globl _C_LABEL(x);                                                          \
  _C_LABEL(x) :

#define _SENTRY(x)                                                             \
  .align 2;                                                                    \
  .type x, @function;                                                          \
  x:
#define _ENTRY(x)                                                              \
  .globl x;                                                                    \
  _SENTRY(x)
#define _END(x) .size x, .- x

#ifdef GPROF
#define _PROF_PROLOGUE                                                         \
  mov x9, x30;                                                                 \
  bl __mcount
#else
#define _PROF_PROLOGUE
#endif

/* Global procedure start. */
#define ENTRY(y)                                                               \
  .text;                                                                       \
  _ENTRY(_C_LABEL(y));                                                         \
  .cfi_startproc;                                                              \
  _PROF_PROLOGUE
/* As above, without profiling. */
#define ENTRY_NP(y)                                                            \
  .text;                                                                       \
  _ENTRY(_C_LABEL(y));                                                         \
  .cfi_startproc
/* Local procedure start. */
#define SENTRY(y)                                                              \
  .text;                                                                       \
  _SENTRY(_C_LABEL(y));                                                        \
  .cfi_startproc;                                                              \
  _PROF_PROLOGUE
/* End of any procedure. */
#define END(y)                                                                 \
  .cfi_endproc;                                                                \
  _END(_C_LABEL(y))

#define fp x29
#define lr x30

/*
 * Add a speculation barrier after the 'eret'. Some aarch64 cpus speculatively
 * execute instructions after 'eret', and this potentiates side-channel attacks.
 */
#define ERET                                                                   \
  eret;                                                                        \
  dsb sy;                                                                      \
  isb

#endif /* !_AARCH64_ASM_H_ */


text:
<?php

namespace Ongoing;

class ReceivedInOrder
{

    /**
     * @var ReceivedInOrderInfoClass $InOrderInfo
     */
    protected $InOrderInfo = null;

    /**
     * @var ReceivedInOrderSupplier $InOrderSupplier
     */
    protected $InOrderSupplier = null;

    /**
     * @var GoodsOwner $GoodsOwner
     */
    protected $GoodsOwner = null;

    /**
     * @var WsiSystem $WsiSystem
     */
    protected $WsiSystem = null;

    /**
     * @var ArrayOfReceivedInOrderLine $ReceivedInOrderLines
     */
    protected $ReceivedInOrderLines = null;

    /**
     * @var ArrayOfReceivedArticlItem $ReceivedArticleItems
     */
    protected $ReceivedArticleItems = null;

    public function __construct()
    {

    }

    /**
     * @return ReceivedInOrderInfoClass
     */
    public function getInOrderInfo()
    {
      return $this->InOrderInfo;
    }

    /**
     * @param ReceivedInOrderInfoClass $InOrderInfo
     * @return \Ongoing\ReceivedInOrder
     */
    public function setInOrderInfo($InOrderInfo)
    {
      $this->InOrderInfo = $InOrderInfo;
      return $this;
    }

    /**
     * @return ReceivedInOrderSupplier
     */
    public function getInOrderSupplier()
    {
      return $this->InOrderSupplier;
    }

    /**
     * @param ReceivedInOrderSupplier $InOrderSupplier
     * @return \Ongoing\ReceivedInOrder
     */
    public function setInOrderSupplier($InOrderSupplier)
    {
      $this->InOrderSupplier = $InOrderSupplier;
      return $this;
    }

    /**
     * @return GoodsOwner
     */
    public function getGoodsOwner()
    {
      return $this->GoodsOwner;
    }

    /**
     * @param GoodsOwner $GoodsOwner
     * @return \Ongoing\ReceivedInOrder
     */
    public function setGoodsOwner($GoodsOwner)
    {
      $this->GoodsOwner = $GoodsOwner;
      return $this;
    }

    /**
     * @return WsiSystem
     */
    public function getWsiSystem()
    {
      return $this->WsiSystem;
    }

    /**
     * @param WsiSystem $WsiSystem
     * @return \Ongoing\ReceivedInOrder
     */
    public function setWsiSystem($WsiSystem)
    {
      $this->WsiSystem = $WsiSystem;
      return $this;
    }

    /**
     * @return ArrayOfReceivedInOrderLine
     */
    public function getReceivedInOrderLines()
    {
      return $this->ReceivedInOrderLines;
    }

    /**
     * @param ArrayOfReceivedInOrderLine $ReceivedInOrderLines
     * @return \Ongoing\ReceivedInOrder
     */
    public function setReceivedInOrderLines($ReceivedInOrderLines)
    {
      $this->ReceivedInOrderLines = $ReceivedInOrderLines;
      return $this;
    }

    /**
     * @return ArrayOfReceivedArticlItem
     */
    public function getReceivedArticleItems()
    {
      return $this->ReceivedArticleItems;
    }

    /**
     * @param ArrayOfReceivedArticlItem $ReceivedArticleItems
     * @return \Ongoing\ReceivedInOrder
     */
    public function setReceivedArticleItems($ReceivedArticleItems)
    {
      $this->ReceivedArticleItems = $ReceivedArticleItems;
      return $this;
    }

}


text:
package declared

import (
	"testing"

	"github.com/pkg/errors"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"kpt.dev/configsync/pkg/core"
	"kpt.dev/configsync/pkg/kinds"
	"kpt.dev/configsync/pkg/status"
	"kpt.dev/configsync/pkg/testing/fake"
)

func TestDontDeleteAllNamespaces(t *testing.T) {
	testCases := []struct {
		name     string
		previous []string
		current  []string
		want     status.Error
	}{
		{
			name:     "zero to zero",
			previous: []string{},
			current:  []string{},
		},
		{
			name:     "zero to one",
			previous: []string{},
			current:  []string{"foo"},
		},
		{
			name:     "zero to two",
			previous: []string{},
			current:  []string{"foo", "bar"},
		},
		{
			name:     "one to zero",
			previous: []string{},
			current:  []string{},
		},
		{
			name:     "one to one",
			previous: []string{"foo"},
			current:  []string{"foo"},
		},
		{
			name:     "one to two",
			previous: []string{"foo"},
			current:  []string{"foo", "bar"},
		},
		{
			name:     "two to zero",
			previous: []string{"foo", "bar"},
			current:  []string{},
			want:     DeleteAllNamespacesError([]string{"foo", "bar"}),
		},
		{
			name:     "two to one",
			previous: []string{"foo", "bar"},
			current:  []string{"foo"},
		},
		{
			name:     "two to two",
			previous: []string{"foo", "bar"},
			current:  []string{"foo", "bar"},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			previous := make(map[core.ID]*unstructured.Unstructured)
			for _, p := range tc.previous {
				u := fake.UnstructuredObject(kinds.Namespace(), core.Name(p))
				previous[core.IDOf(u)] = u
			}
			current := make(map[core.ID]*unstructured.Unstructured)
			for _, c := range tc.current {
				u := fake.UnstructuredObject(kinds.Namespace(), core.Name(c))
				current[core.IDOf(u)] = u
			}

			got := deletesAllNamespaces(previous, current)
			if !errors.Is(got, tc.want) {
				t.Errorf("got deletesAllNamespaces() = %v, want %v", got, tc.want)
			}
		})
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
{{# class="no-js" needed for modernizr }}
{{theme=response.s3.theme}}
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
{{# Always force latest IE rendering engine (even in intranet) & Chrome Frame }}
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>
{{try:}}{{title #Test Title}}
 {{=settings.get_system_name_short()}}:  {{=title}}
{{except:}}{{=settings.get_system_name()}}{{pass}}
</title>
{{if response.refresh:}}{{=XML(response.refresh)}}{{pass}}
{{# http://dev.w3.org/html5/markup/meta.name.html }}
<meta name="application-name" content="{{=appname}}" />
{{# Set your site up with Google: http://google.com/webmasters }}
{{# <meta name="google-site-verification" content="" /> }}
{{a=""" """}}
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

 {{=T("Countries")}}

 {{=T("Organizations")}}

  {{=T("More")}}

 {{=T("Camps")}}

 {{=T("Contact Directory")}}

 {{=T("Demographics")}}

 {{=T("Documents")}}

 {{=T("Health Facilities")}}

       {{get_vars = request.get_vars}}
       {{language = response.s3.language}}
       {{icon = {"ar":"icon-check"}.get(language, "icon-check-empty")}}
       {{lang_vars = dict(_language="ar")}}{{for var in get_vars:}}{{if var != "_language":}}{{lang_vars[var] = get_vars[var]}}{{pass}}{{pass}}

 العربية

       {{icon = {"en":"icon-check"}.get(language, "icon-check-empty")}}
       {{lang_vars = dict(_language="en")}}{{for var in get_vars:}}{{if var != "_language":}}{{lang_vars[var] = get_vars[var]}}{{pass}}{{pass}}

 English

{{is_logged_in=auth.is_logged_in()}}
      {{if is_logged_in and auth.s3_has_role("ADMIN"):}}

 {{=T("Admin")}}

      {{pass}}
      {{if is_logged_in:}}

 {{=T("Contact People")}}

 {{=auth.user.email}}

      {{pass}}
      {{if is_logged_in:}}

 {{=T("Change Password")}}

 {{=T("Logout")}}

       {{else:}}

 {{=T("Login")}}

       {{pass}}

  {{if response.error:}}
<button type='button' class='close' data-dismiss='alert'>×</button>{{=response.error}}
{{pass}}
  {{if response.warning:}}
<button type='button' class='close' data-dismiss='alert'>×</button>{{=response.warning}}
{{pass}}
  {{if response.information:}}
<button type='button' class='close' data-dismiss='alert'>×</button>{{=response.information}}
{{pass}}
  {{if response.confirmation:}}
<button type='button' class='close' data-dismiss='alert'>×</button>{{=response.confirmation}}
{{pass}}
  {{if response.flash:}}
<button type='button' class='close' data-dismiss='alert'>×</button>{{=response.flash}}
{{pass}}

 {{include}}

  {{include "../private/templates/%s/views/footer.html" % response.s3.theme}}
  {{if s3.debug:}}{{=s3.toolbar()}}{{pass}}

{{pass}}
{{include "bootstrap_js.html"}}
{{include "scripts.html"}}


text:
include(${RunCMake_SOURCE_DIR}/check.cmake)

test_property(${EXPECTED_MYTEST_NAME} CPACK_TEST_PROP2 PROP_VALUE2)


text:
> Testing your plugin is the only way to ensure quality. It brings confidence to your users and makes your life easier.

[Writing a Plugin](README.md) > Testing

## Tooling

Most plugins use [mocha](https://github.com/visionmedia/mocha),[should](https://github.com/visionmedia/should.js) and [event-stream](https://github.com/dominictarr/event-stream) to help them test. The following examples will use these tools.

## Testing plugins for streaming mode

```js
var assert = require('assert');
var es = require('event-stream');
var File = require('vinyl');
var prefixer = require('../');

describe('gulp-prefixer', function() {
  describe('in streaming mode', function() {

    it('should prepend text', function(done) {

      // create the fake file
      var fakeFile = new File({
        contents: es.readArray(['stream', 'with', 'those', 'contents'])
      });

      // Create a prefixer plugin stream
      var myPrefixer = prefixer('prependthis');

      // write the fake file to it
      myPrefixer.write(fakeFile);

      // wait for the file to come back out
      myPrefixer.once('data', function(file) {
        // make sure it came out the same way it went in
        assert(file.isStream());

        // buffer the contents to make sure it got prepended to
        file.contents.pipe(es.wait(function(err, data) {
          // check the contents
          assert.equal(data, 'prependthisstreamwiththosecontents');
          done();
        }));
      });

    });

  });
});
```

## Testing plugins for buffer mode

```js
var assert = require('assert');
var es = require('event-stream');
var File = require('vinyl');
var prefixer = require('../');

describe('gulp-prefixer', function() {
  describe('in buffer mode', function() {

    it('should prepend text', function(done) {

      // create the fake file
      var fakeFile = new File({
        contents: new Buffer('abufferwiththiscontent')
      });

      // Create a prefixer plugin stream
      var myPrefixer = prefixer('prependthis');

      // write the fake file to it
      myPrefixer.write(fakeFile);

      // wait for the file to come back out
      myPrefixer.once('data', function(file) {
        // make sure it came out the same way it went in
        assert(file.isBuffer());

        // check the contents
        assert.equal(file.contents.toString('utf8'), 'prependthisabufferwiththiscontent');
        done();
      });

    });

  });
});
```

## Some plugins with high-quality Testing

* [gulp-cat](https://github.com/ben-eb/gulp-cat/blob/master/test.js)
* [gulp-concat](https://github.com/wearefractal/gulp-concat/blob/master/test/main.js)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.cassandra.utils Class Hierarchy (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.cassandra.utils

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.cassandra.dht.AbstractBounds<T> (implements java.io.Serializable)

org.apache.cassandra.dht.Range<T> (implements java.lang.Comparable<T>, java.io.Serializable)

org.apache.cassandra.utils.MerkleTree.TreeRange

org.apache.cassandra.utils.MerkleTree.TreeDifference

org.apache.cassandra.utils.Allocator

org.apache.cassandra.utils.HeapAllocator

org.apache.cassandra.utils.SlabAllocator

org.apache.cassandra.utils.AlwaysPresentFilter (implements org.apache.cassandra.utils.IFilter)

org.apache.cassandra.utils.BackgroundActivityMonitor

org.apache.cassandra.utils.BackgroundActivityMonitor.BackgroundActivityReporter (implements java.lang.Runnable)

org.yaml.snakeyaml.representer.BaseRepresenter

org.yaml.snakeyaml.representer.Representer

org.apache.cassandra.utils.SkipNullRepresenter

org.apache.cassandra.utils.BiMultiValMap<K,V> (implements java.util.Map<K,V>)

org.apache.cassandra.utils.SortedBiMultiValMap<K,V>

org.apache.cassandra.utils.BloomFilter (implements org.apache.cassandra.utils.IFilter)

org.apache.cassandra.utils.Murmur3BloomFilter

org.apache.cassandra.utils.BooleanSerializer (implements org.apache.cassandra.io.IVersionedSerializer<T>)

org.apache.cassandra.utils.ByteBufferUtil

org.apache.cassandra.utils.BytesReadTracker (implements java.io.DataInput)

org.apache.cassandra.utils.CLibrary

org.apache.cassandra.utils.ConcurrentBiMap<K,V> (implements java.util.Map<K,V>)

org.apache.cassandra.utils.CounterId (implements java.lang.Comparable<T>)

org.apache.cassandra.utils.CounterId.CounterIdRecord

org.apache.cassandra.utils.CounterId.OneShotRenewer

org.apache.cassandra.utils.DefaultDouble

org.apache.cassandra.utils.DefaultInteger

org.apache.cassandra.utils.EstimatedHistogram

org.apache.cassandra.utils.EstimatedHistogram.EstimatedHistogramSerializer (implements org.apache.cassandra.io.ISerializer<T>)

org.apache.cassandra.utils.ExpiringMap<K,V>

org.apache.cassandra.utils.ExpiringMap.CacheableObject<T>

org.apache.cassandra.utils.FBUtilities

org.apache.cassandra.utils.FilterFactory

org.apache.cassandra.utils.GuidGenerator

org.apache.cassandra.utils.Hex

org.apache.cassandra.utils.HistogramBuilder

org.apache.cassandra.utils.Interval<C,D>

org.apache.cassandra.utils.IntervalTree<C,D,I> (implements java.lang.Iterable<T>)

org.apache.cassandra.utils.IntervalTree.Serializer<C,D,I> (implements org.apache.cassandra.io.IVersionedSerializer<T>)

org.apache.cassandra.utils.LatencyTracker

org.apache.cassandra.utils.MD5Digest

org.apache.cassandra.utils.MergeIterator.Candidate<In> (implements java.lang.Comparable<T>)

org.apache.cassandra.utils.MergeIterator.Reducer<In,Out>

org.apache.cassandra.utils.MerkleTree (implements java.io.Serializable)

org.apache.cassandra.utils.MerkleTree.MerkleTreeSerializer (implements org.apache.cassandra.io.IVersionedSerializer<T>)

org.apache.cassandra.utils.MerkleTree.RowHash

org.apache.cassandra.utils.Murmur3BloomFilter.Murmur3BloomFilterSerializer

org.apache.cassandra.utils.MurmurHash

org.apache.cassandra.utils.Mx4jTool

org.apache.cassandra.utils.ObjectSizes

org.apache.cassandra.utils.OutputHandler.LogOutput (implements org.apache.cassandra.utils.OutputHandler)

org.apache.cassandra.utils.OutputHandler.SystemOutput (implements org.apache.cassandra.utils.OutputHandler)

org.apache.cassandra.utils.Pair<T1,T2>

org.apache.cassandra.utils.PureJavaCrc32 (implements java.util.zip.Checksum)

org.apache.cassandra.utils.ResourceWatcher

org.apache.cassandra.utils.ResourceWatcher.WatchedResource (implements java.lang.Runnable)

org.apache.cassandra.utils.RMIServerSocketFactoryImpl (implements java.rmi.server.RMIServerSocketFactory)

org.apache.cassandra.utils.SemanticVersion (implements java.lang.Comparable<T>)

org.apache.cassandra.utils.SimpleCondition (implements java.util.concurrent.locks.Condition)

org.apache.cassandra.utils.StatusLogger

org.apache.cassandra.utils.StreamingHistogram

org.apache.cassandra.utils.StreamingHistogram.StreamingHistogramSerializer (implements org.apache.cassandra.io.ISerializer<T>)

com.google.common.collect.UnmodifiableIterator<E> (implements java.util.Iterator<E>)

com.google.common.collect.AbstractIterator<T>

org.apache.cassandra.utils.MergeIterator<In,Out> (implements org.apache.cassandra.utils.IMergeIterator<In,Out>)

org.apache.cassandra.utils.MerkleTree.TreeRangeIterator (implements java.lang.Iterable<T>, com.google.common.collect.PeekingIterator<E>)

org.apache.cassandra.utils.UUIDGen

org.apache.cassandra.utils.UUIDSerializer (implements org.apache.cassandra.io.IVersionedSerializer<T>)

org.apache.cassandra.utils.WrappedRunnable (implements java.lang.Runnable)

Interface Hierarchy

java.lang.AutoCloseable

java.io.Closeable

org.apache.cassandra.utils.CloseableIterator<T> (also extends java.util.Iterator<E>)

org.apache.cassandra.utils.IMergeIterator<In,Out>

org.apache.cassandra.utils.IFilter

java.util.Iterator<E>

org.apache.cassandra.utils.BatchRemoveIterator<T>

org.apache.cassandra.utils.CloseableIterator<T> (also extends java.io.Closeable)

org.apache.cassandra.utils.IMergeIterator<In,Out>

org.apache.cassandra.utils.ObjectSizes.MemoryLayoutSpecification

org.apache.cassandra.utils.OutputHandler

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
#ifndef PUSHCONSTDATA_H
#define PUSHCONSTDATA_H

#include "../00_commons/glm/glm/mat4x4.hpp"

/*
 * Data for push constants
 */
struct PushConstData
{
	glm::mat4 projMatrix;
	float animationTime = 0;
};

#endif // PUSHCONSTDATA_H


text:
/**
 * @author bh-lay
 *
 * @github: https://github.com/bh-lay/Selection
 *
 * @modified 2014-6-9 11:22
 *
 */
define(function(doc){
	//set
	var setPosition = (function() {
		var textarea = doc.createElement("textarea");
		if (textarea.setSelectionRange) {
			return function(tarea,start, len) {
				var len = len || 0;
				setTimeout(function(){
					tarea.focus();
					tarea.setSelectionRange(start,start+len);
				});
			}
		} else if (textarea.createTextRange) {//IE
			return function(tarea,start, len) {
				var len = len || 0;
				tarea.focus();
				var strLen = tarea.value.length;
				var rng = tarea.createTextRange();
				rng.moveStart('character', start);
				rng.moveEnd('character', start + len - strLen);
				rng.select();
			}
		}
	})();
	//get
	var getPosition = (function(){
		var textarea = doc.createElement("textarea");
		if(typeof(textarea.selectionStart)=='number'){ //not IE
			return function(tarea){

				return [tarea.selectionStart,tarea.selectionEnd,tarea.value.slice(tarea.selectionStart,tarea.selectionEnd)];
			}
		}else{ //IE
			return function(tarea){
				var start = 0,
					 end = 0;
				tarea.focus();
				var sTextRange = doc.selection.createRange();

				if (tarea.tagName == "TEXTAREA") {
					var oTextRange = doc.body.createTextRange();
					oTextRange.moveToElementText(tarea);
					for (start = 0; oTextRange.compareEndPoints("StartToStart", sTextRange) < 0; start++) {
						oTextRange.moveStart('character', 1);
					}
					for (var i = 0; i <= start; i++) {
						if (tarea.value.charAt(i) == '\n') {
							start++;
						}
					}
					oTextRange.moveToElementText(tarea);
					for (end = 0; oTextRange.compareEndPoints('StartToEnd', sTextRange) < 0; end++) {
						oTextRange.moveStart('character', 1);
					}
					for(var i = 0; i <= end; i++) {
						if(tarea.value.charAt(i) == '\n') {
							end++;
						}
					}
				}
				return [start,end,selectedTxt,tarea.value.slice(start,end)];
			}
		}
	})();

	/**
	 * @method insertTxt
	 * @param {Object} dom jquery dom
	 * @param {String} text
	 * @param {Number} [start]
	 * @param {Number} [end]
	 *
	 **/
	function insertTxt(tarea,txt,start,end){
		if(tarea.tagName != 'TEXTAREA' || typeof(txt) == 'undefined'){
			return
		}
		var txt = txt.toString();
		var this_start,this_end;
		if(typeof(start) == 'undefined'){
			var pos = getPosition(tarea);

			this_start = pos[0];
			this_end = pos[1];
		}else{
			this_start = parseInt(start);
			this_end = end || this_start;
		}

		var allTxt = tarea.value,
			frontTxt = allTxt.slice(0,this_start),
			 endTxt = allTxt.slice(this_end);
		tarea.value = frontTxt + txt + endTxt;

		setPosition(tarea ,frontTxt.length + txt.length,0);
	};

	//exports
	return {
		insertTxt : insertTxt,
		Selection : Selection,
		setPosition : setPosition,
		getPosition : getPosition
	};
});


text:
/**
 * @jsx React.DOM
 */

var React = require('react');
var Actions = require('../actions/Actions');
var ErrorMessage = require('./ErrorMessage.react');

var ENTER_KEY = 13;

var NewComment = React.createClass({

  _spotPost: undefined,
  _opState: undefined,

  _onClickComment: function(event) {
    event.preventDefault();
    Actions.comment(this._spotPost.id);
  },

  _onClickCancel: function(event) {
    event.preventDefault();
    Actions.cancelEdit();
  },

  _onClickSubmit: function(event) {
    event.preventDefault();
    this._submit();
  },

  _submit: function() {
    Actions.submitComment(this._spotPost.id, this.refs.content.state.value);
  },

  _clearError: function() {
    var error = this._opState.edit.errorMessage;
    if (error !== undefined && error !== null) {
      Actions.clearEditError();
    }
  },

  _onKeyDown: function(event) {
    this._clearError();
    if (event.keyCode === ENTER_KEY) {
      this._submit();
    }
  },

  _clear: function() {
    this._clearError();
    this.refs.content.setState({
      value: null
    });
  },

  render: function() {
    var spotPost = this.props.spotPost;
    var opState = this.props.opState;

    this._spotPost = spotPost;
    this._opState = opState;

    var isLoading = opState.isLoading;
    var edit = opState.edit;
    if (edit.isEditing && edit.newComment && edit.spotPostId === spotPost.id) {
      var error = opState.edit.errorMessage;
      return (

            <input className="col-md-2 form-control" ref="content" type="text" onKeyDown={this._onKeyDown} placeholder="Comment" />
            <button type="button" className="btn btn-primary" onClick={this._onClickSubmit} disable={isLoading}>Post</button>
            <button type="button" className="btn btn-default" onClick={this._onClickCancel} disable={isLoading}>Cancel</button>
            <ErrorMessage error={error} />

      );
    }

    var disable = edit.isEditing || isLoading;

    return (

          <button type="button" className="btn btn-default" onClick={this._onClickComment} disable={disable}>Comment</button>

    );
  }

});

module.exports = NewComment;


text:
import pkg_resources

__version__ = pkg_resources.get_distribution("channelstream").parsed_version


text:
package org.apache.camel.component.hl7;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HL7MLLPDecoder that is aware that a HL7 message can span several buffers.
 * In addition, it avoids rescanning packets by keeping state in the IOSession.
 */
class HL7MLLPDecoder extends CumulativeProtocolDecoder {

    private static final Logger LOG = LoggerFactory.getLogger(HL7MLLPDecoder.class);
    private static final String DECODER_STATE = HL7MLLPDecoder.class.getName() + ".STATE";
    private static final String CHARSET_DECODER = HL7MLLPDecoder.class.getName() + ".charsetdecoder";

    private HL7MLLPConfig config;

    HL7MLLPDecoder(HL7MLLPConfig config) {
        this.config = config;
    }

    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

        // Get the state of the current message and
        // Skip what we have already scanned before
        DecoderState state = decoderState(session);
        in.position(state.current());

        LOG.debug("Received data, checking from position {} to {}", in.position(), in.limit());
        boolean messageDecoded = false;

        while (in.hasRemaining()) {

            int previousPosition = in.position();
            byte current = in.get();

            // Check if we are at the end of an HL7 message
            if (current == config.getEndByte2() && state.previous() == config.getEndByte1()) {
                if (state.isStarted()) {
                    // Save the current buffer pointers and reset them to surround the identifier message
                    int currentPosition = in.position();
                    int currentLimit = in.limit();
                    LOG.debug("Message ends at position {} with length {}", previousPosition, previousPosition - state.start() + 1);
                    in.position(state.start());
                    in.limit(currentPosition);
                    LOG.debug("Set start to position {} and limit to {}", in.position(), in.limit());

                    // Now create string or byte[] from this part of the buffer and restore the buffer pointers
                    try {
                        out.write(config.isProduceString()
                                ? parseMessageToString(in.slice(), charsetDecoder(session))
                                : parseMessageToByteArray(in.slice()));
                        messageDecoded = true;
                    } finally {
                        LOG.debug("Resetting to position {} and limit to {}", currentPosition, currentLimit);
                        in.position(currentPosition);
                        in.limit(currentLimit);
                        state.reset();
                    }
                } else {
                    LOG.warn("Ignoring message end at position {} until start byte has been seen.", previousPosition);
                }
            } else {
                // Check if we are at the start of an HL7 message
                if (current == config.getStartByte()) {
                    state.markStart(previousPosition);
                } else {
                    // Remember previous byte in state object because the buffer could
                    // be theoretically exhausted right between the two end bytes
                    state.markPrevious(current);
                }
                messageDecoded = false;
            }
        }

        if (!messageDecoded) {
            // Could not find a complete message in the buffer.
            // Reset to the initial position (just as nothing had been read yet)
            // and return false so that this method is called again with more data.
            LOG.debug("No complete message yet at position {}", in.position());
            state.markCurrent(in.position());
            in.position(0);
        }
        return messageDecoded;
    }

    // Make a defensive byte copy (the buffer will be reused)
    // and omit the start and the two end bytes of the MLLP message
    // returning a byte array
    private Object parseMessageToByteArray(IoBuffer buf) throws CharacterCodingException {
        int len = buf.limit() - 3;
        LOG.debug("Making byte array of length {}", len);
        byte[] dst = new byte[len];
        buf.skip(1); // skip start byte
        buf.get(dst, 0, len);
        buf.skip(2); // skip end bytes

        // Only do this if conversion is enabled
        if (config.isConvertLFtoCR()) {
            LOG.debug("Replacing LF by CR");
            for (int i = 0; i < dst.length; i++) {
                if (dst[i] == (byte) '\n') {
                    dst[i] = (byte) '\r';
                }
            }
        }
        return dst;
    }

    // Make a defensive byte copy (the buffer will be reused)
    // and omit the start and the two end bytes of the MLLP message
    // returning a String
    private Object parseMessageToString(IoBuffer buf, CharsetDecoder decoder) throws CharacterCodingException {
        int len = buf.limit() - 3;
        LOG.debug("Making string of length {} using charset {}", len, decoder.charset());
        buf.skip(1); // skip start byte
        String message = buf.getString(len, decoder);
        buf.skip(2); // skip end bytes

        // Only do this if conversion is enabled
        if (config.isConvertLFtoCR()) {
            LOG.debug("Replacing LF by CR");
            message = message.replace('\n', '\r');
        }
        return message;
    }

    @Override
    public void dispose(IoSession session) throws Exception {
        session.removeAttribute(DECODER_STATE);
        session.removeAttribute(CHARSET_DECODER);
    }

    private CharsetDecoder charsetDecoder(IoSession session) {
        synchronized (session) {
            CharsetDecoder decoder = (CharsetDecoder) session.getAttribute(CHARSET_DECODER);
            if (decoder == null) {
                decoder = config.getCharset().newDecoder()
                    .onMalformedInput(config.getMalformedInputErrorAction())
                    .onUnmappableCharacter(config.getUnmappableCharacterErrorAction());
                session.setAttribute(CHARSET_DECODER, decoder);
            }
            return decoder;
        }
    }

    private DecoderState decoderState(IoSession session) {
        synchronized (session) {
            DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE);
            if (decoderState == null) {
                decoderState = new DecoderState();
                session.setAttribute(DECODER_STATE, decoderState);
            }
            return decoderState;
        }
    }

    /**
     * Holds the state of the decoding process
     */
    private static class DecoderState {
        private int startPos = -1;
        private int currentPos;
        private byte previousByte;

        void reset() {
            startPos = -1;
            currentPos = 0;
            previousByte = 0;
        }

        void markStart(int position) {
            if (isStarted()) {
                LOG.warn("Ignoring message start at position {} before previous message has ended.", position);
            } else {
                startPos = position;
                LOG.debug("Message starts at position {}", startPos);
            }
        }

        void markCurrent(int position) {
            currentPos = position;
        }

        void markPrevious(byte previous) {
            previousByte = previous;
        }

        public int start() {
            return startPos;
        }

        public int current() {
            return currentPos;
        }

        public byte previous() {
            return previousByte;
        }

        public boolean isStarted() {
            return startPos >= 0;
        }
    }
}


text:
from src.g2p_converter import AeiouadoG2P
import argparse

def show_all_trans_simple(word, g2p_instance):

    aeiouado_trans = g2p_instance.transcribe_word_simple(word, c = 'aeiouado')
    ipa_trans = g2p_instance.transcribe_word_simple(word, c = 'ipa')
    xsampa_trans = g2p_instance.transcribe_word_simple(word, c = 'xsampa')
    spaced_xsampa_trans = g2p_instance.transcribe_word_simple(word, c = 'xsampa', space = True)
    htk_trans = g2p_instance.transcribe_word_simple(word, c = 'htk')

    print '#' * 60
    print '### Transcribing word "%s" in all conventions (simple method)' % word
    print '#' * 60
    print 'i) Aeiouado convention: %s' % aeiouado_trans.encode('utf-8')
    print 'ii) IPA: %s' % ipa_trans.encode('utf-8')
    print 'iii) X-SAMPA: %s' % xsampa_trans.encode('utf-8')
    print 'iv) spaced X-SAMPA: %s' % spaced_xsampa_trans.encode('utf-8')
    print 'v) HTK: %s' % spaced_xsampa_trans.encode('utf-8')
    print '#' * 60

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Script to test the speller over a text.')
    parser.add_argument('g2p_model_dir', help='G2P model dir')
    parser.add_argument('nlpnet_model_dir', help='nlpnet POS model dir')
    parser.add_argument('dic_file', help='dictionary with exceptions')
    parser.add_argument('conv', help='phone convention: "ipa", "xsampa", "htk" or "aeiouado"')
    parser.add_argument('wlist_input', help='word list to transcribe')
    parser.add_argument('wlist_output', help='file to save the trascribed word list')
    args = parser.parse_args()

    g2p = AeiouadoG2P(args.g2p_model_dir, args.nlpnet_model_dir, args.dic_file)

    word_trans = []
    with open(args.wlist_input) as word_list:
        for line in word_list:
            word = line.decode('utf-8').strip()
            trans = g2p.transcribe_word_simple(word, c = args.conv)
            word_trans.append((word, trans))

    with open(args.wlist_output, 'w') as output_file:
        for word, trans in word_trans:
            output_file.write('%s  %s\n'.encode('utf-8') % (word.encode('utf-8'), trans.encode('utf-8')))


text:
angular
  .module('whatsapp')
  .run(run);

function run ($ionicPlatform) {
  $ionicPlatform.ready(function () {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleLightContent();
    }
  });
}


text:
package com.java110.api.components.corder;

import com.java110.core.context.IPageData;
import com.java110.api.smo.corder.IListCordersSMO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

/**
 * 订单
 */
@Component("corderManage")
public class CorderManageComponent {
    @Autowired
    private IListCordersSMO listCordersSMOImpl;

    /**
     * 查询发布广告列表
     *
     * @param pd 页面数据封装
     * @return 返回 ResponseEntity 对象
     */
    public ResponseEntity<String> list(IPageData pd) {
        return listCordersSMOImpl.listCorders(pd);
    }

    public IListCordersSMO getListCordersSMOImpl() {
        return listCordersSMOImpl;
    }

    public void setListCordersSMOImpl(IListCordersSMO listCordersSMOImpl) {
        this.listCordersSMOImpl = listCordersSMOImpl;
    }
}


text:
SYNONYM

#### According to
IRMNG Homonym List

#### Published in
Bull. Soc. mycol. Fr. 1: 119 (1885)

#### Original name
null

### Remarks
null


text:
date: 2016-09-13T09:00:00+00:00
title: Escalations
menu:
  main:
    parent: "API"
    identifier: "api-reference-escalations-092"
    weight: 120
---
Escalation templates are static artifacts. You can save and manage escalation templates through the API, these can then be referenced in an sla and applied to each cluster in a blueprint. Read about [using escalations](/documentation/using-vamp/escalations/) and [using slas](/documentation/using-vamp/sla/).

## Actions

 * [List](/documentation/api/v0.9.2/api-escalations/#list-escalations) - return a list of all escalations
 * [Get](/documentation/api/v0.9.2/api-escalations/#get-single-escalation) - get a single escalation
 * [Create](/documentation/api/v0.9.2/api-escalations/#create-escalation) - create a new escalation
 * [Update](/documentation/api/v0.9.2/api-escalations/#update-escalation) - update a escalation
 * [Delete](/documentation/api/v0.9.2/api-escalations/#delete-escalation) - delete a escalation

## Escalation resource

The resource examples shown below are in YAML format. Vamp API requests and responses can be in JSON (default) or YAML format, see [common parameters](/documentation/api/v0.9.2/using-the-api) for details on how to set this.

### Minimum resource
The minimum fields required to successfully create an escalation.

```
- name: unique_name
  type: scale_instances
  minimum: 1
  maximum: 3
  scale_by: 1
```

### API return resource
The fields returned by the API after an escalation has been created (also visible in the UI)

```
- name: unique_name
  kind: escalation
  type: scale_instances
  target: cluster_name
  minimum: 1
  maximum: 3
  scale_by: 1

```

 Field name    | Options | Required?  | description
 -----------------|-----|------|------
 name |  -  |  Required  | A unique name to reference the escalation
 kind |  `escalation`  |  Optional  | The resource type. Required to [send multiple resources](/documentation/api/v0.9.2/api-reference/#send-multiple-resources-post-put-and-delete) to `/api/v1`
 type |  `scale_instances`, `scale_cpu`, `scale_memory`  |  Required  |  Escalation handler. Specifies what is to be scaled.
 target |    | Optional   | The target cluster to scale up/down. If not included, will default to the cluster where escalations are specified.
 minimum |    | Required  | Minimum setting.
 maximum |    | Required   |  Maximum setting.
 scale_by |    |  Required   | Increment to scale up/down by.

-----------------

## List Escalations

Return a list of all stored escalation templates. For details on pagination see [common parameters](/documentation/api/v0.9.2/using-the-api)

### Request
* `GET`
* `/api/v1/escalations`
* The request body should be empty.

### Response
If successful, will return a list of [escalation resources](/documentation/api/v0.9.2/api-escalations/#escalation-resource) in the specified `accept` format (default JSON).

-----------------

## Get single escalation

Return a the named escalation resource.

### Request
* `GET`
* `/api/v1/escalations/{escalation_name}`
* The request body should be empty.

### Response
If successful, will return the named [escalation resource](/documentation/api/v0.9.2/api-escalations/#escalation-resource) in the specified `accept` format (default JSON).

-----------------

## Create escalation

Stores a new escalation template.

### Request
* `POST`
* `/api/v1/escalations`
* The request body should include at least a mimnimum [escalation resource](/documentation/api/v0.9.2/api-escalations/#escalation-resource).
* Query string parameters:

| parameter     | options           | default          | description       |
| ------------- |:-----------------:|:----------------:| -----------------:|
| `validate_only` | true or false     | false            | validates the escalation and returns a `201 Created` if the escalation is valid.

### Response
A successful create operation has status code 201 `Created` and the response body will contain the created [escalation resource](/documentation/api/v0.9.2/api-escalations/#escalation-resource) in the specified `accept` format (default JSON).

-----------------

## Update escalation

Update a stored escalation.

### Request
* `PUT`
* `/api/v1/escalations/{escalation_name}`
* The request body should include at least a mimnimum [escalation resource](/documentation/api/v0.9.2/api-escalations/#escalation-resource). The `name` field must match the `escalation_name` specified in the request path.
* Query string parameters:

| parameter     | options           | default          | description      |
| ------------- |:-----------------:|:----------------:| ----------------:|
| `validate_only` | true or false     | false            | validates the escalation and returns a `200 OK` if the escalation is valid.

### Response
A successful update operation has status code 200 `OK` or 202 `Accepted` and the response body will contain the updated [escalation resource](/documentation/api/v0.9.2/api-escalations/#escalation-resource) in the specified `accept` format (default JSON).

-----------------

## Delete escalation

Delete a stored escalation. Note that delete operations are idempotent: sending a second request with the same content will not result in an error response (4xx).

### Request
* `DELETE`
* `/api/v1/escalations/{escalation_name}`
* The request body should be empty.
* Query string parameters:

| parameter     | options           | default          | description      |
| ------------- |:-----------------:|:----------------:| ----------------:|
| `validate_only` | true or false     | false            | returns a `204 No Content` if the escalation is valid, without actual delete of the escalation.

### Response
A successful delete operation has status code 204 `No Content` or 202 `Accepted` with an empty response body.

-----------------


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Authorization.Models;

namespace Microsoft.Azure.Management.Authorization.Models
{
    /// <summary>
    /// Role assignment list operation result.
    /// </summary>
    public partial class RoleAssignmentListResult : AzureOperationResponse
    {
        private string _nextLink;

        /// <summary>
        /// Optional. Gets or sets the URL to get the next set of role
        /// assignment results.
        /// </summary>
        public string NextLink
        {
            get { return this._nextLink; }
            set { this._nextLink = value; }
        }

        private IList<RoleAssignment> _roleAssignments;

        /// <summary>
        /// Optional. Role assignment list.
        /// </summary>
        public IList<RoleAssignment> RoleAssignments
        {
            get { return this._roleAssignments; }
            set { this._roleAssignments = value; }
        }

        /// <summary>
        /// Initializes a new instance of the RoleAssignmentListResult class.
        /// </summary>
        public RoleAssignmentListResult()
        {
            this.RoleAssignments = new LazyList<RoleAssignment>();
        }
    }
}


text:
/**
 * This package contains an implementation of a bounded {@link java.util.concurrent.ConcurrentMap} data structure.
 *

 * {@link Weigher} is a simple interface for determining how many units of capacity an entry consumes. Depending on which concrete Weigher class is
 * used, an entry may consume a different amount of space within the cache. The {@link Weighers} class provides utility methods for obtaining the most
 * common kinds of implementations.
 *

 * {@link EvictionListener} provides the ability to be notified when an entry is evicted from the map. An eviction occurs when the entry was
 * automatically removed due to the map exceeding a capacity threshold. It is not called when an entry was explicitly removed.
 *

 * The {@link ConcurrentLinkedHashMap} class supplies an efficient, scalable, thread-safe, bounded map. As with the
 * Java Collections Framework the "Concurrent" prefix is used to indicate that the map is not governed by a single exclusion lock.
 *
 * @see  http://code.google.com/p/concurrentlinkedhashmap/
 */
package mssql.googlecode.concurrentlinkedhashmap;


text:
static NSString *const WEOperationSimpleSubclassResult = @"WEOperationSimpleSubclass";

@interface WEOperationSimpleSubclass : WEOperation<NSString *>
@end

@implementation WEOperationSimpleSubclass

- (void)start
{
    dispatch_async(dispatch_get_main_queue(), ^{
        WEOperationResult<NSString *> *result = [[WEOperationResult alloc] initWithResult:WEOperationSimpleSubclassResult];
        [self completeWithResult:result];
    });
}

@end

@interface WEOperationTests : XCTestCase
@end

@implementation WEOperationTests

- (void)testSimpleOperationInitialState
{
    WEOperationSimpleSubclass *operation = [[WEOperationSimpleSubclass alloc] initWithName:@"operationName"];

    XCTAssertFalse(operation.finished);
    XCTAssertFalse(operation.active);
    XCTAssertFalse(operation.cancelled);
    XCTAssertEqualObjects(operation.name, @"operationName");
}

- (void)testSimpleOperationToCompletion
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"wait until operation completes"];
    WEOperationSimpleSubclass *operation = [[WEOperationSimpleSubclass alloc] initWithName:@"operationName"];
    [operation startWithCompletion:^(WEOperationResult<NSString *> * _Nullable result) {
        XCTAssert(operation.finished);

        WEOperationResult<NSString *> *operationResult = operation.result;
        XCTAssertNotNil(operationResult);
        XCTAssertEqualObjects(operationResult.result, WEOperationSimpleSubclassResult);

        [expectation fulfill];
    } completionQueue:dispatch_get_main_queue()];

    [self waitForExpectationsWithTimeout:0.5 handler:^(NSError *error) {
        // retain operation until completion
        (void)operation;
    }];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.hadoop.yarn.security.client (Apache Hadoop Main 2.7.3 API)</title>
<meta name="date" content="2016-08-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

@InterfaceAudience.Public

Package org.apache.hadoop.yarn.security.client

Class Summary

Class
Description

BaseClientToAMTokenSecretManager

A base SecretManager for AMs to extend and validate Client-RM tokens
 issued to clients by the RM using the underlying master-key shared by RM to
 the AMs on their launch.

ClientRMSecurityInfo

ClientTimelineSecurityInfo

ClientToAMTokenIdentifier

ClientToAMTokenSecretManager

A simple SecretManager for AMs to validate Client-RM tokens issued to
 clients by the RM using the underlying master-key shared by RM to the AMs on
 their launch.

RMDelegationTokenIdentifier

Delegation Token Identifier that identifies the delegation tokens from the
 Resource Manager.

RMDelegationTokenSelector

TimelineDelegationTokenIdentifier

TimelineDelegationTokenSelector

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2016 Apache Software Foundation. All rights reserved.


text:
require 'addressable/uri'

# MWS
module MWS
  # Query
  class Query
    attr_reader :verb, :uri, :host, :aws_access_key_id, :aws_secret_access_key, :mws_auth_token, :action, :seller_id,
                :signature_method, :signature_version, :timestamp, :version

    # rubocop:disable all
    def initialize(params = {})
      @verb = params[:verb] || 'GET'
      @uri = params[:uri] || '/'
      @host = params[:host]

      @aws_access_key_id = params[:aws_access_key_id]
      @aws_secret_access_key = params[:aws_secret_access_key]
      @mws_auth_token = params[:mws_auth_token]
      @action = params[:action].to_s.camelize.gsub(/(Sku|Asin)/i) { |_s| Regexp.last_match(1).upcase }
      @seller_id = params[:seller_id]
      @signature_method = params[:signature_method] || 'HmacSHA256'
      @signature_version = params[:signature_version] || 2
      @timestamp = params[:timestamp] || Time.now
      @version = params[:version]

      @params = params[:params]
    end

    def request_uri
      'https://' << @host << @uri << '?' << build_query(signature)
    end

    def canonical
      [@verb.to_s.upcase, @host.downcase, @uri, build_query].join("\n")
    end

    def signature
      encode_canonical(canonical)
    end

    def build_query(signature = nil)
      query = base_query(signature)

      params = Helpers.camelize_keys(@params || {})
      params = Helpers.make_structured_lists(params)
      query.merge!(params)

      # Sort hash in natural-byte order
      uri = Addressable::URI.new
      uri.query_values = Hash[Helpers.escape_date_time_params(query).sort]
      uri.query
    end

    # Helpers
    module Helpers
      def self.escape_date_time_params(params = {})
        params.map do |key, value|
          case value.class.name
          when 'Time', 'Date', 'DateTime'
            { key => value.iso8601 }
          when 'Hash'
            { key => escape_date_time_params(value) }
          else
            { key => value }
          end
        end.reduce({}, :merge)
      end

      def self.camelize_keys(params = {})
        params.map do |key, value|
          case value.class.name
          when 'Hash'
            { key.to_s.camelize => camelize_keys(value) }
          else
            { key.to_s.camelize => value }
          end
        end.reduce({}, :merge)
      end

      def self.make_structured_lists(params = {})
        params.map do |key, value|
          if key.to_s.end_with?('list')
            value[:values].each_with_index.map do |item, index|
              { "#{value[:label]}.#{index + 1}" => item }
            end.reduce({}, :merge)
          else
            { key => value }
          end
        end.reduce({}, :merge)
      end
    end

    protected

    def base_query(signature = nil)
      query = {
        'AWSAccessKeyId' => @aws_access_key_id,
        'Action' => @action,
        'SellerId' => @seller_id,
        'SignatureMethod' => @signature_method,
        'SignatureVersion' => @signature_version,
        'Timestamp' => @timestamp,
        'Version' => @version
      }
      query['MWSAuthToken'] = @mws_auth_token if @mws_auth_token
      query['Signature'] = signature if signature
      query
    end

    def encode_canonical(canonical_str)
      digest = OpenSSL::Digest.new('sha256')
      Base64.encode64(OpenSSL::HMAC.digest(digest, aws_secret_access_key, canonical_str)).strip
    end
  end
end