text:
'''
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

#!/usr/bin/python

import os
import time
import traceback
import testcase_driver
import onerror_driver
import Framework.Utils as Utils
from Framework.Utils.testcase_Utils import pNote
from Framework.Utils.print_Utils import print_info, print_error, print_debug, print_warning
from WarriorCore import testsuite_utils, common_execution_utils
import exec_type_driver

"""This is sequential testcase driver which is used to execute
the testcases of a suite in sequential order"""

def update_suite_attribs(junit_resultfile, errors, skipped,
                         tests, failures, time='0'):
    """Update suite attributes """
    testsuite_utils.pSuite_update_suite_attributes(junit_resultfile, str(errors),
                                                   str(skipped), str(tests), str(failures), time)

def execute_sequential_testcases(testcase_list, suite_repository,
                                 data_repository, from_project, auto_defects,
                                 iter_ts_sys, tc_parallel, queue, ts_iter):
    """Executes the list of cases(of a suite) in sequential order
        - Takes a testcase_list as input and sends
        each case to Basedriver for execution.
        - Computes the suite status based on the case_status
        and the impact value of the case
        - Handles case failures as per the default/specific
        onError action/value
        - Calls the function to report the suite status

    :Arguments:
        1. testcase_list(list) = List of cases to be executed
        2. suite_repository(dict) = suite repository
        3. data_repository(dict) = Warrior data repository
        4. from_project(boolean) = True for Project execution else False
        5. auto_defects(boolean) = True for Jira auto defect creation else False
        6. iter_ts_sys(string) = System for iterative execution
        7. tc_parallel(boolean) = True for Parallel execution else False
        8. queue = Python multiprocessing queue for parallel execution
        9. ts_iter(boolean) = True for 'iterative_parallel' execution else False
    :Returns:
        1. suite_status - overall suite status

    """
    goto_tc = False

    junit_resultfile = suite_repository['junit_resultfile']
    suite_name = suite_repository['suite_name']
    testsuite_filepath = suite_repository['testsuite_filepath']
    suite_error_action = suite_repository['def_on_error_action']
    suite_error_value = suite_repository['def_on_error_value']
    testsuite_dir = os.path.dirname(testsuite_filepath)
    data_repository['wt_tc_timestamp'] = None

    errors = 0
    skipped = 0
    failures = 0
    tests = 0
    tc_duration = 0
    tc_status_list = []
    tc_impact_list = []
    impact_dict = {"IMPACT": "Impact", "NOIMPACT": "No Impact"}
    tc_duration_list = []
    tc_junit_list = []

    while tests < len(testcase_list):
        testcase = testcase_list[tests]
        tests += 1

        tc_rel_path = testsuite_utils.get_path_from_xmlfile(testcase)
        if tc_rel_path is not None:
            tc_path = Utils.file_Utils.getAbsPath(tc_rel_path, testsuite_dir)
        else:
            # if tc_rel_path is None, what are we doing here?
            tc_path = str(tc_rel_path)
        print_info('\n')
        print_debug("<<<< Starting execution of Test case: {0}>>>>".
                    format(tc_path))
        action, tc_status = exec_type_driver.main(testcase)
        tc_runtype = testsuite_utils.get_runtype_from_xmlfile(testcase)
        tc_impact = Utils.testcase_Utils.get_impact_from_xmlfile(testcase)
        tc_context = Utils.testcase_Utils.get_context_from_xmlfile(testcase)
        suite_step_data_file = testsuite_utils.get_data_file_at_suite_step(
                                                testcase, suite_repository)
        tc_onError_action = Utils.xml_Utils.get_attributevalue_from_directchildnode(
                                            testcase, 'onError', 'action')
        tc_onError_action = tc_onError_action if tc_onError_action else suite_error_action
        if suite_step_data_file is not None:
            data_file = Utils.file_Utils.getAbsPath(suite_step_data_file,
                                                    testsuite_dir)
            data_repository[tc_path] = data_file
        data_repository['wt_tc_impact'] = tc_impact
        if testcase.find("runmode") is not None and \
           testcase.find("runmode").get("attempt") is not None:
            # condition to print the start of runmode execution
            if testcase.find("runmode").get("attempt") == 1:
                print_info("\n----------------- Start of Testcase Runmode Execution"
                           " -----------------\n")
            print_info("TESTCASE ATTEMPT: {0}".format(testcase.find("runmode")
                                                      .get("attempt")))
        if testcase.find("retry") is not None and \
           testcase.find("retry").get("attempt") is not None:
            print_info("TESTCASE ATTEMPT: {0}".format(testcase.find("retry")
                                                      .get("attempt")))

        if Utils.file_Utils.fileExists(tc_path) or action is False:
            tc_name = Utils.file_Utils.getFileName(tc_path)
            testsuite_utils.pSuite_testcase(junit_resultfile, suite_name,
                                            tc_name, time='0')

            if not goto_tc and action is True:
                try:
                    tc_result = testcase_driver.main(tc_path,
                                                     data_repository,
                                                     tc_context,
                                                     runtype=tc_runtype,
                                                     auto_defects=auto_defects,
                                                     suite=suite_name,
                                                     tc_onError_action=tc_onError_action,
                                                     iter_ts_sys=iter_ts_sys)

                    tc_status = tc_result[0]
                    tc_duration = tc_result[1]
                except Exception:
                    print_error('unexpected error {0}'.format(
                                                    traceback.format_exc()))
                    tc_status, tc_duration = False, False
                    tc_impact = Utils.testcase_Utils.get_impact_from_xmlfile(
                                                                    testcase)

            elif goto_tc and goto_tc == str(tests) and action is True:

                try:
                    tc_result = testcase_driver.main(tc_path,
                                                     data_repository,
                                                     tc_context,
                                                     runtype=tc_runtype,
                                                     auto_defects=auto_defects,
                                                     suite=suite_name,
                                                     tc_onError_action=tc_onError_action,
                                                     iter_ts_sys=iter_ts_sys)
                    tc_status = tc_result[0]
                    tc_duration = tc_result[1]
                    goto_tc = False

                except Exception:
                    print_error('unexpected error {0}'.format(
                                                    traceback.format_exc()))
                    tc_status, tc_duration = False, False
                    tc_impact = Utils.testcase_Utils.get_impact_from_xmlfile(
                                                                    testcase)

            else:
                print_info('skipped testcase %s ' % tc_name)
                skipped += 1
                testsuite_utils.pSuite_testcase_skip(junit_resultfile)
                testsuite_utils.pSuite_update_suite_attributes(
                                junit_resultfile, str(errors), str(skipped),
                                str(tests), str(failures), time='0')
                data_repository['wt_junit_object'].update_count(
                                "skipped", "1", "ts",
                                data_repository['wt_ts_timestamp'])
                data_repository['wt_junit_object'].update_count(
                                "tests", "1", "ts",
                                data_repository['wt_ts_timestamp'])
                data_repository['wt_junit_object'].update_count(
                                "tests", "1", "pj", "not applicable")
                tmp_timestamp = str(Utils.datetime_utils.get_current_timestamp())
                time.sleep(2)
                data_repository['wt_junit_object'].create_testcase(
                                location="from testsuite",
                                timestamp=tmp_timestamp,
                                ts_timestamp=data_repository['wt_ts_timestamp'],
                                classname=data_repository['wt_suite_name'],
                                name=os.path.splitext(tc_name)[0])
                data_repository['wt_junit_object'].add_testcase_message(
                                                    tmp_timestamp, "skipped")
                data_repository['wt_junit_object'].update_attr(
                                "status", "SKIPPED", "tc", tmp_timestamp)
                data_repository['testcase_%d_result' % tests] = "SKIP"
                if Utils.file_Utils.fileExists(tc_path):
                    title = Utils.xml_Utils.getChildTextbyParentTag(
                                            tc_path, 'Details', 'Title')
                title = title.strip() if Utils.file_Utils.fileExists(tc_path) and title else "None"
                data_repository['wt_junit_object'].update_attr(
                                "title", title, "tc", tmp_timestamp)
                data_repository['wt_junit_object'].update_attr(
                                "impact", impact_dict.get(tc_impact.upper()),
                                "tc", tmp_timestamp)
                data_repository['wt_junit_object'].update_attr(
                                "onerror", "N/A", "tc", tmp_timestamp)
                data_repository['wt_junit_object'].output_junit(
                                data_repository['wt_results_execdir'],
                                print_summary=False)
                continue

        else:
            errors += 1
            msg = print_error("Test case does not exist in the provided path: "
                              "{0}".format(tc_path))
            testsuite_utils.pSuite_testcase(junit_resultfile, suite_name,
                                            tc_path, time='0')
            testsuite_utils.pSuite_testcase_error(junit_resultfile, msg, '0')
            tc_status = "ERROR"
            if goto_tc and goto_tc == str(tests):
                goto_tc = False
            elif goto_tc and goto_tc != str(tests):
                data_repository['testcase_%d_result' % tests] = "ERROR"
                continue

        goto_tc_num = onerror_driver.main(testcase, suite_error_action,
                                          suite_error_value)
        if goto_tc_num is False:
            onerror = "Next"
        elif goto_tc_num == "ABORT":
            onerror = "Abort"
        else:
            onerror = "Goto:" + str(goto_tc_num)
        data_repository['wt_junit_object'].update_attr(
                        "impact", impact_dict.get(tc_impact.upper()), "tc",
                        data_repository['wt_tc_timestamp'])
        data_repository['wt_junit_object'].update_attr(
                        "onerror", onerror, "tc",
                        data_repository['wt_tc_timestamp'])

        tc_status_list, tc_impact_list = \
            common_execution_utils.compute_status(testcase, tc_status_list,
                                                  tc_impact_list,
                                                  tc_status, tc_impact)
        tc_duration_list.append(tc_duration)

        string_status = {"TRUE": "PASS", "FALSE": "FAIL", "ERROR": "ERROR",
                         "SKIP": "SKIP", "RAN": "RAN"}

        if str(tc_status).upper() in string_status.keys():
            data_repository['testcase_%d_result' % tests] = string_status[
                                                    str(tc_status).upper()]
        else:
            print_error("unexpected testcase status, default to exception")
            data_repository['testcase_%d_result' % tests] = "ERROR"

        if tc_impact.upper() == 'IMPACT':
            msg = "Status of the executed test case impacts Testsuite result"
        elif tc_impact.upper() == 'NOIMPACT':
            msg = "Status of the executed test case does not impact "
            "Teststuie result"
        print_debug(msg)

        runmode, value, _ = common_execution_utils.get_runmode_from_xmlfile(
                                                                testcase)
        retry_type, retry_cond, retry_cond_value, retry_value, \
            retry_interval = common_execution_utils.get_retry_from_xmlfile(testcase)
        # Adding condition to check tc_status is error or not
        if runmode is not None or tc_status == "ERROR":
            if tc_status is True:
                testsuite_utils.update_tc_duration(str(tc_duration))
                # if runmode is 'rup' & tc_status is True, skip the repeated
                # execution of same testcase and move to next actual testcase
                if runmode.upper() == "RUP":
                    goto_tc = str(value)
            elif tc_status == 'ERROR' or tc_status == 'EXCEPTION':
                errors += 1
                testsuite_utils.pSuite_testcase_error(
                            junit_resultfile,
                            'Encountered error/exception during TC execution',
                            str(tc_duration))
                goto_tc = onerror_driver.main(testcase, suite_error_action,
                                              suite_error_value)
                if goto_tc in ['ABORT', 'ABORT_AS_ERROR']:
                    update_suite_attribs(junit_resultfile, str(errors),
                                         str(skipped), str(tests),
                                         str(failures), time='0')
                    break
                # when 'onError:goto' value is less than the current tc num,
                # change the next iteration point to goto value
                elif goto_tc and int(goto_tc) < tests:
                    tests = int(goto_tc)-1
                    goto_tc = False
                # Handles the goto value is greater than total no of TC's
                if int(goto_tc) > len(testcase_list):
                    print_error("The goto value {} is more than no of TC's {} so skipping all the TC's".format(
                        goto_tc, len(testcase_list)))

            elif tc_status is False:
                failures += 1
                testsuite_utils.pSuite_testcase_failure(junit_resultfile,
                                                        time=str(tc_duration))
                goto_tc = onerror_driver.main(testcase, suite_error_action,
                                              suite_error_value)
                if goto_tc in ['ABORT', 'ABORT_AS_ERROR']:
                    update_suite_attribs(junit_resultfile, str(errors),
                                         str(skipped), str(tests),
                                         str(failures), time='0')
                    break
                # when 'onError:goto' value is less than the current tc num,
                # change the next iteration point to goto value
                elif goto_tc and int(goto_tc) < tests:
                    tests = int(goto_tc)-1
                    goto_tc = False
                # if runmode is 'ruf' & tc_status is False, skip the repeated
                # execution of same testcase and move to next actual testcase
                if not goto_tc and runmode.upper() == "RUF":
                    goto_tc = str(value)
        elif retry_type is not None:
            if retry_type.upper() == 'IF':
                try:
                    if data_repository[retry_cond] == retry_cond_value:
                        condition_met = True
                        pNote("Wait for {0}sec before retrying".format(
                                                        retry_interval))
                        pNote("The given condition '{0}' matches the expected "
                              "value '{1}'".format(data_repository[retry_cond],
                                                   retry_cond_value))
                        time.sleep(int(retry_interval))
                    else:
                        condition_met = False
                        print_warning("The condition value '{0}' does not "
                                      "match with the expected value "
                                      "'{1}'".format(
                                        data_repository[retry_cond],
                                        retry_cond_value))
                except KeyError:
                    print_warning("The given condition '{0}' is not there in "
                                  "the data repository".format(
                                                    retry_cond_value))
                    condition_met = False
                if condition_met is False:
                    goto_tc = str(retry_value)
            else:
                if retry_type.upper() == 'IF NOT':
                    try:
                        if data_repository[retry_cond] != retry_cond_value:
                            condition_met = True
                            pNote("Wait for {0}sec before retrying".format(
                                                            retry_interval))
                            pNote("The condition value '{0}' does not match "
                                  "with the expected value "
                                  "'{1}'".format(data_repository[retry_cond],
                                                 retry_cond_value))
                            time.sleep(int(retry_interval))
                        else:
                            condition_met = False
                            print_warning("The given condition '{0}' matches "
                                          "the expected value "
                                          "'{1}'".format(
                                                data_repository[retry_cond],
                                                retry_cond_value))
                    except KeyError:
                        condition_met = False
                        print_warning("The given condition '{0}' is not there "
                                      "in the data repository".format(
                                                            retry_cond_value))
                    if condition_met is False:
                        pNote("The given condition '{0}' matched with the "
                              "value '{1}'".format(data_repository[retry_cond],
                                                   retry_cond_value))
                        goto_tc = str(retry_value)
# suite_status = testsuite_utils.compute_testsuite_status(suite_status,
# tc_status, tc_impact)
        update_suite_attribs(junit_resultfile, str(errors),
                             str(skipped), str(tests), str(failures),
                             time='0')
        # junit_object/python_process is different for all the cases
        # executed in parallel
        if ts_iter is False:
            tc_junit_list.append(data_repository['wt_junit_object'])

    # junit_object/python_process is same for all the cases executed in the
    # same system for 'iterative_parallel' suite execution
    if ts_iter is True:
        tc_junit_list = data_repository['wt_junit_object']
    # print the end of runmode execution as the steps skip when the condition
    # is met for RUF/RUP or when all the attempts finish
    if testcase.find("runmode") is not None and \
       testcase.find("runmode").get("attempt") is not None:
        if testcase.find("runmode").get("attempt") == \
           testcase.find("runmode").get("runmode_val"):
            print_info("\n----------------- End of Testcase Runmode Execution"
                       " -----------------\n")
    suite_status = Utils.testcase_Utils.compute_status_using_impact(
                                        tc_status_list, tc_impact_list)

    if tc_parallel:
        tc_impact = data_repository['wt_tc_impact']
        if tc_impact.upper() == 'IMPACT':
            msg = "Status of the executed test case impacts Testsuite result"
        elif tc_impact.upper() == 'NOIMPACT':
            msg = "Status of the executed test case does not impact Teststuie result"
        print_debug(msg)
        tc_name = Utils.file_Utils.getFileName(tc_path)
        # put result into multiprocessing queue and later retrieve in
        # corresponding driver
        queue.put((tc_status_list, tc_name, tc_impact_list, tc_duration_list,
                   tc_junit_list))
    return suite_status

def main(testcase_list, suite_repository, data_repository, from_project,
         auto_defects, iter_ts_sys=None, tc_parallel=False, queue=False,
         ts_iter=False):
    """Executes testcases in a testsuite sequentially """
    try:
        testsuite_status = execute_sequential_testcases(
         testcase_list, suite_repository, data_repository, from_project,
         auto_defects, iter_ts_sys, tc_parallel, queue, ts_iter)
    except Exception:
        testsuite_status = False
        print_error('unexpected error {0}'.format(traceback.format_exc()))
    return testsuite_status


text:
using System;
using System.Threading;
using BlyncLightForSkype.Client.Interfaces;
using BlyncLightForSkype.Client.Models;

namespace BlyncLightForSkype.Client.BlyncLightBehaviours
{
    /// <summary>
    /// Behaviour that only activates blynclight during office hours
    /// </summary>
    public class BlyncLightScheduler : IBlyncLightBehaviour
    {
        #region Props

        /// <summary>
        /// Reference to BlyncLightManager object
        /// </summary>
        private BlyncLightManager blyncLighteManager;

        /// <summary>
        /// True if the light is active
        /// </summary>
        private bool blyncLightActive = false;

        private Timer startTimer;

        private Timer endTimer;

        #endregion

        #region Ctor

        public BlyncLightScheduler()
        {
            Priority = Priority.Normal;
        }

        #endregion

        #region IBlyncLightBehaviour

        public Priority Priority { get; private set; }

        public void InitBehaviour(BlyncLightManager manager)
        {
            blyncLighteManager = manager;

            if (blyncLighteManager.Logger.IsDebugEnabled)
            {
                blyncLighteManager.Logger.Debug("Initialised BlyncLightScheduler");
            }

            DateTime startTime = DateTime.Today.AddHours(7).AddMinutes(00);
            if (DateTime.Now > startTime)
            {
                if (startTime.DayOfWeek != DayOfWeek.Saturday &&
                    startTime.DayOfWeek != DayOfWeek.Sunday)
                {
                    blyncLightActive = true;
                }
            }

            DateTime endTime = DateTime.Today.AddHours(18).AddMinutes(00);
            if (DateTime.Now > endTime)
            {
                blyncLightActive = false;
            }

            UpdateBlyncLightState();
        }

        public void EnableBehaviour()
        {
            SetStartTimer();
            SetEndTimer();

            UpdateBlyncLightState();
        }

        public void DisableBehaviour()
        {
            startTimer.Change(Timeout.Infinite, Timeout.Infinite);
            endTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }

        #endregion

        private void SetStartTimer()
        {
            // trigger the event at 7 AM
            DateTime startTime = DateTime.Today.AddHours(7).AddMinutes(00);
            if (DateTime.Now > startTime)
            {
                if (startTime.DayOfWeek != DayOfWeek.Saturday &&
                    startTime.DayOfWeek != DayOfWeek.Sunday)
                {
                    blyncLightActive = true;
                }

                startTime = startTime.AddDays(1);
            }

            startTimer = new Timer(StartTimerAction);
            startTimer.Change((int)(startTime - DateTime.Now).TotalMilliseconds, Timeout.Infinite);
        }

        private void SetEndTimer()
        {
            // trigger the event at 6 PM.
            DateTime endTime = DateTime.Today.AddHours(18).AddMinutes(00);
            if (DateTime.Now > endTime)
            {
                blyncLightActive = false;

                endTime = endTime.AddDays(1);
            }

            endTimer = new Timer(EndTimerAction);
            endTimer.Change((int)(endTime - DateTime.Now).TotalMilliseconds, Timeout.Infinite);
        }

        private void StartTimerAction(object e)
        {
            blyncLighteManager.Logger.Info("Turning on BlyncLights");

            blyncLightActive = true;

            UpdateBlyncLightState();

            SetStartTimer();
        }

        private void EndTimerAction(object e)
        {
            blyncLighteManager.Logger.Info("Turning off BlyncLights");

            blyncLightActive = false;

            UpdateBlyncLightState();

            SetEndTimer();
        }

        private void UpdateBlyncLightState()
        {
            if (blyncLightActive)
            {
                blyncLighteManager.EnableBlyncDevices();
            }
            else
            {
                blyncLighteManager.DisableBlyncDevices();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Class: PerspectiveProjection
module Shumway.AVMX.AS.flash.geom {
  import notImplemented = Shumway.Debug.notImplemented;
  export class PerspectiveProjection extends ASObject {

    // Called whenever the class is initialized.
    static classInitializer: any = null;

    // List of static symbols to link.
    static classSymbols: string [] = null; // [];

    // List of instance symbols to link.
    static instanceSymbols: string [] = null; // [];

    constructor () {
      super();
    }

    // _fieldOfView: number;
    // _projectionCenter: flash.geom.Point;
    // _focalLength: number;
    get fieldOfView(): number {
      notImplemented("public flash.geom.PerspectiveProjection::get fieldOfView"); return;
      // return this._fieldOfView;
    }
    set fieldOfView(fieldOfViewAngleInDegrees: number) {
      fieldOfViewAngleInDegrees = +fieldOfViewAngleInDegrees;
      notImplemented("public flash.geom.PerspectiveProjection::set fieldOfView"); return;
      // this._fieldOfView = fieldOfViewAngleInDegrees;
    }
    get projectionCenter(): flash.geom.Point {
      notImplemented("public flash.geom.PerspectiveProjection::get projectionCenter"); return;
      // return this._projectionCenter;
    }
    set projectionCenter(p: flash.geom.Point) {
      p = p;
      notImplemented("public flash.geom.PerspectiveProjection::set projectionCenter"); return;
      // this._projectionCenter = p;
    }
    get focalLength(): number {
      notImplemented("public flash.geom.PerspectiveProjection::get focalLength"); return;
      // return this._focalLength;
    }
    set focalLength(value: number) {
      value = +value;
      notImplemented("public flash.geom.PerspectiveProjection::set focalLength"); return;
      // this._focalLength = value;
    }
    toMatrix3D(): flash.geom.Matrix3D {
      notImplemented("public flash.geom.PerspectiveProjection::toMatrix3D"); return;
    }
  }
}


text:
from flask.ext.script import Command

from ark.exts import db

class Destroy(Command):

    def __call__(self, app):
        with app.test_request_context():
            print 'Droping Database'
            db.drop_all()
            print 'Done!'


text:
import React, {PropTypes as t} from 'react';
import {sortBy} from 'lodash';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';

import Markdown from '../common/markdown';
import Message from '../common/message';
import urlQuery from '../../utils/url-query';
import getIdByPathname from '../../utils/get-id-by-pathname';
import PatternFolder from '../pattern/pattern-folder';
import PatternSection from '../pattern/pattern-section';
import navigate from '../../utils/navigate';

export default Content;

const sortTypes = ['folder', 'pattern'];
const rateType = item => sortTypes.indexOf(item.type);

function Content(props) {
	const {base, config, location} = props;
	const {hierarchy} = config;

	const {pathname} = urlQuery.parse(location.pathname);
	const id = getIdByPathname(pathname, props.base);

	const fragments = id.split('/');
	const depth = fragments.length - 1;
	const up = depth > 0 ? fragments.slice(0, fragments.length - 1).join('/') : '';
	const item = navigate(id, props.navigation);

	if (!item) {
		return (

					<Markdown source={getNotFoundSource(id)}/>

		);
	}

	const itemDefaults = {base, location};
	const items = sortBy(sortBy(getItems(item, hierarchy, itemDefaults, props.hide), 'name'), rateType);

	return (

			{
				item.type === 'folder' &&
					<PatternFolder
						id={id}
						location={location}
						items={items}
						up={up}
						base={base}
						/>
			}
			{
				item.type === 'pattern' &&
					<PatternSection
						id={id}
						data={props.pattern}
						navigation={props.navigation}
						config={props.config}
						location={location}
						type={item.type}
						onDataRequest={props.onLoad}
						base={base}
						/>
			}
			<CSSTransitionGroup
				component="aside"
				transitionName="pattern-content-transition"
				className="messages"
				transitionEnterTimeout={300}
				transitionLeaveTimeout={300}
				>
				{
					props.messages.map(message => {
						return (
							<Message
								id={message.id}
								key={message.id}
								type={message.type}
								title={message.subject}
								body={message.body || message.stack}
								pattern={String(message.pattern).trim()}
								payload={message.payload}
								retry={message.retry}
								file={message.file}
								timestamp={message.timestamp}
								onDismiss={props.onDismiss}
								onRetry={props.onRetry}
								location={location}
								base={base}
								/>
						);
					})
				}
			</CSSTransitionGroup>

	);
}

Content.propTypes = {
	base: t.string.isRequired,
	config: t.object.isRequired,
	hide: t.bool.isRequired,
	location: t.shape({
		pathname: t.string.isRequired
	}).isRequired,
	navigation: t.object.isRequired,
	onDismiss: t.func.isRequired,
	onLoad: t.func.isRequired,
	onRetry: t.func.isRequired,
	pattern: t.object.isRequired,
	messages: t.array.isRequired
};

function getItemName(item, hierarchy) {
	if (item.type === 'pattern') {
		return item.manifest.displayName || item.manifest.name || item.id;
	}
	const configured = hierarchy[item.id] || {};
	return configured.displayName || item.id;
}

function getNotFoundSource(id) {
	return `
# Pattern not found

We looked everywhere and could not find pattern \`${id}\`.

You might want to navigate back to [Home](/) or use the search.

---

Help us to make this message more helpful on [GitHub](https://github.com/sinnerschrader/patternplate)
`;
}

function getItems(root, hierarchy, defaults, hide) {
	if (root.type !== 'folder') {
		return [];
	}
	return Object.values(root.children)
		.map(selectPatternData(hierarchy, defaults, hide))
		.filter(item => item.type !== 'pattern' || item.display);
}

function selectPatternData(hierarchy, defaults, hide) {
	return child => {
		const amend = child.type === 'pattern' ?
		{
			version: child.manifest.version,
			flag: child.manifest.flag,
			tags: child.manifest.tags,
			display: hide ? child.manifest.display !== false : true
		} :
		{};

		return {
			...defaults,
			id: child.id,
			name: getItemName(child, hierarchy),
			type: child.type,
			...amend
		};
	};
}


text:
@implementation MHMoreEmotionViewModel

@end


text:
{-# LANGUAGE OverloadedStrings #-}

module View.Header (headerHtml) where

import Text.Blaze.Html5.Attributes (href, rel)
import Text.Blaze.Html5 (Html, head, title, link, (!))
import qualified Text.Blaze.Html5 as H (head)

headerHtml :: Html
headerHtml =
    H.head $ do
        title "Wubble"
        link ! rel "stylesheet" ! href "css/style.css"


text:
namespace llvm {
namespace jitlink {

template <typename BuilderImpl> class BasicGOTAndStubsBuilder {
public:
  BasicGOTAndStubsBuilder(LinkGraph &G) : G(G) {}

  void run() {
    // We're going to be adding new blocks, but we don't want to iterate over
    // the newly added ones, so just copy the existing blocks out.
    std::vector<Block *> Blocks(G.blocks().begin(), G.blocks().end());

    LLVM_DEBUG(dbgs() << "Creating GOT entries and stubs:\n");

    for (auto *B : Blocks)
      for (auto &E : B->edges())
        if (impl().isGOTEdge(E)) {
          LLVM_DEBUG({
            dbgs() << "  Updating GOT edge ";
            printEdge(dbgs(), *B, E, "<target GOT>");
            dbgs() << "\n";
          });
          impl().fixGOTEdge(E, getGOTEntrySymbol(E.getTarget()));
        } else if (impl().isExternalBranchEdge(E)) {
          LLVM_DEBUG({
            dbgs() << "  Updating external branch edge ";
            printEdge(dbgs(), *B, E, "<target PC-rel>");
            dbgs() << "\n";
          });
          impl().fixExternalBranchEdge(E, getStubSymbol(E.getTarget()));
        }
  }

protected:
  Symbol &getGOTEntrySymbol(Symbol &Target) {
    assert(Target.hasName() && "GOT edge cannot point to anonymous target");

    auto GOTEntryI = GOTEntries.find(Target.getName());

    // Build the entry if it doesn't exist.
    if (GOTEntryI == GOTEntries.end()) {
      auto &GOTEntry = impl().createGOTEntry(Target);
      LLVM_DEBUG({
        dbgs() << "    Created GOT entry for " << Target.getName() << ": "
               << GOTEntry << "\n";
      });
      GOTEntryI =
          GOTEntries.insert(std::make_pair(Target.getName(), &GOTEntry)).first;
    }

    assert(GOTEntryI != GOTEntries.end() && "Could not get GOT entry symbol");
    LLVM_DEBUG(
        { dbgs() << "    Using GOT entry " << *GOTEntryI->second << "\n"; });
    return *GOTEntryI->second;
  }

  Symbol &getStubSymbol(Symbol &Target) {
    assert(Target.hasName() &&
           "External branch edge can not point to an anonymous target");
    auto StubI = Stubs.find(Target.getName());

    if (StubI == Stubs.end()) {
      auto &StubSymbol = impl().createStub(Target);
      LLVM_DEBUG({
        dbgs() << "    Created stub for " << Target.getName() << ": "
               << StubSymbol << "\n";
      });
      StubI = Stubs.insert(std::make_pair(Target.getName(), &StubSymbol)).first;
    }

    assert(StubI != Stubs.end() && "Count not get stub symbol");
    LLVM_DEBUG({ dbgs() << "    Using stub " << *StubI->second << "\n"; });
    return *StubI->second;
  }

  LinkGraph &G;

private:
  BuilderImpl &impl() { return static_cast<BuilderImpl &>(*this); }

  DenseMap<StringRef, Symbol *> GOTEntries;
  DenseMap<StringRef, Symbol *> Stubs;
};

} // end namespace jitlink
} // end namespace llvm

#endif // LLVM_LIB_EXECUTIONENGINE_JITLINK_BASICGOTANDSTUBSBUILDER_H


text:
@extends('fakultet.master')
@section('title', 'Dobrodošli na Algebrin fakultet')

@section('content')

Sve dvorane

Kreiraj novu dvoranu

@if (Session::has('message'))

{{ Session::get('message') }}

@endif

            Oznaka
            Kapacitet

        @foreach($dvoranas as $key => $value)

            {{ $value->oznDvorana }}
            {{ $value->kapacitet }}

                {!! Form::open(array('url' => 'dvorana/' . $value->oznDvorana, 'class' => 'pull-right')) !!}
                {!! Form::hidden('_method', 'DELETE') !!}
                {!! Form::submit('Obrisi ovu dvoranu', array('class' => 'btn btn-warning','id'=>'dvorana-del-'.$value->oznDvorana)) !!}
                {!! Form::close() !!}

                oznDvorana}}" href="{{ URL::to('dvorana/' . $value->oznDvorana) }}">Pokaži ovu dvoranu

                oznDvorana . '/edit') }}">Uredi ovu dvoranu

        @endforeach

@endsection


text:
module RailsVersion
  def self.is_6?
    Rails::VERSION::MAJOR == 6
  end
end


text:
<VAST version="4.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.iab.com/VAST">
  <Ad id="20008" sequence="1" conditionalAd="false">
    <InLine>
      <AdSystem version="4.0">iabtechlab</AdSystem>
      <Error>http://example.com/error</Error>
      <Extensions>
        <Extension type="iab-Count">
          <total_available>
            <![CDATA[ 2 ]]>
          </total_available>
        </Extension>
      </Extensions>
      <Impression id="Impression-ID">http://example.com/track/impression</Impression>
      <Pricing model="cpm" currency="USD">
        <![CDATA[ 25.00 ]]>
      </Pricing>
      <AdTitle>iabtechlab video ad</AdTitle>
      <Category authority="http://www.iabtechlab.com/categoryauthority">AD CONTENT description category</Category>

      <Creatives>
        <Creative id="5480" sequence="1" adId="2447226">
          <UniversalAdId idRegistry="Ad-ID" idValue="8465">8465</UniversalAdId>
          <Linear>
            <TrackingEvents>
              <Tracking event="start" offset="08:34:01">http://example.com/tracking/start</Tracking>
              <Tracking event="firstQuartile">http://example.com/tracking/firstQuartile</Tracking>
              <Tracking event="midpoint">http://example.com/tracking/midpoint</Tracking>
              <Tracking event="thirdQuartile">http://example.com/tracking/thirdQuartile</Tracking>
              <Tracking event="complete">http://example.com/tracking/complete</Tracking>
            </TrackingEvents>
            <Duration>00:00:16</Duration>
            <MediaFiles>
              <MediaFile id="5241" delivery="progressive" type="video/mp4" bitrate="2000" width="1280" height="720" minBitrate="1500" maxBitrate="2500" scalable="1" maintainAspectRatio="1" codec="0">
                <![CDATA[https://iabtechlab.com/wp-content/uploads/2016/07/VAST-4.0-Short-Intro.mp4]]>
              </MediaFile>
              <MediaFile id="5244" delivery="progressive" type="video/mp4" bitrate="1000" width="854" height="480" minBitrate="700" maxBitrate="1500" scalable="1" maintainAspectRatio="1" codec="0">
                <![CDATA[http://example.com/mediafile/mid_resolution.mp4]]>
              </MediaFile>
              <MediaFile id="5246" delivery="progressive" type="video/mp4" bitrate="600" width="640" height="360" minBitrate="500" maxBitrate="700" scalable="1" maintainAspectRatio="1" codec="0">
                <![CDATA[http://example.com/mediafile/low_resolution.mp4]]>
              </MediaFile>
            </MediaFiles>

            <VideoClicks>
              <ClickThrough id="blog">
                <![CDATA[https://iabtechlab.com]]>
              </ClickThrough>
            </VideoClicks>
          </Linear>
        </Creative>
      </Creatives>
    </InLine>
  </Ad>
</VAST>


text:
/*!
{
  "name": "EXIF Orientation",
  "property": "exiforientation",
  "tags": ["image"],
  "builderAliases": ["exif_orientation"],
  "async": true,
  "authors": ["Paul Sayre"],
  "notes": [{
    "name": "Article by Dave Perrett",
    "href": "http://recursive-design.com/blog/2012/07/28/exif-orientation-handling-is-a-ghetto/"
  },{
    "name": "Article by Calvin Hass",
    "href": "http://www.impulseadventure.com/photo/exif-orientation.html"
  }]
}
!*/
/* DOC
Detects support for EXIF Orientation in JPEG images.

iOS looks at the EXIF Orientation flag in JPEGs and rotates the image accordingly. Most desktop browsers just ignore this data.
*/
define(['Modernizr', 'addTest'], function( Modernizr, addTest ) {
  // Bug trackers:
  //    bugzil.la/298619 (unimplemented)
  //    crbug.com/56845 (looks incomplete)
  //    webk.it/19688 (available upstream but its up all ports to turn on individually)
  Modernizr.addAsyncTest(function() {
    var img = new Image();

    img.onerror = function() {
      addTest('exiforientation', false, { aliases: ['exif-orientation'] });
    };

    img.onload = function() {
      addTest('exiforientation', img.width !== 2, { aliases: ['exif-orientation'] });
    };

    // There may be a way to shrink this more, it's a 1x2 white jpg with the orientation flag set to 6
    img.src = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q==';
  });
});


text:
import unittest
from widget import Widget

class SimpleWidgetTestCase(unittest.TestCase):

    def test_init(self):
        widget = Widget('The widget', 10, 10)
        self.failUnless(widget.size() == (10, 10),
                        'incorrect size')

    def test_default_size(self):
        widget = Widget('The widget')
        self.failUnless(widget.size() == (50, 50),
                        'incorrect default size')

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


text:
<?php
/**
 * SampleApplicationInfoOrmBaseクラス
 *
 * application_info_mのO-RMapper基礎クラス
 *
 * @access  public
 **/
class SampleApplicationInfoOrmBase extends PhateORMapperBase
{
    protected $_tableName = 'application_info_m';

    protected $_pkey = array(
        'device_type_id',
    );
    protected $_pkeyIsRowId = false;
    protected $_value = array(
        'device_type_id' => null,
        'stable_version' => null,
        'lowest_version' => null,
    );
    protected $_toSave = array(
        'device_type_id' => null,
        'stable_version' => null,
        'lowest_version' => null,
    );

    public function getDeviceTypeId()
    {
        return $this->_toSave['device_type_id'];
    }

    public function setDeviceTypeId($value)
    {
        if ($this->_value['device_type_id'] != $value) {
            $this->_changeFlg = true;
        }
        $this->_toSave['device_type_id'] = $value;
    }

    public function getStableVersion()
    {
        return $this->_toSave['stable_version'];
    }

    public function setStableVersion($value)
    {
        if ($this->_value['stable_version'] != $value) {
            $this->_changeFlg = true;
        }
        $this->_toSave['stable_version'] = $value;
    }

    public function getLowestVersion()
    {
        return $this->_toSave['lowest_version'];
    }

    public function setLowestVersion($value)
    {
        if ($this->_value['lowest_version'] != $value) {
            $this->_changeFlg = true;
        }
        $this->_toSave['lowest_version'] = $value;
    }

}


text:
"""A dictionary with case-insensitive access."""

from marrow.util.object import NoDefault

__all__ = ['CaseInsensitiveDict']

class CaseInsensitiveDict(dict):
    def __init__(self, default=None, *args, **kw):
        self._o = {}

        if default is None:
            default = dict()
            default.update(kw)

        for i in default:
            self[i] = default[i]

        super(CaseInsensitiveDict, self).__init__()

    def items(self):
        return [(self._o[k], self[k]) for k in self]

    def __setitem__(self, k, v):
        try:
            nk = k.lower()
        except:
            nk = k

        self._o[nk] = k
        super(CaseInsensitiveDict, self).__setitem__(nk, v)

    def __getitem__(self, k):
        try:
            nk = k.lower()
        except:
            nk = k

        return super(CaseInsensitiveDict, self).__getitem__(nk)


text:
Pomodoro Timer To-Do:
- add functionality to create fully custom programs, ie: let the user customize the order that different periods automatically switch to when time is up
- end to end test suite

Bugs:
- time initially displays with only one 0 in the minutes place
  - Bug fixed, but in a haphazard way: if seconds == 0, it displays as the string "00"


text:
cDTO is a tool for defining data transport objects for the C language and generating the procedures necessary to transform them to and from various message interchange formats, such as XML and JSON. The goal of cDTO is to enable developers to build REST clients and REST services in C without needing to write all the boilerplate code necessary to validate and transform C data types between message formats.

## Using cDTO
Suppose we wanted to build a REST client to retrieve information about GitHub issues through the GitHub REST API. Our REST client would receive JSON data such as
```json
{
    "url": "https://api.github.com/repos/facebook/react/issues/8795",
    "number": 8795,
    "title": "Large update to tutorial.md's refactor section.",
    "user": {
        "login": "Jwan622",
        "url": "https://api.github.com/users/Jwan622"
    },
    "labels": [
        {
        "name": "CLA Signed",
        "color": "e7e7e7"
        },
        {
        "name": "GH Review: needs-revision",
        "color": "e11d21"
        }
    ],
    "assignees": []
}
```
To use cDTO to consume these JSON messages in our REST client, we would first define our messages in a message definition file, "github_issues.cdto"
```
issue {
    number Number cType=uint32_t;
    url String;
    title String;
    creator user jsonKey=user;
    assignees Array[user];
    labels Array[label];
}

user {
    name String jsonKey=login;
    url String;
}

label {
    name String;
    color String[6];
}
```
Next, this message definition file would be fed into cDTO to generate the corresponding C DTO type definitions along with the necessary clean up functions.
```C
// Header github_issues.cdto.h
typedef struct
    {
    char*    name;
    char*    url;
    } user;

typedef struct
    {
    char*    name;
    char     color[ 7 ];
    } label;

typedef struct
    {
    uint32_t    number;
    char*       url;
    char*       title;
    user        creator;
    user*       assignees;
    int         assignees_cnt;
    label*      labels;
    int         labels_cnt;
    } issue;

void label_free
  (
  label * label
  );

void user_free
  (
  user * user
  );

void issue_free
  (
  issue * issue
  );
```

JSON deserialization and serialization procedures would be generated for the cDTO types. The serialization functions will handle validation of all JSON input strings and will return an error if the JSON does not match the expected message format.
```C
// Header github_issues.cdto.json.h

#include "github_issues.cdto.h"

int issue_json_parse
    (
    char const* json_str,
    issue* obj_out
    );

int issue_json_serialize
    (
    issue const* obj,
    char** json_out
    );

int issue_json_serialize_pretty
    (
    issue const* obj,
    char** json_out
    );

int label_json_parse
    (
    char const* json_str,
    label* obj_out
    );

int label_json_serialize
    (
    label const* obj,
    char** json_out
    );

int label_json_serialize_pretty
    (
    label const* obj,
    char** json_out
    );

int user_json_parse
    (
    char const* json_str,
    user* obj_out
    );

int user_json_serialize
    (
    user const* obj,
    char** json_out
    );

int user_json_serialize_pretty
    (
    user const* obj,
    char** json_out
    );
```
We can now process JSON data received from the GitHub API
```C
#include <stdio.h>
#include "github_issues.cdto.json.h"

int main()
{
  char const * json = "{"
    "\"number\": 8795,"
    "\"url\": \"https://api.github.com/repos/facebook/react/issues/8795\","
    "\"title\": \"Large update to tutorial.md's refactor section.\","
    "\"user\": {"
      "\"login\": \"Jwan622\","
      "\"url\": \"https://api.github.com/users/Jwan622\""
    "},"
    "\"labels\": ["
      "{"
        "\"name\": \"CLA Signed\","
        "\"color\": \"e7e7e7\""
      "},"
    "],"
    "\"assignees\": []"
  "}";

  issue issue;
  int success;

  success = issue_json_parse( json, &issue );
  if( success )
    {
    printf("Parsed issue %s\n", issue.title);
    }

  issue_free( &issue );

  return 0;
}
```

See the example directory for a complete, executable example of using the code generated from a cDTO definition to parse and serialize JSON data.


text:
<?php
/**
 * BjyAuthorize Module (https://github.com/bjyoungblood/BjyAuthorize)
 *
 * @link https://github.com/bjyoungblood/BjyAuthorize for the canonical source repository
 * @license http://framework.zend.com/license/new-bsd New BSD License
 */
namespace BjyAuthorize\Service;

/**
 * Factory responsible of building a set of {@see \BjyAuthorize\Guard\GuardInterface}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 */
class GuardsServiceFactory extends BaseProvidersServiceFactory
{

    const PROVIDER_SETTING = 'guards';
}


text:
/********************************************************************************/
/*																				*/
/*	© 2006, Aurbach & Associates, Inc.  All rights reserved.					*/
/*																				*/
/*	Redistribution and use in source and binary forms, with or without			*/
/*	modification, are permitted provided that the following condition			*/
/*	are met:																	*/
/*																				*/
/*	  ¥	Redistributions of source code must retain the above copyright			*/
/*		notice, this list of conditions and the following disclaimer.			*/
/*																				*/
/*	  ¥	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.	*/
/*																				*/
/*	  ¥	Neither the name of Aurbach & Associates, Inc. nor the names of any		*/
/*		of its employees may be used to endorse or promote products derived		*/
/*		from this software without specific prior written permission.			*/
/*																				*/
/*	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER	*/
/*	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.									*/
/*																				*/
/********************************************************************************/
/*
 *	Module Name:	LContextMenuHelper
 *
 *	SuperClass:		LMenu
 *
 *	Notes:			This module is a helper class providing common logic for the
 *					support of contextual menus.
 *
 *	Change History:
 *
 *	Who     	Date	    Description
 * ---------------------------------------------------------------------------
 *	RLA		06-Jan-2006		Original Code (AContextMenu.h)
 *	RLA		27-Sep-2006		Adapted for contribution to open-powerplant
 */

#include			<LContextMenuHelper.h>
#ifndef __MACH__
#include			<Menus.h>
#endif
#include			<PP_Resources.h>
#include			<UCMMUtils.h>

/***
 * ==>	LContextMenuHelper
 *
 *	Default Constructor
 *
 ***/

LContextMenuHelper::LContextMenuHelper (
	LCommander *			inCtxCmdr )	:	LMenu(0, Str_Empty, false)
{
	mCtxCmdr = inCtxCmdr;
	mCtxPane = dynamic_cast<LPane*>(inCtxCmdr);		// default
	mHelpType = kCMHelpItemNoHelp;
}

/***
 * ==>	LContextMenuHelper
 *
 *	Parameterized Constructor
 *
 ***/

LContextMenuHelper::LContextMenuHelper (
	ResIDT					inMENUid,
	LCommander *			inCtxCmdr )	:	LMenu(inMENUid)
{
	mCtxCmdr = inCtxCmdr;
	mCtxPane = dynamic_cast<LPane*>(inCtxCmdr);		// default
	mHelpType = kCMHelpItemNoHelp;
}

/***
 * ==>	~LContextMenuHelper
 *
 *	Destructor
 *
 ***/

LContextMenuHelper::~LContextMenuHelper ( void )
{
}

/***
 * ==>	AppendMenuCommand
 *
 *	Add a menu command to the end of this menu.
 *
 ***/

void
LContextMenuHelper::AppendMenuCommand (
	const char *			inMenuString,
	CommandT				inCommand )
{
	LStr255					str(inMenuString);
	InsertCommand(str, inCommand, 32000);
}

void
LContextMenuHelper::AppendMenuCommand (
	ConstStringPtr			inMenuString,
	CommandT				inCommand )
{
	InsertCommand(inMenuString, inCommand, 32000);
}

void
LContextMenuHelper::AppendMenuCommand (
	ResIDT					inStringResID,
	SInt16					inStringIndex,
	CommandT				inCommand )
{
	LStr255					str(inStringResID, inStringIndex);
	AppendMenuCommand(str, inCommand);
}

/***
 * ==>	AppendMenuCommandList
 *
 *	Add a list of menu items to the contextual menu, using
 *	another menu resource as the basis.
 *
 ***/

void
LContextMenuHelper::AppendMenuCommandList (
	ResIDT					inMenuID )
{
	LMenu					cmdList(inMenuID);
	MenuHandle				menuH = cmdList.GetMacMenuH();
	SInt16					count = CountMenuItems(menuH);
	for (SInt16 index = 1; index <= count; index++) {
		LStr255				itemTxt;
		::GetMenuItemText(menuH, index, itemTxt);
		CommandT			cmd = cmdList.CommandFromIndex(index);
		AppendMenuCommand(itemTxt, cmd);
	}
}

/***
 * ==>	AppendMenuSeparator
 *
 *	Add a separator line to the contextual menu.
 *
 ***/

void
LContextMenuHelper::AppendMenuSeparator ( void )
{
	InsertCommand("\p-", cmd_Nothing, 32000);
}

/***
 * ==>	TrackMenu
 *
 *	Display a popup menu and track the user interaction with it.
 *	If the user makes a selection, process the selection.
 *	Return a boolean to indicate whether a menu item was processed.
 *
 *	NOTE:		The Help menu is added automatically.
 *
 *	The inExecuteCommand parameter is a hook. Most contextual menus contain
 *	commands that can be processed by calling the context commander's
 *	ProcessCommand method. But this is not always the case. For cases when
 *	other alternatives are needed, set inExecuteCommand to false to return
 *	the command, rather than process it.
 *
 ***/

CommandT
LContextMenuHelper::TrackMenu (
	Point					inGlobalPt,
	bool					inExecuteCommand )
{
	CommandT				cmd = cmd_Nothing;

	if (mCtxCmdr != nil) {
		GetContext();
		PreCMSelect(inGlobalPt);
		PrepareMenuItems();
		FinalizeMenu();

		UInt32				selectionType;
		SInt16				menuID;
		MenuItemIndex		menuIndex;
		OSStatus			err;

		if (mHelpStr.Length() == 0) {
			mHelpStr.Assign(STRx_Standards, str_HelpMenuTitle);
			if (mHelpStr.Length() == 0) {
				mHelpStr.Assign("\pHelp");
			}
		}
		UInt32				helpType = mHelpType;
		if (helpType == kCMHelpItemOtherHelp) {
			helpType = (IsHelpAvailable() ? kCMHelpItemOtherHelp : kCMHelpItemNoHelp);
		}

		AEDesc *			selDesc = mSelection;
		if (mSelection.IsNull()) {
			selDesc = nil;
		}

		::MacInsertMenu(mMacMenuH, hierMenu);

		err = ::ContextualMenuSelect(mMacMenuH, inGlobalPt, false, helpType, mHelpStr,
								selDesc, &selectionType, &menuID, &menuIndex);
		if (err == noErr) {
			PostCMSelect(inGlobalPt);
			if (selectionType == kCMShowHelpSelected) {
				cmd = cmd_Help;
			} else if (selectionType == kCMMenuItemSelected) {
				cmd = CommandFromIndex(menuIndex);
			}
		}

		if (inExecuteCommand) {
			if (cmd == cmd_Help) {
				ShowHelp();
			} else if (cmd != cmd_Nothing) {
				mCtxCmdr->ProcessCommand(cmd);
			}
		}
	}
	return cmd;
}

#pragma mark -
/***
 * ==>	GetContext
 *
 *	Obtain the object specifier for the current selection. Used by
 *	::ContextualMenuSelect() to actually determine our context and
 *	how to build the menu accordingly (used by CMM plugins).
 *
 *	You shouldn't need to override this method, however you may need to
 *	implement LPane::GetSelection(AEDesc&) in the context pane.
 *
 ***/

void
LContextMenuHelper::GetContext ( void )
{
	mSelection.Dispose();

	// If we have a context pane defined, use it.
	// If we have no context pane defined, see if the context commander
	// is a visual object.
	LPane *					pane = dynamic_cast<LPane*>(mCtxPane);
	if (pane == nil) {
		pane = dynamic_cast<LPane*>(mCtxCmdr);
	}

	if (pane != nil) {
		pane->GetSelection(mSelection);
	}
}

/***
 * ==>	PrepareMenuItems
 *
 *	Enable or disable each item in the menu.
 *
 ***/

void
LContextMenuHelper::PrepareMenuItems ( void )
{
	if (mCtxCmdr) {
		SInt16				count;

		count = ::CountMenuItems(mMacMenuH);
		for (SInt16 index = 1; index <= count; index++) {
			MenuItemAttributes	attr = 0;
			::GetMenuItemAttributes(mMacMenuH, index, &attr);
			if ((attr & kMenuItemAttrSeparator) != 0) {
				continue;
			}
			Boolean			enabled = false, usesMark = false;
			UInt16			mark;					// not used
			LStr255			name;
			CommandT		cmd = CommandFromIndex(index);
			CheckCommandStatus(cmd, enabled, usesMark, mark, name);
			if (enabled) {
				::EnableMenuItem(mMacMenuH, index);
			} else {
				::DisableMenuItem(mMacMenuH, index);
			}
			::CheckMenuItem(mMacMenuH, index, usesMark);
			if (name.Length() != 0) {
				::SetMenuItemText(mMacMenuH, index, name);
			}
		}
	}
}

/***
 * ==>	FinializeMenu
 *
 *	Perform last minute tweaks on the menu
 *
 ***/

void
LContextMenuHelper::FinalizeMenu ( void )
{
	Assert_(mMacMenuH != nil);

	UCMMUtils::StripDoubleDividers(mMacMenuH);
	UCMMUtils::StripFirstDivider(mMacMenuH);
	UCMMUtils::StripLastDivider(mMacMenuH);
}

/***
 * ==>	CheckCommandStatus
 *
 *	This function is a hook-proc for contextual menu handling.
 *
 *	Contextual menus that exclusively consist of functions that are implemented
 *	as Commands use this method; contextual menus that handle other cases should
 *	override this method to provide the proper status for the command.
 *
 ***/

void
LContextMenuHelper::CheckCommandStatus (
	CommandT						inCommand,
	Boolean &						outEnabled,
	Boolean &						outUsesMark,
	UInt16 &						outMark,
	Str255							outName )
{
	if (mCtxCmdr) {
		mCtxCmdr->ProcessCommandStatus(inCommand, outEnabled, outUsesMark, outMark, outName);
	}
}


text:
var router = require("express").Router();
var tasksCtrl = require("../../controllers/tasks");
var loadUser = require("../middlewares/loadUser");

router.use(loadUser);

router.route("/")
    .get (tasksCtrl.findAll)
    .post (tasksCtrl.add);

router.route("/:id")
    .get (tasksCtrl.findById)
    .put (tasksCtrl.update)
    .delete (tasksCtrl.delete);

router.route("/find/descendants")
	.get (tasksCtrl.findDescendants);

module.exports = router;


text:
<!DOCTYPE HTML>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>

<input id="spin" type="number" min=0 max=10 value=0 style="position: absolute; left: 100px; top: 50px; width: 300px; height: 20px;">

<script>
test(function(t) {
  var axSpin = accessibilityController.accessibleElementById("spin");
  assert_equals(axSpin.role, "AXRole: AXSpinButton");

  var axSpinUp = axSpin.childAtIndex(1).childAtIndex(0);
  assert_equals(axSpinUp.role, "AXRole: AXButton");

  var axSpinDown = axSpin.childAtIndex(1).childAtIndex(1);
  assert_equals(axSpinDown.role, "AXRole: AXButton");

  // The buttons should be near the right edge of the parent.
  assert_true(Math.abs(axSpinUp.x + axSpinUp.width - (axSpin.x + axSpin.width)) < 5);
  assert_true(Math.abs(axSpinDown.x + axSpinDown.width - (axSpin.x + axSpin.width)) < 5);

  // The buttons should be small.
  assert_true(axSpinUp.width < 30);
  assert_true(axSpinUp.height < 30);
  assert_true(axSpinDown.width < 30);
  assert_true(axSpinDown.height < 30);
}, "Test bounds of spin thumb");
</script>

</body>
</html>


text:
namespace SortingHomework
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class SortableCollection<T> where T : IComparable<T>
    {
        private readonly IList<T> items;

        public SortableCollection()
        {
            this.items = new List<T>();
        }

        public SortableCollection(IEnumerable<T> items)
        {
            this.items = new List<T>(items);
        }

        public IList<T> Items
        {
            get
            {
                return this.items;
            }
        }

        public void Sort(ISorter<T> sorter)
        {
            sorter.Sort(this.items);
        }

        public bool LinearSearch(T item)
        {
            int foundIndex = -1;

            for (int i = 0; i < this.items.Count - 1; i++)
            {
                if (this.items[i].Equals(item))
                {
                    foundIndex = i;
                }
            }

            if (foundIndex >= 0)
            {
                return true;
            }

            return false;
        }

        public bool BinarySearch(T item)
        {
            // To ensure the list is sorted!
            var sortedCollection = this.items.ToList();
            sortedCollection.Sort();

            int fromIndex = 0;
            int toIndex = sortedCollection.Count - 1;

            while (fromIndex <= toIndex)
            {
                int middle = (fromIndex + toIndex) / 2;
                var compareToResult = this.items[middle].CompareTo(item);
                if (compareToResult == 0)
                {
                    return true;
                }
                else if (compareToResult < 0)
                {
                    fromIndex = middle + 1;
                }
                else
                {
                    toIndex = middle - 1;
                }
            }
            return false;
        }

        public void Shuffle()
        {
            var n = this.items.Count;
            var random = new Random();
            for (int i = 0; i < n; i++)
            {
                int randomIndex = random.Next(0, n - i);
                HelperMethods.Swap(this.items, i, randomIndex);
            }
        }

        public void PrintAllItemsOnConsole()
        {
            for (int i = 0; i < this.items.Count; i++)
            {
                if (i == 0)
                {
                    Console.Write(this.items[i]);
                }
                else
                {
                    Console.Write(" " + this.items[i]);
                }
            }

            Console.WriteLine();
        }
    }
}


text:
package org.elasticsearch.index.query;

import org.apache.lucene.search.Filter;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoHashUtils;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexGeoPointFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper;
import org.elasticsearch.index.search.geo.GeoDistanceRangeFilter;

import java.io.IOException;

/**
 * <pre>
 * {
 *     "name.lat" : 1.1,
 *     "name.lon" : 1.2,
 * }
 * </pre>
 */
public class GeoDistanceRangeFilterParser implements FilterParser {

    public static final String NAME = "geo_distance_range";

    @Inject
    public GeoDistanceRangeFilterParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME, "geoDistanceRange"};
    }

    @Override
    public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        XContentParser.Token token;

        String filterName = null;
        String currentFieldName = null;
        GeoPoint point = new GeoPoint();
        String fieldName = null;
        Object vFrom = null;
        Object vTo = null;
        boolean includeLower = true;
        boolean includeUpper = true;
        DistanceUnit unit = DistanceUnit.DEFAULT;
        GeoDistance geoDistance = GeoDistance.DEFAULT;
        String optimizeBbox = "memory";
        boolean normalizeLon = true;
        boolean normalizeLat = true;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (parseContext.isDeprecatedSetting(currentFieldName)) {
                // skip
            } else if (token == XContentParser.Token.START_ARRAY) {
                GeoUtils.parseGeoPoint(parser, point);
                fieldName = currentFieldName;
            } else if (token == XContentParser.Token.START_OBJECT) {
                // the json in the format of -> field : { lat : 30, lon : 12 }
                fieldName = currentFieldName;
                GeoUtils.parseGeoPoint(parser, point);
            } else if (token.isValue()) {
                if (currentFieldName.equals("from")) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vFrom = parser.text(); // a String
                    } else {
                        vFrom = parser.numberValue(); // a Number
                    }
                } else if (currentFieldName.equals("to")) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vTo = parser.text(); // a String
                    } else {
                        vTo = parser.numberValue(); // a Number
                    }
                } else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) {
                    includeLower = parser.booleanValue();
                } else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) {
                    includeUpper = parser.booleanValue();
                } else if ("gt".equals(currentFieldName)) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vFrom = parser.text(); // a String
                    } else {
                        vFrom = parser.numberValue(); // a Number
                    }
                    includeLower = false;
                } else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vFrom = parser.text(); // a String
                    } else {
                        vFrom = parser.numberValue(); // a Number
                    }
                    includeLower = true;
                } else if ("lt".equals(currentFieldName)) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vTo = parser.text(); // a String
                    } else {
                        vTo = parser.numberValue(); // a Number
                    }
                    includeUpper = false;
                } else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) {
                    if (token == XContentParser.Token.VALUE_NULL) {
                    } else if (token == XContentParser.Token.VALUE_STRING) {
                        vTo = parser.text(); // a String
                    } else {
                        vTo = parser.numberValue(); // a Number
                    }
                    includeUpper = true;
                } else if (currentFieldName.equals("unit")) {
                    unit = DistanceUnit.fromString(parser.text());
                } else if (currentFieldName.equals("distance_type") || currentFieldName.equals("distanceType")) {
                    geoDistance = GeoDistance.fromString(parser.text());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LAT_SUFFIX)) {
                    point.resetLat(parser.doubleValue());
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LAT_SUFFIX.length());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.LON_SUFFIX)) {
                    point.resetLon(parser.doubleValue());
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.LON_SUFFIX.length());
                } else if (currentFieldName.endsWith(GeoPointFieldMapper.Names.GEOHASH_SUFFIX)) {
                    GeoHashUtils.decode(parser.text(), point);
                    fieldName = currentFieldName.substring(0, currentFieldName.length() - GeoPointFieldMapper.Names.GEOHASH_SUFFIX.length());
                } else if ("_name".equals(currentFieldName)) {
                    filterName = parser.text();
                } else if ("optimize_bbox".equals(currentFieldName) || "optimizeBbox".equals(currentFieldName)) {
                    optimizeBbox = parser.textOrNull();
                } else if ("normalize".equals(currentFieldName)) {
                    normalizeLat = parser.booleanValue();
                    normalizeLon = parser.booleanValue();
                } else {
                    point.resetFromString(parser.text());
                    fieldName = currentFieldName;
                }
            }
        }

        Double from = null;
        Double to = null;
        if (vFrom != null) {
            if (vFrom instanceof Number) {
                from = unit.toMeters(((Number) vFrom).doubleValue());
            } else {
                from = DistanceUnit.parse((String) vFrom, unit, DistanceUnit.DEFAULT);
            }
            from = geoDistance.normalize(from, DistanceUnit.DEFAULT);
        }
        if (vTo != null) {
            if (vTo instanceof Number) {
                to = unit.toMeters(((Number) vTo).doubleValue());
            } else {
                to = DistanceUnit.parse((String) vTo, unit, DistanceUnit.DEFAULT);
            }
            to = geoDistance.normalize(to, DistanceUnit.DEFAULT);
        }

        if (normalizeLat || normalizeLon) {
            GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
        }

        MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName);
        if (smartMappers == null || !smartMappers.hasMapper()) {
            throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
        }
        FieldMapper<?> mapper = smartMappers.mapper();
        if (!(mapper instanceof GeoPointFieldMapper)) {
            throw new QueryParsingException(parseContext, "field [" + fieldName + "] is not a geo_point field");
        }
        GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper);

        IndexGeoPointFieldData indexFieldData = parseContext.getForField(mapper);
        Filter filter = new GeoDistanceRangeFilter(point, from, to, includeLower, includeUpper, geoDistance, geoMapper, indexFieldData, optimizeBbox);
        if (filterName != null) {
            parseContext.addNamedFilter(filterName, filter);
        }
        return filter;
    }
}


text:
name: "Bug report"
about: 'Report a general library issue.'
---

- Library Version: #.#.#
- API Version: v#
- PHP Version: #.#.#

### Description:

### Steps To Reproduce:


text:
<?php

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThanOrEqualValidator;
use Symfony\Component\Validator\Validation;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class LessThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function getApiVersion()
    {
        return Validation::API_VERSION_2_5;
    }

    protected function createValidator()
    {
        return new LessThanOrEqualValidator();
    }

    protected function createConstraint(array $options)
    {
        return new LessThanOrEqual($options);
    }

    protected function getErrorCode()
    {
        return LessThanOrEqual::TOO_HIGH_ERROR;
    }

    /**
     * {@inheritdoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(1, 2),
            array(1, 1),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
            array(new \DateTime('2000-01-01'), new \DateTime('2020-01-01')),
            array(new \DateTime('2000-01-01'), '2000-01-01'),
            array(new \DateTime('2000-01-01'), '2020-01-01'),
            array(new \DateTime('2000-01-01 UTC'), '2000-01-01 UTC'),
            array(new \DateTime('2000-01-01 UTC'), '2020-01-01 UTC'),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)),
            array('a', 'a'),
            array('a', 'z'),
            array(null, 1),
        );
    }

    /**
     * {@inheritdoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(2, '2', 1, '1', 'integer'),
            array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
            array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
            array(new \DateTime('2010-01-01 UTC'), 'Jan 1, 2010, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
            array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(4), '4', __NAMESPACE__.'\ComparisonTest_Class'),
            array('c', '"c"', 'b', '"b"', 'string'),
        );
    }
}


text:
layout: default
title: "Lord Tope"
house: lords

---

        {% include members/lord-tope.html %}

What is Lord Tope interested in?

Lord Tope hasn't said he is interested in anything! Why not write to them and ask?

Party

Lord Tope is part of the Liberal Democrat party.

What is a party?


text:
package predict4s
package sgp
package ref

import spire.algebra._
import spire.math.{sin,cos,abs}
import spire.implicits._
import spire.syntax.primitives._
import org.scalactic.Good
import org.scalactic.Bad
import predict4s.coord._

trait SimpleKeplerEq {

  /**
   * Solve Kepler's equation
   * 		M = E − e sinE
   * to compute E the eccentric anomaly.
   * The Newton-Raphson iterations start from E0 = M = (l in Delauneys).
   */
   def solveKeplerEq[@sp(Double) F: Field: Trig: Order](e: F, M : F): AnomalyResult[F] = {
     def loop(E: F, remainingIters: Int) : AnomalyResult[F] = {
      val sinE = sin(E)
      val cosE = cos(E)
      val ecosE = e*cosE
      val esinE = e*sinE
      val fdot = 1 - ecosE
      val f = M - (E - esinE)
      val incr = f / fdot
      if (abs(incr) < 1e-12.as[F]) {
        Good(AnomalyState(E,cosE,sinE,ecosE,esinE))
      } else if (remainingIters < 0) {
        Bad(s"No convergence while solving Kepler equation: incr=$incr, E=$E")
      } else {
        loop(E+incr, remainingIters - 1)
      }
    }
    loop(M, 10)
   }

   def solveKeplerEq[@sp(Double) F: Field: Trig: Order](elem : SGPElems[F]): AnomalyResult[F] =
    solveKeplerEq(elem.e, elem.M)

   def solveKeplerEq[@sp(Double) F: Field: Trig: Order](elemCtx : SGPSecularCtx[F]): AnomalyResult[F] =
    solveKeplerEq(elemCtx._1)
}


text:
<?php

namespace Magento\Webapi\Test\Unit\Model\Soap\Wsdl;

class GeneratorTest extends \PHPUnit_Framework_TestCase
{
    /**  @var \Magento\Webapi\Model\Soap\Wsdl\Generator */
    protected $_wsdlGenerator;

    /**
     * @var \Magento\Framework\Webapi\CustomAttributeTypeLocatorInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $customAttributeTypeLocator = null;

    /**  @var \Magento\Webapi\Model\ServiceMetadata|\PHPUnit_Framework_MockObject_MockObject */
    protected $serviceMetadata;

    /**  @var \Magento\Webapi\Model\Soap\WsdlFactory|\PHPUnit_Framework_MockObject_MockObject */
    protected $_wsdlFactoryMock;

    /** @var \Magento\Framework\App\Cache\Type\Webapi|\PHPUnit_Framework_MockObject_MockObject */
    protected $_cacheMock;

    /** @var \Magento\Framework\Reflection\TypeProcessor|\PHPUnit_Framework_MockObject_MockObject */
    protected $_typeProcessor;

    /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */
    protected $storeManagerMock;

    protected function setUp()
    {
        $this->serviceMetadata = $this->getMockBuilder(
            'Magento\Webapi\Model\ServiceMetadata'
        )->disableOriginalConstructor()->getMock();

        $_wsdlMock = $this->getMockBuilder(
            'Magento\Webapi\Model\Soap\Wsdl'
        )->disableOriginalConstructor()->setMethods(
            [
                'addSchemaTypeSection',
                'addService',
                'addPortType',
                'addBinding',
                'addSoapBinding',
                'addElement',
                'addComplexType',
                'addMessage',
                'addPortOperation',
                'addBindingOperation',
                'addSoapOperation',
                'toXML',
            ]
        )->getMock();
        $this->_wsdlFactoryMock = $this->getMockBuilder(
            'Magento\Webapi\Model\Soap\WsdlFactory'
        )->setMethods(
            ['create']
        )->disableOriginalConstructor()->getMock();
        $this->_wsdlFactoryMock->expects($this->any())->method('create')->will($this->returnValue($_wsdlMock));

        $this->_cacheMock = $this->getMockBuilder(
            'Magento\Framework\App\Cache\Type\Webapi'
        )->disableOriginalConstructor()->getMock();
        $this->_cacheMock->expects($this->any())->method('load')->will($this->returnValue(false));
        $this->_cacheMock->expects($this->any())->method('save')->will($this->returnValue(true));

        $this->_typeProcessor = $this->getMock(
            'Magento\Framework\Reflection\TypeProcessor',
            [],
            [],
            '',
            false
        );

        $this->storeManagerMock = $this->getMockBuilder(
            'Magento\Store\Model\StoreManagerInterface'
        )->setMethods(['getStore'])->disableOriginalConstructor()->getMockForAbstractClass();

        $storeMock = $this->getMockBuilder(
            'Magento\Store\Model\Store'
        )->setMethods(['getCode', '__wakeup'])->disableOriginalConstructor()->getMock();

        $this->storeManagerMock->expects($this->any())
            ->method('getStore')
            ->will($this->returnValue($storeMock));

        $storeMock->expects($this->any())
            ->method('getCode')
            ->will($this->returnValue('store_code'));

        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->customAttributeTypeLocator = $objectManager
            ->getObject('Magento\Eav\Model\EavCustomAttributeTypeLocator');

        $this->_wsdlGenerator = $objectManager->getObject(
            'Magento\Webapi\Model\Soap\Wsdl\Generator',
            [
                'wsdlFactory' => $this->_wsdlFactoryMock,
                'cache' => $this->_cacheMock,
                'typeProcessor' => $this->_typeProcessor,
                'storeManager' => $this->storeManagerMock,
                'customAttributeTypeLocator' => $this->customAttributeTypeLocator,
                'serviceMetadata' => $this->serviceMetadata
            ]
        );

        parent::setUp();
    }

    /**
     * Test getElementComplexTypeName
     */
    public function testGetElementComplexTypeName()
    {
        $this->assertEquals("Test", $this->_wsdlGenerator->getElementComplexTypeName("test"));
    }

    /**
     * Test getPortTypeName
     */
    public function testGetPortTypeName()
    {
        $this->assertEquals("testPortType", $this->_wsdlGenerator->getPortTypeName("test"));
    }

    /**
     * Test getBindingName
     */
    public function testGetBindingName()
    {
        $this->assertEquals("testBinding", $this->_wsdlGenerator->getBindingName("test"));
    }

    /**
     * Test getPortName
     */
    public function testGetPortName()
    {
        $this->assertEquals("testPort", $this->_wsdlGenerator->getPortName("test"));
    }

    /**
     * test getServiceName
     */
    public function testGetServiceName()
    {
        $this->assertEquals("testService", $this->_wsdlGenerator->getServiceName("test"));
    }

    /**
     * @test
     */
    public function testGetInputMessageName()
    {
        $this->assertEquals("operationNameRequest", $this->_wsdlGenerator->getInputMessageName("operationName"));
    }

    /**
     * @test
     */
    public function testGetOutputMessageName()
    {
        $this->assertEquals("operationNameResponse", $this->_wsdlGenerator->getOutputMessageName("operationName"));
    }

    /**
     * Test exception for handle
     *
     * @expectedException        \Magento\Framework\Webapi\Exception
     * @expectedExceptionMessage exception message
     */
    public function testHandleWithException()
    {
        $genWSDL = 'generatedWSDL';
        $exceptionMsg = 'exception message';
        $requestedService = ['catalogProduct'];
        $serviceMetadata = ['methods' => ['methodName' => ['interface' => 'aInterface']]];

        $this->serviceMetadata->expects($this->any())
            ->method('getServiceMetadata')
            ->willReturn($serviceMetadata);
        $this->_typeProcessor->expects($this->once())
            ->method('processInterfaceCallInfo')
            ->willThrowException(new \Magento\Framework\Webapi\Exception(__($exceptionMsg)));

        $this->assertEquals(
            $genWSDL,
            $this->_wsdlGenerator->generate($requestedService, 'http://', 'magento.host', '/soap/default')
        );
    }
}


text:
package tradier

import "fmt"

// Balances returns the account's balance for clientID.
func (s *AccountService) Balances(accountID string) (*Balances, *Response, error) {
	u := fmt.Sprintf("accounts/%s/balances", accountID)

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	b := &Balances{}

	resp, err := s.client.Do(req, b)
	if err != nil {
		return nil, resp, err
	}

	return b, resp, nil
}


text:
class GeneratedPasswordSavedInfoBar : public infobars::InfoBarAndroid {
 public:
  explicit GeneratedPasswordSavedInfoBar(
      std::unique_ptr<GeneratedPasswordSavedInfoBarDelegateAndroid> delegate);

  GeneratedPasswordSavedInfoBar(const GeneratedPasswordSavedInfoBar&) = delete;
  GeneratedPasswordSavedInfoBar& operator=(
      const GeneratedPasswordSavedInfoBar&) = delete;

  ~GeneratedPasswordSavedInfoBar() override;

 private:
  // infobars::InfoBarAndroid implementation:
  base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar(
      JNIEnv* env,
      const ResourceIdMapper& resource_id_mapper) override;
  void OnLinkClicked(JNIEnv* env,
                     const base::android::JavaParamRef<jobject>& obj) override;
  void ProcessButton(int action) override;
};

#endif  // CHROME_BROWSER_UI_ANDROID_INFOBARS_GENERATED_PASSWORD_SAVED_INFOBAR_H_


text:
"""
[ref.href] leetcode.com/problems/contains-duplicate-ii
"
  Given an array of integers and an integer k, find out whether
  there are two distinct indices i and j in the array such that
  nums[i] = nums[j] and the difference between i and j is at most k.
"
"""

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dups = {}
        i = 0
        for n in nums:
            if n in dups:
                j = dups[n]
                if i - j <= k:
                    return True
            dups[n] = i
            i += 1
        return False


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.Activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"

        app:elevation="4dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_contract" />

    <com.ashokvarma.bottomnavigation.BottomNavigationBar
        android:id="@+id/bottom_nav_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">
    </com.ashokvarma.bottomnavigation.BottomNavigationBar>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/main_fab"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="72dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:srcCompat="@drawable/home_fab"
        app:layout_behavior="com.charon.www.younghawkdemo.biz.ScrollAwareFABBehavior" />

</android.support.design.widget.CoordinatorLayout>


text:
{-# LANGUAGE NoImplicitPrelude #-}

{-# LANGUAGE PatternGuards      #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Text.CSL.Output.Pandoc
-- Copyright   :  (c) Andrea Rossato
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Andrea Rossato <andrea.rossato@unitn.it>
-- Stability   :  unstable
-- Portability :  unportable
--
-- The pandoc output formatter for CSL
--
-----------------------------------------------------------------------------

module Text.CSL.Output.Pandoc
    ( renderPandoc
    , renderPandoc'
    , headInline
    , initInline
    , lastInline
    , tailInline
    , tailFirstInlineStr
    , toCapital
    ) where

import Prelude
import           Data.Maybe             (fromMaybe)
import           Text.CSL.Style
import           Text.CSL.Util          (headInline, initInline, lastInline,
                                         proc, proc', tailFirstInlineStr,
                                         tailInline, toCapital)
import           Text.Pandoc.Definition
import           Text.Pandoc.XML        (fromEntities)

renderPandoc :: Style -> Formatted -> [Inline]
renderPandoc sty
    = proc (convertQuoted sty) . proc' (clean' sty) . flipFlop .
      fixBreaks . unFormatted

-- remove leading/trailing LineBreak
fixBreaks :: [Inline] -> [Inline]
fixBreaks =
  dropWhile (== LineBreak) . reverse . dropWhile (== LineBreak) . reverse

renderPandoc' :: Style -> (Formatted, String) -> Block
renderPandoc' sty (form, citId) = Div ("ref-" ++ citId, [], []) [Para $ renderPandoc sty form]

clean' :: Style -> [Inline] -> [Inline]
clean' _   []  = []
clean' sty (i:is) =
  case i:is of
      (Str "" : rest) -> clean' sty rest
      (Str xs : Str ys : rest) -> clean' sty $ Str (xs ++ ys) : rest
      (Link a1 lab1 ('#':r1, "") : Str "\8211" : Link a2 lab2 ('#':r2, "") : rest)
        | r1 == r2, a1 == a2 ->
           Link a1 (lab1 ++ [Str "\8211"] ++ lab2) ('#':r1, "") : clean' sty rest
      (Span ("",[],[]) inls : _) -> inls ++ clean' sty is
      (Span ("",["csl-inquote"],kvs) inls : _) ->
         let isOuter = lookup "position" kvs == Just "outer"
         in  case headInline is of
                    [x] -> if x `elem` ".," && isPunctuationInQuote sty
                           then if lastInline inls `elem` [".",",",";",":","!","?"]
                                then quoted isOuter inls ++
                                     clean' sty (tailInline is)
                                else quoted isOuter (inls ++ [Str [x]]) ++
                                     clean' sty (tailInline is)
                           else quoted isOuter inls ++ clean' sty is
                    _   ->      quoted isOuter inls ++ clean' sty is
      (Quoted t inls : _) -> quoted (t == DoubleQuote) inls ++ clean' sty is
      _      -> if lastInline [i] == headInline is && isPunct
                   then i : clean' sty (tailInline is)
                   else i : clean' sty is
    where
      isPunct = all (`elem` ".,;:!? ") $ headInline is
      locale  = case styleLocale sty of
                     (x:_) -> x
                     []    -> Locale [] [] [] [] [] -- should not happen
      getQuote s d     = case [term | term <- localeTerms locale, cslTerm term == s] of
                               (x:_) -> Str (termSingular x)
                               _     -> Str d
      openQuoteOuter   = getQuote "open-quote" """
      openQuoteInner   = getQuote "open-inner-quote" "'"
      closeQuoteOuter  = getQuote "close-quote" """
      closeQuoteInner  = getQuote "close-inner-quote" "'"
      quoted True ils  = openQuoteOuter : ils ++ [closeQuoteOuter]
      quoted False ils = openQuoteInner : ils ++ [closeQuoteInner]

convertQuoted :: Style -> [Inline] -> [Inline]
convertQuoted s = convertQuoted'
    where
      locale = let l = styleLocale s in case l of [x] -> x; _   -> Locale [] [] [] [] []
      getQuote  x y = fromEntities . termSingular . fromMaybe newTerm {termSingular = x} .
                      findTerm y Long . localeTerms $ locale
      doubleQuotesO = getQuote "\"" "open-quote"
      doubleQuotesC = getQuote "\"" "close-quote"
      singleQuotesO = getQuote "'"  "open-inner-quote"
      singleQuotesC = getQuote "'"  "close-inner-quote"
      convertQuoted' o
          | (Quoted DoubleQuote t:xs) <- o = Str doubleQuotesO : t ++ Str doubleQuotesC : convertQuoted' xs
          | (Quoted SingleQuote t:xs) <- o = Str singleQuotesO : t ++ Str singleQuotesC : convertQuoted' xs
          | (x                   :xs) <- o = x : convertQuoted' xs
          | otherwise                      = []

-- flip-flop

data FlipFlopState = FlipFlopState
     { inEmph        :: Bool
     , inStrong      :: Bool
     , inSmallCaps   :: Bool
     , inOuterQuotes :: Bool
     }

flipFlop :: [Inline] -> [Inline]
flipFlop = map (flipFlop' $ FlipFlopState False False False False)

flipFlop' :: FlipFlopState -> Inline -> Inline
flipFlop' st (Emph ils) =
  (if inEmph st then Span ("",["csl-no-emph"],[]) else Emph)
  $ map (flipFlop' st{ inEmph = not $ inEmph st }) ils
flipFlop' st (Strong ils) =
  (if inStrong st then Span ("",["csl-no-strong"],[]) else Strong)
  $ map (flipFlop' st{ inStrong = not $ inStrong st }) ils
flipFlop' st (SmallCaps ils) =
  (if inSmallCaps st then Span ("",["csl-no-smallcaps"],[]) else SmallCaps)
  $ map (flipFlop' st{ inSmallCaps = not $ inSmallCaps st }) ils
flipFlop' st (Strikeout ils) =
  Strikeout $ map (flipFlop' st) ils
flipFlop' st (Superscript ils) =
  Superscript $ map (flipFlop' st) ils
flipFlop' st (Subscript ils) =
  Subscript $ map (flipFlop' st) ils
flipFlop' st (Quoted _ ils) =
  Quoted (if inOuterQuotes st then SingleQuote else DoubleQuote)
  $ map (flipFlop' st{ inOuterQuotes = not $ inOuterQuotes st }) ils
flipFlop' st (Span (_, ["csl-inquote"], _) ils) =
  Span ("", ["csl-inquote"], [("position", if inOuterQuotes st then "inner" else "outer")])
  $ map (flipFlop' st{ inOuterQuotes = not $ inOuterQuotes st }) ils
flipFlop' st (Span (id',classes,kvs) ils)
  | "nodecor" `elem` classes = Span (id',classes',kvs) $ map (flipFlop' st) ils
  | otherwise = Span (id',classes,kvs) $ map (flipFlop' st) ils
     where classes' = filter (/= "nodecor") classes ++
                       ["csl-no-emph"      | inEmph st] ++
                       ["csl-no-strong"    | inStrong st] ++
                       ["csl-no-smallcaps" | inSmallCaps st]
flipFlop' st (Link attr ils t) =
  Link attr (map (flipFlop' st) ils) t
flipFlop' st (Note [Para ils]) =
  Note [Para $ map (flipFlop' st) ils]
flipFlop' _ il = il