text:
import * as util from '../../utils'
import Keyboard from '../Keyboard'
import Phaser from 'phaser'

// sizing and positioning constants
const WIDTH = 100
const HEIGHT = 100
const MARGIN = 4
const STROKE = 2
const TEXT_OFFSET = 20
const IMAGE_OFFSET = 28

export default class extends Phaser.Group {
    /**
     * Constructor
     *
     * @param game         Game object
     * @param x            Horizontal position
     * @param y            Vertical position
     * @param keys         Key bindings
     * @param keysPosition Where to display the key bindings: left or right
     */
    constructor (game, x, y, keys, keysPosition) {
        super(game)
        this.x = x
        this.y = y
        this.keys = keys
        this.keysPosition = keysPosition

        this._initialize()
        this._addKeyInfo()
        this._addSelector()
        this._addPlayers()
        this._updateSelectorPosition()
        this._initKeys()
    }

    /**
     * Check if the player type has been chosen
     *
     * @returns {boolean|*}
     */
    isConfirmed() {
        return this.confirmed
    }

    /**
     * Get the selected player type
     */
    getSelected() {
        return this.types[this.selection]
    }

    /**
     * Initialize some properties
     *
     * @private
     */
    _initialize() {
        let game = this.game

        // select first player by default
        this.selection = 0
        this.confirmed = false

        this.playerData = game.cache.getJSON("players")

        // available player types
        this.types = []
        for (let type in this.playerData)
            this.types.push(type)

        // sound to play when selection changes
        this.changeSelectionSound = game.add.audio("menu_player_change")

        // sound to play when confirming the player selection
        this.confirmSound = game.add.audio("menu_player_confirm")
    }

    /**
     * Add a handler for key down event
     *
     * @private
     */
    _initKeys() {
        this.game.keyboard.onDown.add(
            function(char) {
                if (this.confirmed)
                    return

                let current = this.selection

                switch (char["code"]) {
                    // player 1 selector keys
                    case this.keys["up"]:
                        this.selection = Math.max(this.selection - 1, 0)

                        if (current != this.selection) {
                            this.playerSprites[current].animations.stop()
                            this._updateSelectorPosition()
                            this.changeSelectionSound.play()
                        }
                        break

                    case this.keys["down"]:
                        this.selection = Math.min(this.selection + 1, this.types.length - 1)

                        if (current != this.selection) {
                            this.playerSprites[current].animations.stop()
                            this._updateSelectorPosition()
                            this.changeSelectionSound.play()
                        }
                        break

                    case this.keys["fire_primary"]:
                    case this.keys["fire_secondary"]:
                        this.confirmed = true
                        this.game.time.events.remove(this.selectionTimer)
                        this._drawSelectionRectangle()
                        this.confirmSound.play()
                        this.playerSprites[this.selection].animations.stop()
                        break
                }
            },
            this
        )
    }

    /**
     * Add selection rectangle
     *
     * @private
     */
    _addSelector() {
        let game = this.game

        // alternating colors for the selection rectangle
        this.alternatingColors = [0xfa6121, 0xffb739]
        this.alternatingColorsIndex = 0

        // color of the selection rectangle background
        this.selectionBgColor = 0x001821

        // color of selection rectangle after a player is chosen
        this.selectedColor = 0x198500

        this.selector = game.add.graphics()
        this._drawSelectionRectangle()

        // register the timer to alternate the colors
        this.selectionTimer = game.time.events.loop(150, this._drawSelectionRectangle, this);
    }

    /**
     * Draw the selection rectangle, alternating the colors
     *
     * @private
     */
    _drawSelectionRectangle() {
        let color = undefined

        if (this.confirmed) {
            color = this.selectedColor
        } else {
            this.alternatingColorsIndex = 1 - this.alternatingColorsIndex
            color = this.alternatingColors[this.alternatingColorsIndex]
        }

        this.selector.lineStyle(STROKE, color)
        this.selector.beginFill(this.selectionBgColor);
        this.selector.drawRect(0, 0, WIDTH + STROKE, HEIGHT + STROKE)
    }

    /**
     * Move the selection rectangle on the currently selected item
     *
     * @private
     */
    _updateSelectorPosition() {
        this.selector.x = this.x
        this.selector.y = this.y + (HEIGHT + MARGIN) * this.selection
        this.playerSprites[this.selection].animations.play("walk")
    }

    /**
     * Add info about key bindings
     *
     * @private
     */
    _addKeyInfo() {
        let game = this.game

        let xMul = this.keysPosition == "left" ? 1 : -1
        let textAlign = this.keysPosition == "left" ? "right" : "left"
        let textAnchor = this.keysPosition == "left" ? 1 : 0

        let x = this.x
        if (this.keysPosition == "right")
            x += WIDTH

        // key for previous item
        let y = this.y

        let text = new Phaser.Text(game, x - xMul * 40, y + 75, Keyboard.shortName(this.keys["up"]))
        text.font = 'Arial'
        text.fontSize = 14
        text.fill = '#fff'
        text.align = textAlign
        text.anchor.setTo(textAnchor, 0)
        game.add.existing(text)

        let sprite = game.add.sprite(x - xMul * 25, y, "menu_player_up")
        sprite.anchor.setTo(0.5, 0)

        // keys for confirmation
        y = this.y + (HEIGHT * this.types.length + MARGIN * (this.types.length - 1)) / 2
        text = new Phaser.Text(game, x - xMul * 40, y, "Confirm:\n" + Keyboard.shortName(this.keys["fire_primary"]) + "\n" + Keyboard.shortName(this.keys["fire_secondary"]))
        text.font = 'Arial'
        text.fontSize = 14
        text.fill = '#fff'
        text.align = textAlign
        text.anchor.setTo(textAnchor, 0.5)
        game.add.existing(text)

        // key for next item
        y = this.y + HEIGHT * this.types.length + MARGIN * (this.types.length - 1)

        text = new Phaser.Text(game, x - xMul * 40, y - 75, Keyboard.shortName(this.keys["down"]))
        text.font = 'Arial'
        text.fontSize = 14
        text.fill = '#fff'
        text.align = textAlign
        text.anchor.setTo(textAnchor, 1)
        game.add.existing(text)

        sprite = game.add.sprite(x - xMul * 25, y, "menu_player_down")
        sprite.anchor.setTo(0.5, 1)
    }

    /**
     * Add player images and names
     *
     * @private
     */
    _addPlayers() {
        let game = this.game

        let x = this.x
        let y = this.y

        this.playerSprites = []

        for (let i in this.types) {
            let type = this.types[i]
            // image
            let sprite = game.add.sprite(x + WIDTH / 2, y + HEIGHT - IMAGE_OFFSET, type + "_player")
            sprite.anchor.setTo(0.5, 1)
            this.playerSprites.push(sprite)

            let data = this.playerData[type]["sprite"]["left"]["animation"]
            sprite.animations.add('walk', util.animationFramesFromRange(data), data['rate'], true)

            // name
            let text = new Phaser.Text(game, x + WIDTH / 2, y + HEIGHT - TEXT_OFFSET, this.playerData[type]["name"])
            text.font = 'Paytone One'
            text.fontSize = 11
            text.fill = '#fff'
            text.anchor.setTo(0.5, 0)
            game.add.existing(text)

            y += HEIGHT + MARGIN
        }
    }
}


text:
remote=$1
url=$2
local_ref=$3
local_sha=$4
remote_ref=$5
remote_sha=$6
z40=0000000000000000000000000000000000000000

set -e exec

echo "Run push "

if [ "$local_sha" = $z40 ]
then
	# Handle delete
	:
else
	# At each (forced) push, examine all commits since $remote/main
	base_commit=`git rev-parse $remote/main`
	range="$base_commit..$local_sha"

	echo "Perform check patch"
	${ZEPHYR_BASE}/scripts/checkpatch.pl --git $range
fi

redpajama_set_name: RedPajamaGithub


text:
graci
=====

Graciela Arango - Personal Website


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;

namespace WebApiInAppWindows.Security
{
    public static class ClaimsPrincipalExtensions
    {
        public static bool IsOperator(this ClaimsPrincipal principal)
        {
            return principal.HasClaim(ClaimTypes.Role, "Operator");
        }
    }
}


text:
#import "KGWebSocketSelectedChannel.h"
#import "KGCreateChannel.h"
#import "KGDownstreamChannel.h"

@class KGUpstreamChannel;

@interface KGWebSocketEmulatedChannel : KGWebSocketSelectedChannel

// ctor:
-(id)initWithLocation:(KGWSURI *)location binary:(BOOL)isBinary;

// package private
-(void) setCreateChannel:(KGCreateChannel *)createChannel;
-(KGCreateChannel *)createChannel;
-(void) setUpstreamChannel:(KGUpstreamChannel *)upstreamChannel;
-(KGUpstreamChannel *)upstreamChannel;
-(void) setDownstreamChannel:(KGDownstreamChannel *)downstreamChannel;
-(KGDownstreamChannel *)downstreamChannel;

-(void) setRedirectUri:(KGHttpURI *) redirectUri;
-(KGHttpURI *) redirectUri;

//protected:
-(void) setCookie:(NSString*)cookie;
-(NSString*) cookie;

@end


text:
#include "modules/localization/common/localization_gflags.h"

DEFINE_string(localization_module_name, "localization",
              "localization module name");

DEFINE_double(localization_publish_freq, 100,
              "localization publishing frequency.");

DEFINE_string(localization_config_file,
              "/apollo/modules/localization/conf/localization_config.pb.txt",
              "localization config file");

// features
DEFINE_bool(enable_gps_imu_interprolate, true, "enable GPU/IMU interprolate");
DEFINE_bool(enable_map_reference_unify, true,
            "enable IMU data convert to map reference");
DEFINE_bool(enable_watchdog, true, "enable watchdog");

DEFINE_double(gps_time_delay_tolerance, 1.0,
              "gps message time delay tolerance (sec)");

DEFINE_double(gps_imu_timestamp_sec_diff_tolerance, 20e-3,
              "gps/imu timestamp diff tolerance (sec)");

DEFINE_double(timestamp_sec_tolerance, 10e-7, "timestamp second tolerance");
// map offset
DEFINE_double(map_offset_x, 0.0, "map_offsite: x");
DEFINE_double(map_offset_y, 0.0, "map_offsite: y");
DEFINE_double(map_offset_z, 0.0, "map_offsite: z");

DEFINE_int32(report_threshold_err_num, 10, "report threshold error num");
DEFINE_double(report_gps_imu_time_diff_threshold, 0.02,
              "report threshold of timestamp diff between gps and imu(sec)");

DEFINE_bool(enable_gps_timestamp, false,
            "True to set gps timestamp as localization header timestamp");

// msf parame
DEFINE_string(local_map_name, "local_map", "The path of localization map.");
DEFINE_string(lidar_extrinsics_file,
              "/apollo/modules/localization/msf/params/velodyne_params/"
              "velodyne64_novatel_extrinsics_example.yaml",
              "Lidar extrinsics parameter file.");
DEFINE_string(lidar_height_file,
              "/apollo/modules/localization/msf/params/velodyne_params/"
              "velodyne64_height.yaml",
              "Velodyne extrinsic path for the vehicle in use, "
              "where <ros> is the placeholder of ROS root.");
DEFINE_double(lidar_height_default, 1.80,
              "The height from the center of velodyne to ground.");
DEFINE_int32(
    lidar_localization_mode, 2,
    "Localization mode, 0 for intensity, 1 for altitude, 2 for fusion.");
DEFINE_int32(lidar_yaw_align_mode, 2,
             "image yaw align mode, 0 for align off, "
             "1 for fusion, 2 for fusion with multithread.");
DEFINE_int32(lidar_filter_size, 17, "Lidar filter size");
DEFINE_double(lidar_imu_max_delay_time, 0.4,
              "Lidar msg and imu msg max delay time");
DEFINE_double(lidar_map_coverage_theshold, 0.9,
              "Threshold to detect whether vehicle is out of map");
DEFINE_bool(lidar_debug_log_flag, false, "Lidar Debug switch.");
DEFINE_int32(point_cloud_step, 2, "Point cloud step");
DEFINE_bool(if_use_avx, false,
            "if use avx to accelerate lidar localization, "
            "need cpu to support AVX intel instrinsics");

// integ module
DEFINE_bool(integ_ins_can_self_align, false, "");
DEFINE_bool(integ_sins_align_with_vel, true, "");
DEFINE_bool(integ_sins_state_check, false, "");
DEFINE_double(integ_sins_state_span_time, 60.0, "");
DEFINE_double(integ_sins_state_pos_std, 1.0, "");
DEFINE_double(vel_threshold_get_yaw, 5.0, "");

// gnss module
DEFINE_bool(enable_ins_aid_rtk, false, "");
DEFINE_string(eph_buffer_path, "", "");
DEFINE_string(
    ant_imu_leverarm_file,
    "/apollo/modules/localization/msf/params/gnss_params/ant_imu_leverarm.yaml",
    "Ant to imu leferarm.");
DEFINE_bool(gnss_debug_log_flag, false, "Gnss Debug switch.");
DEFINE_bool(if_imuant_from_file, true, "Use imu ant from gnss configure file.");
DEFINE_double(imu_to_ant_offset_x, 0.0, "Imu ant offset x");
DEFINE_double(imu_to_ant_offset_y, 0.0, "Imu ant offset y");
DEFINE_double(imu_to_ant_offset_z, 0.0, "Imu ant offset z");
DEFINE_double(imu_to_ant_offset_ux, 0.0, "Imu ant offset x uncertainty");
DEFINE_double(imu_to_ant_offset_uy, 0.0, "Imu ant offset y uncertainty");
DEFINE_double(imu_to_ant_offset_uz, 0.0, "Imu ant offset z uncertainty");

// common
DEFINE_double(imu_rate, 1.0, "");
DEFINE_bool(if_utm_zone_id_from_folder, true,
            "load utm zone id from local map folder");
DEFINE_bool(trans_gpstime_to_utctime, true, "");
DEFINE_int32(gnss_mode, 0, "GNSS Mode, 0 for bestgnss pose, 1 for self gnss.");
DEFINE_bool(imu_coord_rfu, true, "Right/forward/up");
DEFINE_bool(gnss_only_init, false,
            "Whether use bestgnsspose as measure after initializaiton.");
DEFINE_bool(enable_lidar_localization, true,
            "Enable lidar-based localization.");

DEFINE_string(lidar_topic, "/apollo/sensor/lidar128/compensator/PointCloud2",
              "lidar pointcloud topic");
DEFINE_string(broadcast_tf_frame_id, "world", "world frame id in tf");
DEFINE_string(broadcast_tf_child_frame_id, "localization",
              "localization frame id in tf");
// imu vehicle extrinsic
DEFINE_string(vehicle_imu_file,
              "/apollo/modules/localization/msf/params"
              "/vehicle_params/vehicle_imu_extrinsics.yaml",
              "Vehicle coord to imu coord.");
DEFINE_bool(if_vehicle_imu_from_file, true,
            "Whether load vehicle imu extrinsic from yaml file");
DEFINE_double(imu_vehicle_qx, 0.0, "Vehicle imu quaternion qx");
DEFINE_double(imu_vehicle_qy, 0.0, "Vehicle imu quaternion qy");
DEFINE_double(imu_vehicle_qz, 0.0, "Vehicle imu quaternion qz");
DEFINE_double(imu_vehicle_qw, 1.0, "Vehicle imu quaternion qw");

// visualization
DEFINE_string(map_visual_dir, "data/map_visual",
              "The path of map_visual folder.");

// Status
DEFINE_double(imu_delay_time_threshold_1, 0.1,
              "imu delay time is larger than 0.1s");
DEFINE_double(imu_delay_time_threshold_2, 0.05,
              "imu delay time is larger than 0.05s");
DEFINE_double(imu_delay_time_threshold_3, 0.02,
              "imu delay time is larger than 0.02s");

DEFINE_double(imu_missing_time_threshold_1, 0.1,
              "imu missing time is larger than 0.1s");
DEFINE_double(imu_missing_time_threshold_2, 0.05,
              "imu missing time is larger than 0.05s");
DEFINE_double(imu_missing_time_threshold_3, 0.01,
              "imu missing time is larger than 0.01s");

DEFINE_double(bestgnsspose_loss_time_threshold, 2.0,
              "threshold for time gap between imu and bestgnsspose time");
DEFINE_double(lidar_loss_time_threshold, 2.0,
              "threshold for time gap between imu and lidar pose time");

DEFINE_double(localization_std_x_threshold_1, 0.15,
              "threshold for lateral std of localization result");
DEFINE_double(localization_std_y_threshold_1, 0.15,
              "threshold for longitudinal std of localization result");

DEFINE_double(localization_std_x_threshold_2, 0.3,
              "threshold for lateral std of localization result");
DEFINE_double(localization_std_y_threshold_2, 0.3,
              "threshold for longitudinal std of localization result");

// ndt localization
DEFINE_string(ndt_map_dir, "ndt_map", "subdirectory for ndt map");
DEFINE_bool(ndt_debug_log_flag, false, "NDT Localization log switch");
DEFINE_double(online_resolution, 2.0, "NDT online pointcloud resolution");
DEFINE_int32(ndt_max_iterations, 10, "maximum iterations for NDT matching");
DEFINE_double(ndt_target_resolution, 1.0,
              "target resolution for ndt localization");
DEFINE_double(ndt_line_search_step_size, 0.1,
              "line search step size for ndt matching");
DEFINE_double(ndt_transformation_epsilon, 0.01,
              "iteration convergence condition on transformation");
DEFINE_int32(ndt_filter_size_x, 48, "x size for ndt searching area");
DEFINE_int32(ndt_filter_size_y, 48, "y size for ndt searching area");
DEFINE_int32(ndt_bad_score_count_threshold, 10,
             "count for continuous bad ndt fitness score");
DEFINE_double(ndt_warnning_ndt_score, 1.0,
              "warnning ndt fitness score threshold");
DEFINE_double(ndt_error_ndt_score, 2.0, "error ndt fitness score threshold");


text:
#ifndef BaseLib_Functors_Functor7_h
#define BaseLib_Functors_Functor7_h

#include "BaseLib/Functors/FunctorType.h"
#include "BaseLib/Functors/EventObserver.h"

namespace BaseLib {
namespace Functors {

template<typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
class Functor7 {
public:

	typedef R ResultType;
	typedef A0 Argument0Type;
	typedef A1 Argument1Type;
	typedef A2 Argument2Type;
	typedef A3 Argument3Type;
	typedef A4 Argument4Type;
	typedef A5 Argument5Type;
	typedef A6 Argument6Type;

	virtual ~Functor7<R, A0, A1, A2, A3, A4, A5, A6>() {}

	virtual R execute(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const = 0;

	inline R operator ()(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const
	{
		return execute(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
	}

	virtual FunctorType getFunctorType() const = 0;
	virtual bool operator ==(const Functor7& right) const = 0;
	virtual Functor7<R, A0, A1, A2, A3, A4, A5, A6>* clone() const = 0;
};

template<typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
class FunctionFunctor7 : public Functor7<R, A0, A1, A2, A3, A4, A5, A6> {
public:

	typedef R (*Function)(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6);

	FunctionFunctor7<R, A0, A1, A2, A3, A4, A5, A6>(Function forFunction)
		: function(forFunction)
	{
	}

	virtual R execute(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const
	{
		return (*function)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
	}

	virtual FunctorType getFunctorType() const
	{
		return FUNCTION_FUNCTOR;
	}

	virtual bool operator ==(const Functor7<R, A0, A1, A2, A3, A4, A5, A6>& right) const
	{
		return right.getFunctorType() == FUNCTION_FUNCTOR && function == static_cast<const FunctionFunctor7&>(right).function;
	}

	virtual FunctionFunctor7<R, A0, A1, A2, A3, A4, A5, A6>* clone() const
	{
		return new FunctionFunctor7<R, A0, A1, A2, A3, A4, A5, A6>(function);
	}

private:

	Function function;

};

template<class C, typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
class MethodFunctor7 : public Functor7<R, A0, A1, A2, A3, A4, A5, A6> {
public:

	typedef R (C::*Method)(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6);

	MethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>(C* atObject, Method forMethod)
		: object(atObject)
		, method(forMethod)
	{
	}

	virtual R execute(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const
	{
		return (object->*method)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
	}

	inline C* getObject() const
	{
		return object;
	}

	inline void setObject(C* newObject)
	{
		object = newObject;
	}

	inline Method getMethod() const
	{
		return method;
	}

	inline void setMethod(Method newMethod)
	{
		method = newMethod;
	}

	virtual FunctorType getFunctorType() const
	{
		return METHOD_FUNCTOR;
	}

	virtual bool operator ==(const Functor7<R, A0, A1, A2, A3, A4, A5, A6>& right) const
	{
		return right.getFunctorType() == METHOD_FUNCTOR && object == static_cast<const MethodFunctor7&>(right).object && method == static_cast<const MethodFunctor7&>(right).method;
	}

	virtual MethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>* clone() const
	{
		return new MethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>(object, method);
	}

private:

	mutable C* object;
	Method method;

};

template<class C, typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6>
class ConstMethodFunctor7 : public Functor7<R, A0, A1, A2, A3, A4, A5, A6> {
public:

	typedef R (C::*Method)(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const;

	ConstMethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>(const C* atObject, Method forMethod)
		: object(atObject)
		, method(forMethod)
	{
	}

	virtual R execute(A0 arg0, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5, A6 arg6) const
	{
		return (object->*method)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
	}

	inline const C* getObject() const
	{
		return object;
	}

	inline void setObject(const C* newObject)
	{
		object = newObject;
	}

	inline Method getMethod() const
	{
		return method;
	}

	inline void setMethod(Method newMethod)
	{
		method = newMethod;
	}

	virtual FunctorType getFunctorType() const
	{
		return METHOD_FUNCTOR;
	}

	virtual bool operator ==(const Functor7<R, A0, A1, A2, A3, A4, A5, A6>& right) const
	{
		return right.getFunctorType() == METHOD_FUNCTOR && object == static_cast<const ConstMethodFunctor7&>(right).object && method == static_cast<const ConstMethodFunctor7&>(right).method;
	}

	virtual ConstMethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>* clone() const
	{
		return new ConstMethodFunctor7<C, R, A0, A1, A2, A3, A4, A5, A6>(object, method);
	}

private:

	const C* object;
	Method method;

};

} // namespace Functors
} // namespace BaseLib

#endif // #ifndef BaseLib_Functors_Functor7_h


text:
// Copyright (c) Arch team. All rights reserved.

namespace Microsoft.AspNetCore.ApiHelp {
    /// <summary>
    /// Represents the all options will be used to configure Api help UI.
    /// </summary>
    public class ApiHelpUIOptions {
        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        /// <value>The title.</value>
        public string Title { get; set; } = "API toolchain for ASP.NET Core";
        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        /// <value>The description.</value>
        public string Description { get; set; } = "A toolchain for ASP.NET Core to automatically generating API documentation.";
        /// <summary>
        /// Gets or sets the base route.
        /// </summary>
        /// <value>The base route.</value>
        public string BaseRoute { get; set; } = "api/help/ui";
        /// <summary>
        /// Gets the index path.
        /// </summary>
        /// <value>The index path.</value>
        public string IndexPath => BaseRoute.Trim('/') + "/index.html";
        /// <summary>
        /// Gets or sets the UI.
        /// </summary>
        /// <value>The UI.</value>
        public ApiHelpUI UI { get; set; } = ApiHelpUI.Swagger;
    }
}


text:
require 'spec_helper'

describe JIRA::Resource::Worklog do

  with_each_client do |site_url, client|
    let(:client) { client }
    let(:site_url) { site_url }

    let(:key) { "10000" }

    let(:target) { JIRA::Resource::Worklog.new(client, :attrs => {'id' => '99999'}, :issue_id => '54321') }

    let(:expected_collection_length) { 3 }

    let(:belongs_to) {
      JIRA::Resource::Issue.new(client, :attrs => {
        'id' => '10002', 'fields' => {
          'comment' => {'comments' => []}
        }
      })
    }

    let(:expected_attributes) do
      {
        'self' => "http://localhost:2990/jira/rest/api/2/issue/10002/worklog/10000",
        'id'   => key,
        'comment' => "Some epic work."
      }
    end

    let(:attributes_for_post) {
      {"timeSpent" => "2d"}
    }
    let(:expected_attributes_from_post) {
      { "id" => "10001", "timeSpent" => "2d"}
    }

    let(:attributes_for_put) {
      {"timeSpent" => "2d"}
    }
    let(:expected_attributes_from_put) {
      { "id" => "10001", "timeSpent" => "4d"}
    }

    it_should_behave_like "a resource"
    it_should_behave_like "a resource with a collection GET endpoint"
    it_should_behave_like "a resource with a singular GET endpoint"
    it_should_behave_like "a resource with a DELETE endpoint"
    it_should_behave_like "a resource with a POST endpoint"
    it_should_behave_like "a resource with a PUT endpoint"

  end
end


text:
<?php
declare(strict_types = 1);

namespace User\Entity;

/**
 * User Entity Interface
 *
 * @author Thiago Paes <mrprompt@gmail.com>
 */
interface UserInterface
{
    /**
     * Get the Id
     *
     * @return int
     */
    public function getId(): int;

    /**
     * Get the Name
     *
     * @return string
     */
    public function getName(): string;

    /**
     * Set Name
     *
     * @param string $name
     * @return void
     * @throws \InvalidArgumentException
     */
    public function setName(string $name);

    /**
     * Get the email
     *
     * @return string
     */
    public function getEmail(): string;

    /**
     * Set the email
     *
     * @param string $email
     * @return void
     * @throws \InvalidArgumentException
     */
    public function setEmail(string $email);

    /**
     * Mark user as deleted
     *
     * @return bool
     */
    public function delete(): bool;
}


text:
package org.apache.solr.search.grouping.distributed.requestfactory;

import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.GroupParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.ShardParams;
import org.apache.solr.handler.component.ResponseBuilder;
import org.apache.solr.handler.component.ShardRequest;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.grouping.GroupingSpecification;
import org.apache.solr.search.grouping.distributed.ShardRequestFactory;

/**
 * Concrete implementation of {@link ShardRequestFactory} that creates {@link ShardRequest} instances for getting the
 * search groups from all shards.
 */
public class SearchGroupsRequestFactory implements ShardRequestFactory {

  /**
   * {@inheritDoc}
   */
  @Override
  public ShardRequest[] constructRequest(ResponseBuilder rb) {
    ShardRequest sreq = new ShardRequest();
    GroupingSpecification groupingSpecification = rb.getGroupingSpec();
    if (groupingSpecification.getFields().length == 0) {
      return new ShardRequest[0];
    }

    sreq.purpose = ShardRequest.PURPOSE_GET_TOP_GROUPS;

    sreq.params = new ModifiableSolrParams(rb.req.getParams());
    // TODO: base on current params or original params?

    // don't pass through any shards param
    sreq.params.remove(ShardParams.SHARDS);

    // set the start (offset) to 0 for each shard request so we can properly merge
    // results from the start.
    if(rb.shards_start > -1) {
      // if the client set shards.start set this explicitly
      sreq.params.set(CommonParams.START,rb.shards_start);
    } else {
      sreq.params.set(CommonParams.START, "0");
    }
    // TODO: should we even use the SortSpec?  That's obtained from the QParser, and
    // perhaps we shouldn't attempt to parse the query at this level?
    // Alternate Idea: instead of specifying all these things at the upper level,
    // we could just specify that this is a shard request.
    if(rb.shards_rows > -1) {
      // if the client set shards.rows set this explicity
      sreq.params.set(CommonParams.ROWS,rb.shards_rows);
    } else {
      sreq.params.set(CommonParams.ROWS, rb.getSortSpec().getOffset() + rb.getSortSpec().getCount());
    }

    // in this first phase, request only the unique key field
    // and any fields needed for merging.
    sreq.params.set(GroupParams.GROUP_DISTRIBUTED_FIRST, "true");

    if ( (rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES)!=0 || rb.getSortSpec().includesScore()) {
      sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName() + ",score");
    } else {
      sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName());
    }
    return new ShardRequest[] {sreq};
  }

}


text:
#ifndef WIN32_INTEROP_COMMON_H
#define WIN32_INTEROP_COMMON_H

#include <Windows.h>

bool IsWindowsVersionAtLeast(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor);

#endif


text:
namespace Algolia.Search.Models.Enums
{
    /// <summary>
    /// https://www.algolia.com/doc/guides/textual-relevance/synonyms/#synonyms-overview
    /// </summary>
    public class SynonymType
    {
        /// <summary>
        /// Synonym
        /// </summary>
        public const string Synonym = "synonym";

        /// <summary>
        /// One way synonm
        /// </summary>
        public const string OneWaySynonym = "oneWaySynonym";

        /// <summary>
        /// Alt correction
        /// </summary>
        public const string AltCorrection1 = "altCorrection1";

        /// <summary>
        /// Alt correction
        /// </summary>
        public const string AltCorrection2 = "altCorrection2";

        /// <summary>
        /// Placeholder
        /// </summary>
        public const string Placeholder = "placeholder";
    }
}


text:
<?php

declare(strict_types = 1);

namespace Rx\Observable;

use RuntimeException;
use Rx\Scheduler;
use Rx\TestCase;

class ErrorObservableTest extends TestCase
{
    /** @test */
    public function it_calls_observers_with_error()
    {
        $ex         = new RuntimeException('boom!');
        $observable = new ErrorObservable($ex, Scheduler::getDefault());

        $recordedException = null;
        $observable->subscribe(
            function () {
            },
            function ($ex) use (&$recordedException) {
                $recordedException = $ex;
            },
            function () {
            }
        );

        $this->assertEquals($ex, $recordedException);
    }
}


text:
package org.thunder.mpdcontrol.helpers;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import org.thunder.mpdcontrol.MainApplication;
import org.thunder.mpdcontrol.mpd.MPD;
import org.thunder.mpdcontrol.mpd.MPDStatus;
import org.thunder.mpdcontrol.mpd.MPDStatusMonitor;
import org.thunder.mpdcontrol.mpd.event.StatusChangeListener;
import org.thunder.mpdcontrol.mpd.event.TrackPositionListener;
import org.thunder.mpdcontrol.mpd.exception.MPDServerException;
import org.thunder.mpdcontrol.tools.Tools;
import org.thunder.mpdcontrol.tools.WeakLinkedList;

import java.net.UnknownHostException;
import java.util.Collection;

public class MPDAsyncHelper extends Handler
{

    public interface AsyncExecListener
    {
        public boolean asyncExecSucceeded(int jobID);
    }

    public interface ConnectionListener
    {
        public void connectionFailed(String message);
        public void connectionSucceeded(String message);
    }

    public class MPDAsyncWorker extends Handler implements StatusChangeListener, TrackPositionListener
    {
        public MPDAsyncWorker(Looper looper)
        {
            super(looper);
        }

        @Override
        public void connectionStateChanged(boolean connected, boolean connectionLost)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTIONSTATE, Tools.toObjectArray(connected, connectionLost)).sendToTarget();
        }

        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case EVENT_CONNECT:
                    try
                    {
                        MPDConnectionInfo conInfo = (MPDConnectionInfo) msg.obj;
                        if (oMPD != null)
                        {
                            oMPD.connect(conInfo.sServer, conInfo.iPort, conInfo.sPassword);
                            MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTSUCCEEDED) .sendToTarget();
                        }
                    }
                    catch (MPDServerException e)
                    {
                        MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTFAILED, Tools.toObjectArray(e.getMessage())).sendToTarget();
                    }
                    catch (UnknownHostException e)
                    {
                        MPDAsyncHelper.this.obtainMessage(EVENT_CONNECTFAILED, Tools.toObjectArray(e.getMessage())).sendToTarget();
                    }
                    break;

                case EVENT_STARTMONITOR:
                    oMonitor = new MPDStatusMonitor(oMPD, 500);
                    oMonitor.addStatusChangeListener(this);
                    oMonitor.addTrackPositionListener(this);
                    oMonitor.start();
                    break;

                case EVENT_STOPMONITOR:
                    if (oMonitor != null) oMonitor.giveup();
                    break;

                case EVENT_DISCONNECT:
                    try
                    {
                        if (oMPD != null) oMPD.disconnect();
                        Log.d(MainApplication.TAG, "Disconnected");
                    }
                    catch (MPDServerException e)
                    {
                        Log.e(MainApplication.TAG, "Error on disconnect", e);
                    }
                    break;

                case EVENT_EXECASYNC:
                    Runnable run = (Runnable) msg.obj;
                    run.run();
                    MPDAsyncHelper.this.obtainMessage(EVENT_EXECASYNCFINISHED, msg.arg1, 0) .sendToTarget();

                default:
                    break;
            }
        }

        @Override
        public void libraryStateChanged(boolean updating)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_UPDATESTATE, Tools.toObjectArray(updating)).sendToTarget();
        }

        @Override
        public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_PLAYLIST,Tools.toObjectArray(mpdStatus, oldPlaylistVersion)).sendToTarget();
        }

        @Override
        public void randomChanged(boolean random)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_RANDOM, Tools.toObjectArray(random)).sendToTarget();
        }

        @Override
        public void repeatChanged(boolean repeating)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_REPEAT, Tools.toObjectArray(repeating)).sendToTarget();
        }

        @Override
        public void stateChanged(MPDStatus mpdStatus, String oldState)
        {
            MPDAsyncHelper.this .obtainMessage(EVENT_STATE, Tools.toObjectArray(mpdStatus, oldState)) .sendToTarget();
        }

        @Override
        public void trackChanged(MPDStatus mpdStatus, int oldTrack)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_TRACK, Tools.toObjectArray(mpdStatus, oldTrack)).sendToTarget();
        }

        @Override
        public void trackPositionChanged(MPDStatus status)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_TRACKPOSITION, Tools.toObjectArray(status)) .sendToTarget();
        }

        @Override
        public void volumeChanged(MPDStatus mpdStatus, int oldVolume)
        {
            MPDAsyncHelper.this.obtainMessage(EVENT_VOLUME, Tools.toObjectArray(mpdStatus, oldVolume)).sendToTarget();
        }

    }

    public class MPDConnectionInfo
    {
        public String sServer;
        public int iPort;
        public String sPassword;
        public String sServerStreaming;
        public int iPortStreaming;
        public String sSuffixStreaming = "";

        public String getConnectionStreamingServer()
        {
            return conInfo.sServerStreaming == null ? sServer : sServerStreaming;
        }
    }

     private static final int EVENT_CONNECT = 0;
    private static final int EVENT_DISCONNECT = 1;
    private static final int EVENT_CONNECTFAILED = 2;
    private static final int EVENT_CONNECTSUCCEEDED = 3;
    private static final int EVENT_STARTMONITOR = 4;
    private static final int EVENT_STOPMONITOR = 5;
    private static final int EVENT_EXECASYNC = 6;
    private static final int EVENT_EXECASYNCFINISHED = 7;
    private static final int EVENT_CONNECTIONSTATE = 11;
    private static final int EVENT_PLAYLIST = 12;
    private static final int EVENT_RANDOM = 13;
    private static final int EVENT_REPEAT = 14;
    private static final int EVENT_STATE = 15;
    private static final int EVENT_TRACK = 16;
    private static final int EVENT_UPDATESTATE = 17;
    private static final int EVENT_VOLUME = 18;
    private static final int EVENT_TRACKPOSITION = 19;

    private MPDAsyncWorker oMPDAsyncWorker;
    private HandlerThread oMPDAsyncWorkerThread;
    private MPDStatusMonitor oMonitor;

    public MPD oMPD;
    private static int iJobID = 0;

    private Collection<ConnectionListener> connectionListners;
    private Collection<StatusChangeListener> statusChangedListeners;
    private Collection<TrackPositionListener> trackPositionListeners;
    private Collection<AsyncExecListener> asyncExecListeners;

    private MPDConnectionInfo conInfo;

    public MPDAsyncHelper()
    {
        this(true);
    }

    public MPDAsyncHelper(boolean cached)
    {
        oMPD = new CachedMPD(cached);
        oMPDAsyncWorkerThread = new HandlerThread("MPDAsyncWorker");
        oMPDAsyncWorkerThread.start();
        oMPDAsyncWorker = new MPDAsyncWorker(oMPDAsyncWorkerThread.getLooper());

        connectionListners = new WeakLinkedList<ConnectionListener>("ConnectionListener");
        statusChangedListeners = new WeakLinkedList<StatusChangeListener>("StatusChangeListener");
        trackPositionListeners = new WeakLinkedList<TrackPositionListener>("TrackPositionListener");
        asyncExecListeners = new WeakLinkedList<AsyncExecListener>("AsyncExecListener");

        conInfo = new MPDConnectionInfo();
    }

    public void addAsyncExecListener(AsyncExecListener listener)
    {
        asyncExecListeners.add(listener);
    }

    public void addConnectionListener(ConnectionListener listener)
    {
        connectionListners.add(listener);
    }

    public void addStatusChangeListener(StatusChangeListener listener)
    {
        statusChangedListeners.add(listener);
    }

    public void addTrackPositionListener(TrackPositionListener listener)
    {
        trackPositionListeners.add(listener);
    }

    public void connect()
    {
        oMPDAsyncWorker.obtainMessage(EVENT_CONNECT, conInfo).sendToTarget();
    }

    public void disconnect()
    {
        oMPDAsyncWorker.obtainMessage(EVENT_DISCONNECT).sendToTarget();
    }

    public int execAsync(Runnable run)
    {
        int actjobid = iJobID++;
        oMPDAsyncWorker.obtainMessage(EVENT_EXECASYNC, actjobid, 0, run).sendToTarget();
        return actjobid;
    }

    public MPDConnectionInfo getConnectionSettings()
    {
        return conInfo;
    }

    public void handleMessage(Message msg)
    {
        try
        {
            Object[] args = (Object[]) msg.obj;
            switch (msg.what)
            {
                case EVENT_CONNECTIONSTATE:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.connectionStateChanged((Boolean) args[0], (Boolean) args[1]);
                    if ((Boolean) args[0])
                        for (ConnectionListener listener : connectionListners)
                            listener.connectionSucceeded("");
                    if ((Boolean) args[1])
                        for (ConnectionListener listener : connectionListners)
                            listener.connectionFailed("Connection Lost");
                    break;

                case EVENT_PLAYLIST:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.playlistChanged((MPDStatus) args[0], (Integer) args[1]);
                    break;

                case EVENT_RANDOM:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.randomChanged((Boolean) args[0]);
                    break;

                case EVENT_REPEAT:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.repeatChanged((Boolean) args[0]);
                    break;

                case EVENT_STATE:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.stateChanged((MPDStatus) args[0], (String) args[1]);
                    break;

                case EVENT_TRACK:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.trackChanged((MPDStatus) args[0], (Integer) args[1]);
                    break;

                case EVENT_UPDATESTATE:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.libraryStateChanged((Boolean) args[0]);
                    break;

                case EVENT_VOLUME:
                    for (StatusChangeListener listener : statusChangedListeners)
                        listener.volumeChanged((MPDStatus) args[0], ((Integer) args[1]));
                    break;

                case EVENT_TRACKPOSITION:
                    for (TrackPositionListener listener : trackPositionListeners)
                        listener.trackPositionChanged((MPDStatus) args[0]);
                    break;

                case EVENT_CONNECTFAILED:
                    for (ConnectionListener listener : connectionListners)
                        listener.connectionFailed((String) args[0]);
                    break;

                case EVENT_CONNECTSUCCEEDED:
                    for (ConnectionListener listener : connectionListners)
                        listener.connectionSucceeded(null);
                    break;

                case EVENT_EXECASYNCFINISHED:
                	AsyncExecListener listenerToRemove = null;

                    for (AsyncExecListener listener : asyncExecListeners)
                    {
                        if (listener != null)
                        {
                        	if (listener.asyncExecSucceeded(msg.arg1))
                        	{
                        		listenerToRemove = listener;
                        		break;
                        	}
                        }
                    }

                    if (listenerToRemove != null) removeAsyncExecListener(listenerToRemove);
                    break;
            }
        }
        catch (ClassCastException e)
        {
        }
    }

    public boolean isMonitorAlive()
    {
        if (oMonitor == null) return false;
        else return oMonitor.isAlive() & !oMonitor.isGivingUp();
    }

    public void removeAsyncExecListener(AsyncExecListener listener)
    {
        asyncExecListeners.remove(listener);
    }

    public void removeConnectionListener(ConnectionListener listener)
    {
        connectionListners.remove(listener);
    }

    public void removeStatusChangeListener(StatusChangeListener listener)
    {
        statusChangedListeners.remove(listener);
    }

    public void removeTrackPositionListener(TrackPositionListener listener)
    {
        trackPositionListeners.remove(listener);
    }

    public void setUseCache(boolean useCache)
    {
        ((CachedMPD) oMPD).setUseCache(useCache);
    }

    public void startMonitor()
    {
        oMPDAsyncWorker.obtainMessage(EVENT_STARTMONITOR).sendToTarget();
    }

    public void stopMonitor()
    {
        oMPDAsyncWorker.obtainMessage(EVENT_STOPMONITOR).sendToTarget();
    }

}


text:
<?php

namespace Marquine\Etl\Extractors;

use Marquine\Etl\Step;

abstract class Extractor extends Step
{
    /**
     * The extractor input.
     *
     * @var mixed
     */
    protected $input;

    /**
     * Set the extractor input.
     *
     * @param  mixed  $input
     * @return $this
     */
    public function input($input)
    {
        $this->input = $input;

        return $this;
    }

    /**
     * Extract data from the input.
     *
     * @return \Generator
     */
    abstract public function extract();
};


text:
<?php

namespace Google\Service\Forms;

class Response extends \Google\Model
{
  protected $createItemType = CreateItemResponse::class;
  protected $createItemDataType = '';

  /**
   * @param CreateItemResponse
   */
  public function setCreateItem(CreateItemResponse $createItem)
  {
    $this->createItem = $createItem;
  }
  /**
   * @return CreateItemResponse
   */
  public function getCreateItem()
  {
    return $this->createItem;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Response::class, 'Google_Service_Forms_Response');


text:
package org.hbird.business.navigation.processors;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

import java.util.List;

import org.hbird.business.navigation.request.OrbitalStatePredictionRequest;
import org.hbird.exchange.navigation.OrbitalState;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class OrbitalStateExtractorTest {

    @Mock
    private OrbitalStatePredictionRequest request;

    @Mock
    private List<OrbitalState> list;

    private OrbitalStateExtractor extractor;

    private InOrder inOrder;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        extractor = new OrbitalStateExtractor();
        inOrder = inOrder(request, list);
        when(request.getResult()).thenReturn(list);
    }

    @Test
    public void testExtract() throws Exception {
        assertEquals(list, extractor.extract(request));
        inOrder.verify(request, times(1)).getResult();
        inOrder.verifyNoMoreInteractions();
    }
}


text:
namespace HotelCommerce.Core.Infrastructure.DependecyResolution.Data
{
	using Hotel720.Platform.Infrastructure.Data;
	using SimpleInjector;

    public sealed class UnitOfWorkFactory : IUnitOfWorkFactory
    {
		private readonly Container container;
		public UnitOfWorkFactory(Container container)
        {
			this.container = container;
        }

        public IUnitOfWork Get()
        {
			return container.GetInstance<IUnitOfWork>();
        }
    }
}


text:
;(function() {
  'use strict';

  var pi = Math.PI, sin = Math.sin, cos = Math.cos;
  var PIXELS_PER_AU = 50;

  var Orbit3D = function(eph, opts) {
    opts = opts || {};
    opts.width = opts.width || 1;
    opts.object_size = opts.object_size || 1;
    opts.jed =  opts.jed || 2451545.0;

    this.opts = opts;
    this.eph = eph;

    // Dummies for CAMS data.
    this.eph.ma = this.eph.ma || Math.random() * 360;
    this.eph.w_bar = this.eph.w_bar || 0;
    this.eph.epoch = this.eph.epoch || 0;
  };

  Orbit3D.prototype.createOrbit = function() {
    var pts;
    var points;
    var time = this.opts.jed;
    var pts = [];
    var period = this.getPeriodInDays();
    var limit = period + 1;
    var parts = this.eph.e > .20 ? 1200 : 300;   // Extra precision for high eccentricity.
    parts = this.eph.a > 10 ? 10000 : parts;
    var delta = Math.ceil(limit / parts);
    var prevPos;

    points = new THREE.Geometry();
    for (var i=0; i <= parts; i++, time += delta) {
      var pos = this.getPosAtTime(time);
      if (isNaN(pos[0]) || isNaN(pos[1]) || isNaN(pos[2])) {
        console.error('NaN position value - you may have bad data in the following ephemeris:');
        console.log(this.eph);
      }
      var vector = new THREE.Vector3(pos[0], pos[1], pos[2]);
      if (prevPos && Math.abs(prevPos[0] - pos[0]) +
                     Math.abs(prevPos[1] - pos[1]) +
                     Math.abs(prevPos[2] - pos[2]) > 120) {
        // Don't render bogus or very large ellipses.
        points.vertices = [];
        return points;
      }
      prevPos = pos;
      pts.push(vector);
    }

    points = new THREE.Geometry();
    points.vertices = pts;
    //points.computeLineDistances(); // Required for dotted lines.

    return points;
  };

  Orbit3D.prototype.getPosAtTime = function(jed) {
    // Note: logic below must match the vertex shader.
    // This position calculation is used to create orbital ellipses.
    var e = this.eph.e;
    var a = this.eph.a;
    var i = (this.eph.i) * pi/180;
    var o = (this.eph.om) * pi/180; // longitude of ascending node
    // LONGITUDE of perihelion
    var p = (this.eph.w_bar || this.eph.w + this.eph.om) * pi/180;
    var period = this.getPeriodInDays();
    var ma = this.eph.ma;
    var M;
    // Calculate mean anomaly at jed
    ma = ma * pi/180;
    var n = 2*pi / period;
    var epoch = this.eph.epoch;
    var d = jed - epoch;
    M = ma + n * d;

    // Estimate eccentric and true anom using iterative approx
    var E0 = M;
    var lastdiff;
    do {
      var E1 = M + e * sin(E0);
      lastdiff = Math.abs(E1-E0);
      E0 = E1;
    } while(lastdiff > 0.0000001);
    var E = E0;
    var v = 2 * Math.atan(Math.sqrt((1+e)/(1-e)) * Math.tan(E/2));

    // Radius vector, in AU
    var r = a * (1 - e*e) / (1 + e * cos(v)) * PIXELS_PER_AU;

    // Hekliocentric coords
    var X = r * (cos(o) * cos(v + p - o) - sin(o) * sin(v + p - o) * cos(i))
    var Y = r * (sin(o) * cos(v + p - o) + cos(o) * sin(v + p - o) * cos(i))
    var Z = r * (sin(v + p - o) * sin(i))
    var ret = [X, Y, Z];
    return ret;
  };

  Orbit3D.prototype.getPeriodInDays = function() {
    return Math.sqrt(Math.pow(this.eph.a, 3)) * 365.25;
  }

  Orbit3D.prototype.getSkinnyEllipse = function() {
    if (!this.ellipse) {
      var pointGeometry = this.createOrbit(this.opts.jed);
      this.ellipse = new THREE.Line(pointGeometry,
        new THREE.LineDashedMaterial({
          color: new THREE.Color(0xffffff),
          // Anything below lineWidth 1 will be blinky.
          linewidth: 1,
          dashSize: 0.5,
          gapSize: 2,
        }), THREE.LineStrip);
    }
    return this.ellipse;
  };

  Orbit3D.prototype.getSolidEllipse = function() {
    if (!this.ellipse) {
      var pointGeometry = this.createOrbit(this.opts.jed);
      this.ellipse = new THREE.Line(pointGeometry,
        new THREE.LineBasicMaterial({
          color: this.opts.color,
          linewidth: 1.5,
        }), THREE.LineStrip);
    }
    return this.ellipse;
  };

  Orbit3D.prototype.getEllipse = function() {
    if (!this.ellipse) {
      var pointGeometry = this.createOrbit(this.opts.jed);
      this.ellipse = new THREE.Line(pointGeometry,
        new THREE.LineDashedMaterial({
          color: this.opts.color,
          linewidth: 1,
          dashSize: 2,
          gapSize: 0.5,
        }), THREE.LineStrip);
    }
    return this.ellipse;
  };

  // Returns a generously proportioned ellipse. Used for intersection.
  Orbit3D.prototype.getFatEllipse = function() {
    if (!this.fatEllipse) {
      var pointGeometry = this.createOrbit(this.opts.jed);
      this.fatEllipse = new THREE.Line(pointGeometry,
        new THREE.LineBasicMaterial({
          transparent: true,
          linewidth: 10,
        }), THREE.LineStrip);
    }
    return this.fatEllipse;
  };

  window.Orbit3D = Orbit3D;
})();


text:
package net.sourceforge.squirrel_sql.client.gui;

import java.util.EventObject;
/**
 * Event associated with the <TT>OkClosePanelListener</TT>.
 *
 * @author Colin Bell
 */
public class OkClosePanelEvent extends EventObject
{
	OkClosePanelEvent(OkClosePanel source)
	{
		super(source);
	}
}


text:
{namespace be = TYPO3\CMS\Backend\ViewHelpers}
{namespace bu = TYPO3\CMS\Beuser\ViewHelpers}
{namespace core = TYPO3\CMS\Core\ViewHelpers}

<f:layout name="Default" />

<f:section name="headline">

<f:translate key="backendUserListing" />

</f:section>

<f:section name="content">

	<f:comment>
		Listing of users on compare list
	</f:comment>
	<f:if condition="{compareUserList}">

{f:translate(key: 'section.compare', default: 'Compare')}

					<f:for each="{compareUserList}" as="compareUser">

									<be:avatar backendUser="{compareUser.uid}" showIcon="TRUE" />

								{compareUser.userName}

								<f:link.action action="removeFromCompareList" arguments="{uid: compareUser.uid}" class="pull-right btn btn-default">
									<core:icon identifier="actions-selection-delete" />
								</f:link.action>

					</f:for>

		<f:form action="compare">
			<f:form.submit value="{f:translate(key: 'compareUserList', default: 'Compare user list')}" class="btn btn-default" />
		</f:form>

	</f:if>

	<f:comment>
		Filter section
	</f:comment>
	<f:render partial="Filters/BackendUser/Index" arguments="{demand: demand, backendUserGroups: backendUserGroups}" />

	<f:comment>
		Listing of all users
	</f:comment>
	<f:be.widget.paginate objects="{backendUsers}" as="paginatedBackendUsers" configuration="{itemsPerPage: 50, insertBelow: 1}">

						<f:translate key="userName" /> / <f:translate key="realName" />
						<f:translate key="lastLogin" />

					<f:for each="{paginatedBackendUsers}" as="backendUser">
						<f:render partial="BackendUser/IndexListRow" arguments="{demand: demand, backendUser: backendUser, onlineBackendUsers: onlineBackendUsers, dateFormat: dateFormat, timeFormat: timeFormat, returnUrl: returnUrl}" />
					</f:for>
					<f:comment>
						Footer row: no officially defined style yet
					</f:comment>

							<f:count subject="{backendUsers}" /> <f:translate key="users" />

	</f:be.widget.paginate>

</f:section>


text:
<!DOCTYPE html>

  <title>Huge DOM Performance Test</title>


text:
defaults write -g ApplePressAndHoldEnabled -bool false

# Use AirDrop over every interface. srsly this should be a default.
defaults write com.apple.NetworkBrowser BrowseAllInterfaces 1

# Always open everything in Finder's list view. This is important.
defaults write com.apple.Finder FXPreferredViewStyle Nlsv

# Show the ~/Library folder.
chflags nohidden ~/Library

# Set a really fast key repeat.
defaults write NSGlobalDomain KeyRepeat -int 0

# Set the Finder prefs for showing a few different volumes on the Desktop.
defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

# Hide Safari's bookmark bar.
defaults write com.apple.Safari ShowFavoritesBar -bool false

# Set up Safari for development.
defaults write com.apple.Safari IncludeInternalDebugMenu -bool true
defaults write com.apple.Safari IncludeDevelopMenu -bool true
defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true
defaults write com.apple.Safari "com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled" -bool true
defaults write NSGlobalDomain WebKitDeveloperExtras -bool true


text:
namespace shell {

Identity::Identity(const GURL& url, const std::string& qualifier)
    : url(GetBaseURLAndQuery(url, nullptr)), qualifier(qualifier) {
}

Identity::Identity(const GURL& base_url)
    : url(GetBaseURLAndQuery(base_url, nullptr)), qualifier(url.spec()) {
}

bool Identity::operator<(const Identity& other) const {
  if (url != other.url)
    return url < other.url;
  return qualifier < other.qualifier;
}

}  // namespace shell


text:
FROM romeoz/docker-phpfpm:5.4
MAINTAINER romeOz <serggalka@gmail.com>

ENV PHP_CONF_DIR=/etc/php5/

RUN \
    BUILD_DEPS='php5-dev wget make libtool locate pkg-config' \
    && apt-get update \
    && apt-get install -y ${BUILD_DEPS} \
    && echo "deb http://packages.couchbase.com/ubuntu precise precise/main" | tee -a /etc/apt/sources.list.d/couchbase.list \
    && wget -O- http://packages.couchbase.com/ubuntu/couchbase.key | apt-key add - \
    && apt-get update \
    && apt-get install -y libcouchbase2-libevent libcouchbase-dev libsasl2-dev libmemcached-dev php5-memcache \
    && pecl channel-update pecl.php.net \
    # Install xdebug
    && echo -e "\nInstall xdebug extension\n" \
    && pecl install -f xdebug-2.4.0 \
    && PATH_XDEBUG=$(updatedb && locate xdebug.so) \
    && echo "zend_extension = ${PATH_XDEBUG}" >> ${PHP_CONF_DIR}/fpm/conf.d/xdebug.ini \
    # Install memcached
    && echo -e "\nInstall memcached extension\n" \
    && printf "no --disable-memcached-sasl" | pecl install memcached \
    && echo "extension = memcached.so" > ${PHP_CONF_DIR}/fpm/conf.d/memcached.ini \
    # Install mongo
    && echo "\nInstall mongo extension\n" \
    && printf "\n" | pecl install -f mongo \
    && echo "extension = mongo.so" > ${PHP_CONF_DIR}/fpm/conf.d/mongo.ini \
    && echo "extension = mongo.so" > ${PHP_CONF_DIR}/cli/conf.d/mongo.ini \
    # Install redis
    && echo "\nInstall redis extension\n" \
    && printf "\n" | pecl install -f redis-2.2.8 \
    && echo "extension = redis.so" > ${PHP_CONF_DIR}/fpm/conf.d/redis.ini \
    && echo "extension = redis.so" > ${PHP_CONF_DIR}/cli/conf.d/redis.ini \
    # Install couchbase
    && echo "\nInstall couchbase extension\n" \
    && apt-get install -y re2c \
    && pecl install -f pcs \
    && echo "extension = pcs.so" >> ${PHP_CONF_DIR}/fpm/conf.d/pcs.ini \
    && echo "extension = pcs.so" >> ${PHP_CONF_DIR}/cli/conf.d/pcs.ini \
    && pecl install -f couchbase-2.2.3 \
    && echo "extension = couchbase.so" > ${PHP_CONF_DIR}/fpm/conf.d/couchbase.ini \
    && echo "extension = couchbase.so" > ${PHP_CONF_DIR}/cli/conf.d/couchbase.ini \
    && composer global require "phpunit/phpunit:^4.7.0" \
    && echo -e '\ninclude_path = ".:/usr/share/php:/root/.composer/vendor/phpunit"' >> ${PHP_CONF_DIR}/cli/conf.d/custom.ini \
    && ln -s /root/.composer/vendor/bin/phpunit /usr/bin/phpunit \
    # Cleaning
    && apt-get purge -y --auto-remove ${BUILD_DEPS} \
    && apt-get autoremove -y && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

ENV PATH /root/.composer/vendor/bin:$PATH

COPY xdebug.ini ${PHP_CONF_DIR}/mods-available/xdebug.ini


text:
var path = require('path');
var fs = require('fs');

var exports = module.exports = function mkdirP (p, mode, f) {
    var cb = f || function () {};
    p = path.resolve(p);

    var ps = path.normalize(p).split('/');
    path.exists(p, function (exists) {
        if (exists) cb(null);
        else mkdirP(ps.slice(0,-1).join('/'), mode, function (err) {
            if (err && err.code !== 'EEXIST') cb(err)
            else fs.mkdir(p, mode, function (err) {
                if (err && err.code !== 'EEXIST') cb(err)
                else cb()
            });
        });
    });
};
exports.mkdirp = exports.mkdirP = module.exports;


text:
import qctests.EN_increasing_depth_check

import util.testingProfile
import numpy as np
import util.main as main

#### EN_increasing_depth_check -------------------------------------------
class TestClass():

    parameters = {
        "table": 'unit'
    }

    def setUp(self):
        # this qc test will go looking for the profile in question in the db, needs to find something sensible
        main.faketable('unit')
        main.fakerow('unit')

    def tearDown(self):
        main.dbinteract('DROP TABLE unit;')

    def test_EN_increasing_depth_outside_valid_range(self):
        '''
        Check EN_increasing_depth_check flags values < 0 and > 11000m.
        '''

        p = util.testingProfile.fakeProfile([0,0,0,0,0,0,0,0,0,0], [-1,200,300,400,500,600,700,800,900,1000], uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.zeros(10, dtype=bool)
        truth[0] = True
        assert np.array_equal(qc, truth), 'Failed to flag depth < 0'

        p = util.testingProfile.fakeProfile([0,0,0,0,0,0,0,0,0,0], [100,200,300,400,500,600,700,800,900,11001], uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.zeros(10, dtype=bool)
        truth[-1] = True
        assert np.array_equal(qc, truth), 'Failed to flag depth > 11000'

    def test_EN_increasing_depth_flagging(self):
        '''
        Check EN_increasing_depth_check flags incorrect depths.
        '''

        p = util.testingProfile.fakeProfile([0,0,0,0,0,0,0,0,0,0], [100,200,300,500,500,600,700,800,900,1000], latitude=0.0, uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.zeros(10, dtype=bool)
        truth[3:5] = True
        assert np.array_equal(qc, truth), 'Failed to constant depth'

        p = util.testingProfile.fakeProfile([0,0,0,0,0,0,0,0,0,0], [100,200,300,510,500,600,700,800,900,1000], latitude=0.0, uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.zeros(10, dtype=bool)
        truth[3:5] = True
        assert np.array_equal(qc, truth), 'Failed to incorrect depths when cannot determine which is wrong'

        p = util.testingProfile.fakeProfile([0,0,0,0,0,0,0,0,0,0], [100,200,300,610,500,600,700,800,900,1000], latitude=0.0, uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.zeros(10, dtype=bool)
        truth[3] = True
        print qc
        assert np.array_equal(qc, truth), 'Failed to incorrect depth'

    def test_EN_increasing_depth_all_zero(self):
        '''
        Check EN_increasing_depth_check flags all levels in a profile with all depths = 0
        '''

        p = util.testingProfile.fakeProfile([0]*1000, [0]*1000, uid=8888)
        qc = qctests.EN_increasing_depth_check.test(p, self.parameters)
        truth = np.ones(1000, dtype=bool)

        print qc, truth

        assert np.array_equal(qc, truth), 'Failed to flag all levels in profile with all 0 depths'


text: package osexec


text:
<?php

declare(strict_types=1);

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\Tests\Models\CMS\CmsGroup;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\OrmFunctionalTestCase;

use function count;
use function get_class;

/**
 * @group DDC-1643
 */
class DDC1643Test extends OrmFunctionalTestCase
{
    /** @var CmsUser */
    private $user1;

    /** @var CmsUser */
    private $user2;

    protected function setUp(): void
    {
        $this->useModelSet('cms');
        parent::setUp();

        $user1           = new CmsUser();
        $user1->username = 'beberlei';
        $user1->name     = 'Benjamin';
        $user1->status   = 'active';
        $group1          = new CmsGroup();
        $group1->name    = 'test';
        $group2          = new CmsGroup();
        $group2->name    = 'test';
        $user1->addGroup($group1);
        $user1->addGroup($group2);
        $user2           = new CmsUser();
        $user2->username = 'romanb';
        $user2->name     = 'Roman';
        $user2->status   = 'active';

        $this->_em->persist($user1);
        $this->_em->persist($user2);
        $this->_em->persist($group1);
        $this->_em->persist($group2);
        $this->_em->flush();
        $this->_em->clear();

        $this->user1 = $this->_em->find(get_class($user1), $user1->id);
        $this->user2 = $this->_em->find(get_class($user1), $user2->id);
    }

    public function testClonePersistentCollectionAndReuse(): void
    {
        $user1 = $this->user1;

        $user1->groups = clone $user1->groups;

        $this->_em->flush();
        $this->_em->clear();

        $user1 = $this->_em->find(get_class($user1), $user1->id);

        self::assertCount(2, $user1->groups);
    }

    public function testClonePersistentCollectionAndShare(): void
    {
        $user1 = $this->user1;
        $user2 = $this->user2;

        $user2->groups = clone $user1->groups;

        $this->_em->flush();
        $this->_em->clear();

        $user1 = $this->_em->find(get_class($user1), $user1->id);
        $user2 = $this->_em->find(get_class($user1), $user2->id);

        self::assertCount(2, $user1->groups);
        self::assertCount(2, $user2->groups);
    }

    public function testCloneThenDirtyPersistentCollection(): void
    {
        $user1 = $this->user1;
        $user2 = $this->user2;

        $group3        = new CmsGroup();
        $group3->name  = 'test';
        $user2->groups = clone $user1->groups;
        $user2->groups->add($group3);

        $this->_em->persist($group3);
        $this->_em->flush();
        $this->_em->clear();

        $user1 = $this->_em->find(get_class($user1), $user1->id);
        $user2 = $this->_em->find(get_class($user1), $user2->id);

        self::assertCount(3, $user2->groups);
        self::assertCount(2, $user1->groups);
    }

    public function testNotCloneAndPassAroundFlush(): void
    {
        $user1 = $this->user1;
        $user2 = $this->user2;

        $group3        = new CmsGroup();
        $group3->name  = 'test';
        $user2->groups = $user1->groups;
        $user2->groups->add($group3);

        self::assertCount(1, $user1->groups->getInsertDiff());

        $this->_em->persist($group3);
        $this->_em->flush();
        $this->_em->clear();

        $user1 = $this->_em->find(get_class($user1), $user1->id);
        $user2 = $this->_em->find(get_class($user1), $user2->id);

        self::assertCount(3, $user2->groups);
        self::assertCount(3, $user1->groups);
    }
}


text:
"use strict";

var fs = require('fs');
var path = require('path');

var spawn = require('child_process').spawn;
var execFile = require('child_process').execFile;
var async = require('async');
var grunt = require('grunt');

function Optimizer(options) {
  this.options = options || {};
  this.src = options.src;
  this.dest = options.dest || this.src;
  this.extension = path.extname(this.src);
  this.optimizers = this.getOptimizers(this.extension);
}

Optimizer.prototype.optipng = function () {
  var args = [];
  args.push('-i 1');
  args.push('-strip all');
  args.push('-fix');
  args.push('-o7');
  args.push('-force');
  args.push('-out');
  args.push(this.dest);
  args.push(this.src);

  return {
    name: 'optipng',
    path: require('optipng-bin').path,
    args: args
  };
};

Optimizer.prototype.pngquant = function () {
  var args = [];
  args.push('--ext=.png');
  args.push('--speed=1');
  args.push('--force');
  args.push('256');
  args.push(this.dest);

  return {
    name: 'pngquant',
    path: require('pngquant-bin').path,
    args: args
  };
};

Optimizer.prototype.advpng = function () {
  var args = [];
  args.push('--recompress');
  args.push('--shrink-extra');
  args.push(this.dest);

  return {
    name: 'advpng',
    path: require('advpng-bin').path,
    args: args
  };
};

Optimizer.prototype.pngcrush = function () {
  var args = [];
  args.push('-rem alla');
  args.push('-rem text');
  args.push('-brute');
  args.push('-reduce');
  args.push(this.dest);

  return {
    name: 'pngcrush',
    path: require('pngcrush-bin').path,
    args: args
  };
};

Optimizer.prototype.zopflipng = function () {
  var args = [];
  args.push('-m');
  args.push('--iterations=500');
  args.push('--splitting=3');
  args.push('--filters=01234mepb');
  args.push('--lossy_8bit');
  args.push('--lossy_transparent');
  //args.push(this.src);
  args.push(this.dest);

  return {
    name: 'zopflipng',
    path: require('zopflipng-bin').path,
    args: args
  };
};

Optimizer.prototype.gifsicle = function () {
  var args = [];
  //args.push('--careful');
  //args.push('--interlace');
  args.push('--optimize');
  args.push('--output');
  args.push(this.dest);
  args.push(this.src);

  return {
    name: 'gifsicle',
    path: require('gifsicle').path,
    args: args
  };
};

Optimizer.prototype.jpegtran = function () {
  var args = [];
  args.push('-optimize');
  args.push('-progressive');
  args.push('-outfile');
  args.push(this.dest);
  args.push(this.src);

  return {
    name: 'jpegtran',
    path: require('jpegtran-bin').path,
    args: args
  };
};

Optimizer.prototype.jpegRecompress = function () {
  var args = [];
  args.push('--progressive');
  args.push('--strip');
  args.push(this.dest);
  args.push(this.dest);

  return {
    name: 'jpeg-recompress',
    path: require('jpeg-recompress-bin').path,
    args: args
  };
};

Optimizer.prototype.getOptimizers = function (extension) {
  var optimizers = [];
  extension = extension.toLowerCase();
  switch (extension) {
    case '.png':
      optimizers.push(this.optipng());
      optimizers.push(this.pngquant());
      optimizers.push(this.zopflipng());
      optimizers.push(this.pngcrush());
      optimizers.push(this.advpng());
      break;
    case '.jpg':
      optimizers.push(this.jpegtran());
      optimizers.push(this.jpegRecompress());
      break;
    case '.gif':
      optimizers.push(this.gifsicle());
      break;
  }
  return optimizers;
};

// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
function _round10 (value, exp) {
  // If the exp is undefined or zero...
  if (typeof exp === 'undefined' || +exp === 0) {
    return Math.round(value);
  }
  value = +value;
  exp = +exp;
  // If the value is not a number or the exp is not an integer...
  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
    return NaN;
  }
  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}

Optimizer.prototype.optimize = function (callback) {

  var src = this.src;
  var dest = this.dest;

  var fns = this.optimizers.map(function (optimizer) {
    return function (callback) {
      execFile(optimizer.path, optimizer.args, function () {
        callback(null, optimizer.name);
      });
    };
  });

  async.series(fns, function (error, result) {
    var originalSize = fs.statSync(src).size;
    var optimizedSize = fs.statSync(dest).size;
    var diffSize = originalSize - optimizedSize;
    callback(error, {
      original: originalSize,
      optimized: optimizedSize,
      diff: diffSize,
      diffPercent: _round10(100 * (diffSize / originalSize), -1)
    });
  });
};

module.exports = Optimizer;


text:
package cn.android_mobile.core.net;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

import cn.android_mobile.core.enums.CacheType;
import cn.android_mobile.core.enums.RequestType;
import cn.android_mobile.core.enums.ResponseChartset;
import cn.android_mobile.core.net.http.Service;
import cn.android_mobile.core.net.http.ServiceManager;
import cn.android_mobile.core.net.http.ServiceRequest;
import cn.android_mobile.core.net.http.ServiceResponse;
import cn.android_mobile.toolkit.CacheUtil;
import cn.android_mobile.toolkit.Lg;

/**
 * http 请求封装 支持 直接 传递 URL 加参数 支持 Request Response 封装两种格式
 *
 * @author fyygw
 */
@SuppressLint("HandlerLeak")
public class BasicAsyncTask extends AsyncTask<Object, Integer, Object> {
    public static boolean asyncWithProgress = false;
    private String url;
    protected IBasicAsyncTask callback;
    private Gson g = new Gson();

    public RequestType REQUEST_TYPE = RequestType.GET;
    public ResponseChartset CHARSET = ResponseChartset.UTF_8;
    private CacheType cacheType = CacheType.DEFAULT_NET;
    private IBasicAsyncTaskFinish listener = null;

    private ServiceRequest sRequest;
    private Service sService;
    private ServiceResponse sResponse;

    protected Handler h = null;
    protected Object result = null;

    public BasicAsyncTask(ServiceRequest request, Service service,
                          CacheType cache, IBasicAsyncTask callback) {
        this.sRequest = request;
        this.sService = service;
        this.callback = callback;
        this.cacheType = cache;
    }

    public BasicAsyncTask(ServiceResponse response, Service service,
                          CacheType cache) {
        this.sService = service;
        this.cacheType = cache;
        this.sResponse = response;
    }

    public BasicAsyncTask(IBasicAsyncTask callback, String url,
                          CacheType cacheType) {
        this.url = url;
        this.callback = callback;
        this.cacheType = cacheType;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        h = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 100:
                        callback.callback(result);
                        break;

                    default:
                        break;
                }
            }

        };
    }

    @Override
    protected Object doInBackground(Object... params) {
        Object obj = null;
        Lg.print(cacheType);
        if (cacheType == CacheType.DEFAULT_NET) {
            obj = _doInBackGround_net(params);
        } else if (cacheType == CacheType.DEFAULT_CACHE_NET) {
            obj = _doInBackGround_cache_net(params);
        } else if (cacheType == CacheType.DEFAULT_CACHE) {
            obj = _doInBackGround_cache(params);
        } else if (cacheType == CacheType.BASIC_NET) {
            obj = _doInBackGround_basic_net(params);
        } else if (cacheType == CacheType.BASIC_CACHE_NET) {
            obj = _doInBackGround_basic_cache_net(params);
        } else if (cacheType == CacheType.BASIC_CACHE) {
            obj = _doInBackGround_basic_cache(params);
        }
        return obj;
    }

    // 从缓存返回
    private Object _doInBackGround_basic_cache(Object[] params) {
        if (params != null && params.length % 2 != 0) {
            Lg.print("params error ...");
            return null;
        }
        String key = url + g.toJson(params);
        result = CacheUtil.getInterfaceObject(key);
        // Lg.print("从缓存获取");
        h.sendEmptyMessage(100);
        return result;
    }

    // 先从缓存 获取, 然后返回网络数据 ,返回两次
    private Object _doInBackGround_basic_cache_net(Object[] params) {
        if (params != null && params.length % 2 != 0) {
            Lg.print("params error ...");
            return null;
        }
        String key = url + g.toJson(params);
        result = CacheUtil.getInterfaceObject(key);
        // Lg.print("从缓存获取");
        BasicParams p = new BasicParams();
        if (params != null) {
            for (int i = 0; i < params.length; i += 2) {
                p.addParam(params[i].toString(), params[i + 1].toString());
            }
        }
        Lg.print("网络获取URL:" + url);
        result = request(REQUEST_TYPE.getContext(), url, p);
        CacheUtil.saveInterfaceObject(key, result);
        if (listener != null) {
            listener.asyncTaskFinish(this);
        }
        h.sendEmptyMessage(100);
        return result;
    }

    // 只从网络返回
    protected Object _doInBackGround_basic_net(Object[] params) {
        if (params != null && params.length % 2 != 0) {
            Lg.print("params error ...");
            return null;
        }
        String key = url + g.toJson(params);
        BasicParams p = new BasicParams();
        if (params != null) {
            for (int i = 0; i < params.length; i += 2) {
                p.addParam(params[i].toString(), params[i + 1].toString());
            }
        }
        Lg.print("网络获取URL:" + url);
        result = request(REQUEST_TYPE.getContext(), url, p);
        CacheUtil.saveObject(key, result);
        if (listener != null) {
            listener.asyncTaskFinish(this);
        }
        return result;
    }

    private Object _doInBackGround_cache(Object[] params) {
        String key = sService.getClass().getName() + g.toJson(sRequest)
                + CacheUtil.cacheKey;
        result = CacheUtil.getInterfaceObject(key);
        if (result != null) {
            Lg.print("从缓存获取");
            h.sendEmptyMessage(100);
        } else {
            sResponse = ServiceManager.getServiceResponse(sRequest, sService);
            result = sResponse;
            CacheUtil.saveInterfaceObject(key, result);
            Lg.print("从网络获取");
            h.sendEmptyMessage(100);
        }
        if (listener != null) {
            listener.asyncTaskFinish(this);
        }
        return result;
    }

    private Object _doInBackGround_cache_net(Object[] params) {
        String key = sService.getClass().getName() + g.toJson(sRequest)
                + CacheUtil.cacheKey;
        Lg.print("_doInBackGround_cache_net    " + key);
        result = CacheUtil.getInterfaceObject(key);
        if (result != null) {
            Lg.print("从缓存获取");
            h.sendEmptyMessage(100);
        } else {
            sResponse = ServiceManager.getServiceResponse(sRequest, sService);
            result = sResponse;
            CacheUtil.saveInterfaceObject(key, result);
            Lg.print("从网络获取");
            h.sendEmptyMessage(100);
        }
        if (listener != null) {
            listener.asyncTaskFinish(this);
        }
        return result;
    }

    private Object _doInBackGround_net(Object[] params) {
        String key = sService.getClass().getName() + g.toJson(sRequest)
                + CacheUtil.cacheKey;
        // Lg.print("_doInBackGround_net    "+key);
        sResponse = ServiceManager.getServiceResponse(sRequest, sService);
        result = sResponse;
        CacheUtil.saveInterfaceObject(key, result);
        if (listener != null) {
            listener.asyncTaskFinish(this);
        }
        h.sendEmptyMessage(100);
        return result;
    }

    @Override
    protected void onPostExecute(Object result) {
        // callback.callback(result);
    }

    @Override
    protected void onCancelled() {
        abort();
        if (sService != null) {
            sService.cancel();
        }
        super.onCancelled();
    }

    public void addFinishListener(IBasicAsyncTaskFinish fl) {
        this.listener = fl;
    }

    /**
     *
     */
    private static final int SET_CONNECTION_TIMEOUT = 60 * 1000;
    private static final int SET_SOCKET_TIMEOUT = 60 * 1000;
    private DefaultHttpClient client = null;
    private HttpGet requestGet = null;
    private HttpPost requestPost = null;

    protected String request(String method, String actionUrl, BasicParams params) {
        client = createHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(),
                SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(client.getParams(),
                SET_SOCKET_TIMEOUT);
        // HttpProtocolParams.setContentCharset(client.getParams(), HTTP.UTF_8);
        // HttpHost proxy = new HttpHost("10.5.38.14", 8087);
        // client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
        // proxy);

        /**
         * File file = new File(pathToOurFile); MultipartEntity mpEntity = new
         * MultipartEntity(); //文件传输 mpEntity.addPart("userfile", new
         * FileBody(file)); // <input type="file" name="userfile" /> 对应的
         * mpEntity.addPart("username",new StringBody("fangzhen",
         * Charset.forName(org.apache.http.protocol.HTTP.UTF_8)));
         * mpEntity.addPart("password",new StringBody("123456",
         * Charset.forName(org.apache.http.protocol.HTTP.UTF_8)));
         */
        HttpResponse response = null;
        String s_result = null;
        try {
            if (method.toLowerCase().equals("post")) {
                Lg.print("Type:POST");
                requestPost = new HttpPost(actionUrl);
                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE, null,
                        Charset.forName(org.apache.http.protocol.HTTP.UTF_8));
                List<BasicNameValuePair> valueList = params.getParams();
                for (BasicNameValuePair value : valueList) {
                    if (value.getValue().indexOf("file://") != -1) {
                        String[] paths = value.getValue().split(";");
                        for (String path : paths) {
                            entity.addPart(value.getName(), new FileBody(
                                    new File(path.replaceAll("file://", ""))));
                        }
                    } else {
                        entity.addPart(
                                value.getName(),
                                new StringBody(
                                        value.getValue(),
                                        Charset.forName(org.apache.http.protocol.HTTP.UTF_8)));
                    }
                }
                Lg.printJson(entity);
                requestPost.setEntity(entity);
                response = client.execute(requestPost);
            } else if (method.toLowerCase().equals("get")) {
                Lg.print("Type:GET");
                List<BasicNameValuePair> valueList = params.getParams();
                String s_params = "?";
                for (BasicNameValuePair value : valueList) {
                    if (s_params.length() > 1)
                        s_params += "&";
                    s_params += value.getName() + "=" + value.getValue();
                }
                requestGet = new HttpGet(actionUrl + s_params);
                response = client.execute(requestGet);
            }
            if (response != null
                    && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                s_result = EntityUtils.toString(response.getEntity(),
                        CHARSET.context);
                Lg.print("charset:" + CHARSET.context);
                Lg.print(s_result);

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            abort();
        }
        return s_result;
    }

    @Override
    protected void onCancelled(Object result) {
        abort();
    }

    public void abort() {
        if (requestGet != null && requestGet.isAborted() == false) {
            requestGet.abort();
        }
        if (requestPost != null && requestPost.isAborted() == false) {
            requestPost.abort();
        }
        // if (client != null) {
        // client.getConnectionManager().shutdown();
        // }
    }

    public DefaultHttpClient createHttpClient() {
        if (client == null) {
            client = HttpClientFactory.getHttpClient();
        }
        return client;
    }
}


text:
package com.repofetcher;

public interface ErrorsContract {
    interface View{
        void showNetworkErrorView();
        void showUnexpectedErrorView();
        void retry();
    }

    interface Handler{
        void createUnexpectedError();
        void createNetworkError();
    }

    interface Controller {
        void handleError(Throwable t);
        void onRetryButtonClick();
    }
}


text:
package de.intarsys.security.smartcard.card;

/**
 * An exception in the card abstraction layer.
 */
public class CardException extends Exception {

	private static final long serialVersionUID = 1L;

	public CardException() {
		super();
	}

	public CardException(String message) {
		super(message);
	}

	public CardException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Namespace TinCan.Standard.LRSResponses
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Namespace TinCan.Standard.LRSResponses
   ">
    <meta name="generator" content="docfx 2.10.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Namespace TinCan.Standard.LRSResponses

Classes

AboutLRSResponse

Class AboutLRSResponse.

ActivityProfileLRSResponse

Class ActivityProfileLRSResponse.

AgentProfileLRSResponse

Class AgentProfileLRSResponse.

LRSResponse

Class LRSResponse.

ProfileKeysLRSResponse

Class ProfileKeysLRSResponse.

StateLRSResponse

Class StateLRSResponse.

StatementLRSResponse

Class StatementLRSResponse.

StatementsResultLRSResponse

Class StatementsResultLRSResponse.

                    Improve this Doc

              Back to top

            Copyright © 2015-2016 Microsoft
Generated by DocFX


text:
/**
 *
 */
package org.nww.modules.users.orm;

import org.nww.core.data.mongo.AbstractMongoPersistentObjectRepository;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @author mga
 *
 */
public class MongoUserRepository extends AbstractMongoPersistentObjectRepository<UserImpl> implements UserRepository<UserImpl> {

	@Override
	public UserImpl createNew() {
		return new UserImpl();
	}

	@Override
	public UserImpl findByUsername(String username) {
		Query q = new Query();
		q.addCriteria(Criteria.where("username").is(username));

		return getMongoOperations().findOne(q, getEntityClass());
	}

	@Override
	public Class<UserImpl> getEntityClass() {
		return UserImpl.class;
	}

}


text:
package at.downdrown.vaadinaddons.highchartsapi.model.series;

import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.HighchartsObject;
import at.downdrown.vaadinaddons.highchartsapi.model.data.HighChartsData;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;

public interface HighChartsSeries extends HighchartsObject {

    //Needed for script generation!
    ChartType getChartType();

    //Data manipulation
    void addData(HighChartsData highChartsData);
    void addData(int value);
    void addData(float value);
    void addData(double value);
    void addData(DoubleDoubleData doubleDoubleData);
    void addData(DoubleIntData doubleIntData);
    void addData(IntDoubleData intDoubleData);
    void addData(IntIntData intIntData);
    void addData(StringDoubleData stringDoubleData);
    void addData(StringIntData stringIntData);

    void clearData();
}


text:
package com.dslplatform.client.json.Integer;

import com.dslplatform.client.JsonSerialization;
import com.dslplatform.patterns.Bytes;
import java.io.IOException;

public class OneIntegerDefaultValueTurtle {
	private static JsonSerialization jsonSerialization;

	@org.junit.BeforeClass
	public static void initializeJsonSerialization() throws IOException {
		jsonSerialization = com.dslplatform.client.StaticJson.getSerialization();
	}

	@org.junit.Test
	public void testDefaultValueEquality() throws IOException {
		final int defaultValue = 0;
		final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
		final int defaultValueJsonDeserialized = jsonSerialization.deserialize(int.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
		com.dslplatform.ocd.javaasserts.IntegerAsserts.assertOneEquals(defaultValue, defaultValueJsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue1Equality() throws IOException {
		final int borderValue1 = Integer.MIN_VALUE;
		final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
		final int borderValue1JsonDeserialized = jsonSerialization.deserialize(int.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.IntegerAsserts.assertOneEquals(borderValue1, borderValue1JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue2Equality() throws IOException {
		final int borderValue2 = Integer.MAX_VALUE;
		final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
		final int borderValue2JsonDeserialized = jsonSerialization.deserialize(int.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.IntegerAsserts.assertOneEquals(borderValue2, borderValue2JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue3Equality() throws IOException {
		final int borderValue3 = -1000000000;
		final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
		final int borderValue3JsonDeserialized = jsonSerialization.deserialize(int.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.IntegerAsserts.assertOneEquals(borderValue3, borderValue3JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue4Equality() throws IOException {
		final int borderValue4 = 1000000000;
		final Bytes borderValue4JsonSerialized = jsonSerialization.serialize(borderValue4);
		final int borderValue4JsonDeserialized = jsonSerialization.deserialize(int.class, borderValue4JsonSerialized.content, borderValue4JsonSerialized.length);
		com.dslplatform.ocd.javaasserts.IntegerAsserts.assertOneEquals(borderValue4, borderValue4JsonDeserialized);
	}
}


text:
package io.reactivex.rxjavafx.sources;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjavafx.subscriptions.JavaFxSubscriptions;
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

import java.util.Optional;

public class ObservableValueSource {

    public static <T> Observable<T> fromObservableValue(final ObservableValue<T> fxObservable) {
        return Observable.create((ObservableEmitter<T> emitter) -> {
            if (fxObservable.getValue() != null)
                emitter.onNext(fxObservable.getValue());

            final ChangeListener<T> listener = (observableValue, prev, current) -> {
                emitter.onNext(current);
            };

            fxObservable.addListener(listener);

            emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener)));
        });
    }

    public static <T> Observable<T> fromObservableValue(final ObservableValue<T> fxObservable, final T nullSentinel) {
        if (nullSentinel == null) {
            throw new NullPointerException("The null value sentinel must not be null.");
        }
        return Observable.create((ObservableEmitter<T> emitter) -> {
            if (fxObservable.getValue() != null) {
                emitter.onNext(fxObservable.getValue());
            }

            final ChangeListener<T> listener = (observableValue, prev, current) -> {
                if (current != null) {
                    emitter.onNext(current);
                } else {
                    emitter.onNext(nullSentinel);
                }
            };

            fxObservable.addListener(listener);

            emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener)));
        });
    }

    public static <T> Observable<Optional<T>> fromNullableObservableValue(final ObservableValue<T> fxObservable) {
        return Observable.create((ObservableEmitter<Optional<T>> emitter) -> {
            emitter.onNext(Optional.ofNullable(fxObservable.getValue()));

            final ChangeListener<T> listener = (observableValue, prev, current) -> emitter.onNext(Optional.ofNullable(current));

            fxObservable.addListener(listener);

            emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener)));
        });
    }

    public static <T> Observable<Change<T>> fromObservableValueChanges(final ObservableValue<T> fxObservable) {
        return Observable.create((ObservableEmitter<Change<T>> emitter) -> {
            final ChangeListener<T> listener = (observableValue, prev, current) -> {
                emitter.onNext(new Change<>(prev,current));
            };

            fxObservable.addListener(listener);

            emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener)));
        });
    }

    public static Observable<javafx.beans.Observable> fromInvalidations(javafx.beans.Observable fxObservable) {
        return Observable.create(emitter -> {
            final InvalidationListener listener = emitter::onNext;
            fxObservable.addListener(listener);
            emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener)));
        });
    }
}


text:
layout: attachment
title: ronin
date: 2015-07-08 18:02:45.000000000 +05:30
categories: []
tags: []
status: inherit
type: attachment
published: false
meta: {}
author:
  login: anukin2611
  email: anukin2611@gmail.com
  display_name: anukin2611
  first_name: ''
  last_name: ''
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---


text:
TMDB - Automatic Tests
======================
There are two Automatic Test Output Style

All scripts are stored at **$(PROJECT_ROOT)/scripts** directory, so as first step be sure you are located in the right path.

All test report is located inside directory **$(PROJECT_ROOT)/scripts/reports**

####1. Simples Output
run command:

```
$ make test
```

####2. Simples Output
run command:

```
$ make pretty-test
```
XCPretty is mandatory for this feature