text:
title: "RON HEADINGS ENDURING FOREST EXHIBIT"
date: "2000-01-01 18:05:25 -06:00"
categories:
- exhibit

subtitle: A Celebration of Trees in Wire
layout: "free-events"
event-image: "ron-headings-wiretree-exhibit.jpg"
event-dates: "MAY 25 - JUNE 17, 2018"
event-location: "Red Butte Garden Visitor Center"
button-type: "register"
tickets-link: ""
registration-info: "Questions?
Please call 801-585-0556"
instructor-info: "N/A"
member-cost: "Free"
public-cost: "Garden Admission"
event-notes: "Artist Reception May 26 @ 2-4PM"
tickets-button: "hide"
refund-policy: "hide"
published: false
---

Meet the Artist Reception

  Saturday, May 26 from 2-4PM

Ron Headings, 58, began creating wire trees as a teenager in Kansas. Inspired by his love of horticulture and the coaching of a local horticulture extension agent, Ron has refined his work with wire and rock over the years.

Trees are like people, the forest like humanity. They come in an infinate number of colors, shapes, and sizes - each one is beautiful in it's own way. The trees, like people, are shaped by their genetic structure and the environment in which they live.

Trees are created as a certain species with a variety of characteristics.  Then they are changed by the locations in which they live, the amount of water and nutrients they receive, and the impact of wind and weather.

For more, please visit: www.HeadingsArts.com


text:
/**
 * Selfbits API V2
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: 2.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

import * as models from './models';

export interface NewFileResponse {
    file?: models.File;

    fileId?: string;

    putFileUrl?: string;

    postVerifyUploadUrl?: string;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Google\AdsApi\Examples\AdWords\v201702\BasicOperations;

require '../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201702\cm\AdGroupCriterionOperation;
use Google\AdsApi\AdWords\v201702\cm\AdGroupCriterionService;
use Google\AdsApi\AdWords\v201702\cm\AgeRange;
use Google\AdsApi\AdWords\v201702\cm\BiddableAdGroupCriterion;
use Google\AdsApi\AdWords\v201702\cm\Gender;
use Google\AdsApi\AdWords\v201702\cm\NegativeAdGroupCriterion;
use Google\AdsApi\AdWords\v201702\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds demographic target criteria to an ad group.
 * To get ad groups, run AddAdGroup.php.
 */
class AddAdGroupDemographicCriteria {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $adGroupCriterionService =
        $adWordsServices->get($session, AdGroupCriterionService::class);

    $operations = [];

    // Create biddable ad group criterion for gender.
    $genderTarget = new Gender();
    // ID for "male" criterion. The IDs can be found here:
    // https://developers.google.com/adwords/api/docs/appendix/genders
    $genderTarget->setId(10);
    $genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    $genderBiddableAdGroupCriterion->setAdGroupId($adGroupId);
    $genderBiddableAdGroupCriterion->setCriterion($genderTarget);

    // Create an ad group criterion operation and add it to the list.
    $genderBiddableAdGroupCriterionOperation = new AdGroupCriterionOperation();
    $genderBiddableAdGroupCriterionOperation->setOperand(
        $genderBiddableAdGroupCriterion);
    $genderBiddableAdGroupCriterionOperation->setOperator(Operator::ADD);
    $operations[] = $genderBiddableAdGroupCriterionOperation;

    // Create negative ad group criterion for age range.
    $ageRangeNegative = new AgeRange();
    // Criterion ID for age 18 to 24. The IDs can be found here:
    // https://developers.google.com/adwords/api/docs/appendix/ages
    $ageRangeNegative->setId(503001);
    $ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion();
    $ageRangeNegativeAdGroupCriterion->setAdGroupId($adGroupId);
    $ageRangeNegativeAdGroupCriterion->setCriterion($ageRangeNegative);

    // Create an ad group criterion operation and add it to the list.
    $ageRangeNegativeAdGroupCriterionOperation =
        new AdGroupCriterionOperation();
    $ageRangeNegativeAdGroupCriterionOperation->setOperand(
        $ageRangeNegativeAdGroupCriterion);
    $ageRangeNegativeAdGroupCriterionOperation->setOperator(Operator::ADD);
    $operations[] = $ageRangeNegativeAdGroupCriterionOperation;

    // Create the ad group criteria on the server and print out some information
    // for each created ad group criterion.
    $result = $adGroupCriterionService->mutate($operations);
    foreach ($result->getValue() as $adGroupCriterion) {
      printf(
          "Ad group criterion with ad group ID %d, criterion ID %d "
              . "and type '%s' was added.\n",
          $adGroupCriterion->getAdGroupId(),
          $adGroupCriterion->getCriterion()->getId(),
          $adGroupCriterion->getCriterion()->getType()
      );
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::AD_GROUP_ID));
  }
}

AddAdGroupDemographicCriteria::main();


text:
import React, {SFC, MouseEvent} from 'react'

import {MarkdownRenderer} from 'src/shared/components/views/MarkdownRenderer'
import {DapperScrollbars} from '@influxdata/clockface'

interface Props {
  note: string
  scrollTop: number
  onScroll: (e: MouseEvent) => void
}

const cloudImageRenderer = (): any =>
  "We don't support images in markdown for security purposes"

const NoteEditorPreview: SFC<Props> = props => {
  return (

      <DapperScrollbars
        className="note-editor--preview-scroll"
        scrollTop={props.scrollTop}
        onScroll={props.onScroll}
      >

          <MarkdownRenderer
            text={props.note}
            className="markdown-format"
            cloudRenderers={{
              image: cloudImageRenderer,
              imageReference: cloudImageRenderer,
            }}
          />

      </DapperScrollbars>

  )
}

export default NoteEditorPreview


text:
{% comment %}
  Main title for lesson pages.
{% endcomment %}

{% include base_path.html %}

{{ site.title }}{% if page.title %}: {{ page.title }}{% endif %}


text:
/*
	SObjectizer 5.
*/

/*!
	\file
	\brief Interface for the dispatcher definition.
*/

#if !defined( _SO_5__RT__DISP_HPP_ )
#define _SO_5__RT__DISP_HPP_

#include <memory>
#include <map>
#include <string>

#include <so_5/h/declspec.hpp>
#include <so_5/h/ret_code.hpp>

namespace so_5
{

namespace rt
{

//
// dispatcher_t
//

//! An interface for all dispatchers.
/*!
 * Dispatcher schedules and calls agents' events.
 *
 * Each agent is binded to a dispatcher during the registration.
 * A dispatcher_binder_t object is used for this.
 *
 * Each agent stores its events in the own event queue. When event is
 * stored in the queue an agent informs its dispatcher about it.
 * The dispatcher should schedule the agent for the event execution on
 * the agent's working thread context.
 */
class SO_5_TYPE dispatcher_t
{
	public:
		/*! Do nothing. */
		dispatcher_t();
		/*! Do nothing. */
		virtual ~dispatcher_t();

		/*! Auxiliary method. */
		inline dispatcher_t *
		self_ptr()
		{
			return this;
		}

		//! Launch the dispatcher.
		virtual void
		start() = 0;

		//! Signal about shutdown.
		/*!
		 * Dispatcher must initiate actions for the shutting down of all
		 * working threads. This method shall not block caller until
		 * all threads have beed stopped.
		 */
		virtual void
		shutdown() = 0;

		//! Wait for the full stop of the dispatcher.
		/*!
		 * This method must block the caller until all working threads
		 * have been stopped.
		 */
		virtual void
		wait() = 0;
};

//! Typedef of the dispatcher autopointer.
typedef std::unique_ptr< dispatcher_t > dispatcher_unique_ptr_t;

//! Typedef of the dispatcher smart pointer.
typedef std::shared_ptr< dispatcher_t >
	dispatcher_ref_t;

//! Typedef of the map from dispatcher name to a dispather.
typedef std::map<
		std::string,
		dispatcher_ref_t >
	named_dispatcher_map_t;

} /* namespace rt */

} /* namespace so_5 */

#endif


text:
package xhsun.gw2app.steve.view.dialog.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import xhsun.gw2app.steve.R;
import xhsun.gw2app.steve.backend.util.support.dialog.CustomAlertDialogListener;

/**
 * Template for custom alert dialog
 *
 * @author xhsun
 * @since 2017-03-26
 */

public class CustomAlertDialog extends DialogFragment {
	private CustomAlertDialogListener listener;
	private String title_str;
	private String content_str;
	@BindView(R.id.dialog_alert_title)
	TextView title;
	@BindView(R.id.dialog_alert_content)
	TextView content;

	@NonNull
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = View.inflate(getContext(), R.layout.dialog_alert_template, null);
		ButterKnife.bind(this, view);

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setView(view);

		title.setText(title_str);
		content.setText(content_str);

		builder.setPositiveButton("OK", (dialog, which) -> {
			listener.onPositiveClick();
			CustomAlertDialog.this.dismiss();
		})
				.setNegativeButton("Cancel", (dialog, which) -> {
					listener.onNegativeClick();
					CustomAlertDialog.this.dismiss();
				});
		return builder.create();
	}

	public void setListener(CustomAlertDialogListener listener) {
		this.listener = listener;
	}

	public void setTitle(String title) {
		title_str = title;
	}

	public void setContent(String content) {
		content_str = content;
	}
}


text:
#include "avionics/servo/firmware/r22_types.h"

#include "avionics/firmware/drivers/log.h"

const char *R22ErrorName(R22Error code) {
  switch (code) {
    case kR22ErrorNone:
      return "None";
    case kR22ErrorTooMuchDataSent:
      return "TooMuchDataSent";
    case kR22ErrorChecksum:
      return "Checksum";
    case kR22ErrorIllegalOpCode:
      return "IllegalOpCode";
    case kR22ErrorNotEnoughData:
      return "NotEnoughData";
    case kR22ErrorUnexpectedData:
      return "UnexpectedData";
    case kR22ErrorErasingFlashMemory:
      return "ErasingFlashMemory";
    case kR22ErrorWritingFlashMemory:
      return "WritingFlashMemory";
    case kR22ErrorIllegalMemoryPageSpecified:
      return "IllegalMemoryPageSpecified";
    case kR22ErrorUnknownVariableId:
      return "UnknownVariableId";
    case kR22ErrorParameterValueOutOfRange:
      return "ParameterValueOutOfRange";
    case kR22ErrorReadOnlyParameter:
      return "ReadOnlyParameter";
    case kR22ErrorInvalidTraceChannel:
      return "InvalidTraceChannel";
    case kR22ErrorInvalidTraceVariableNumber:
      return "InvalidTraceVariableNumber";
    case kR22ErrorInvalidModeOfOperation:
      return "InvalidModeOfOperation";
    case kR22ErrorVariableDoesNotExist:
      return "VariableDoesNotExist";
    case kR22ErrorIllegalSerialForwarding:
      return "IllegalSerialForwarding";
    case kR22ErrorDataFlashCrcError:
      return "DataFlashCrcError";
    case kR22ErrorIllegalMoveAttempt:
      return "IllegalMoveAttempt";
    case kR22ErrorIllegalVelocityLimit:
      return "IllegalVelocityLimit";
    case kR22ErrorIllegalAccelerationLimit:
      return "IllegalAccelerationLimit";
    case kR22ErrorIllegalDecelerationLimit:
      return "IllegalDecelerationLimit";
    case kR22ErrorIllegalJerkLimit:
      return "IllegalJerkLimit";
    case kR22ErrorTrajectoryBufferUnderflow:
      return "TrajectoryBufferUnderflow";
    case kR22ErrorTrajectoryBufferOverflow:
      return "TrajectoryBufferOverflow";
    case kR22ErrorInvalidTrajectoryMode:
      return "InvalidTrajectoryMode";
    case kR22ErrorCvmLocationNotAvailable:
      return "CvmLocationNotAvailable";
    case kR22ErrorIllegalOperationCvmRunning:
      return "IllegalOperationCvmRunning";
    case kR22ErrorCvmTooBigToUpload:
      return "CvmTooBigToUpload";
    case kR22ErrorInternalFileSystem:
      return "InternalFileSystem";
    case kR22ErrorProgramDoesNotExist:
      return "ProgramDoesNotExist";
    case kR22ErrorInvalidNodeIdSerialForwarding:
      return "InvalidNodeIdSerialForwarding";
    case kR22ErrorCanNetworkFailure:
      return "CanNetworkFailure";
    case kR22ErrorAsciiParsingFailure:
      return "AsciiParsingFailure";
    case kR22ErrorInternalError:
      return "InternalError";
    case kR22ErrorFileSystemReadOnlyCammingMode:
      return "FileSystemReadOnlyCammingMode";
    case kR22ErrorIllegalAxisSpecified:
      return "IllegalAxisSpecified";
    case kR22ErrorInvalidFpgaDataStored:
      return "InvalidFpgaDataStored";
    case kR22ErrorUnableToInitializeFpga:
      return "UnableToInitializeFpga";
    case kR22ErrorFpgaFailedToConfigure:
      return "FpgaFailedToConfigure";
    case kR22ErrorFileAlreadyExists:
      return "FileAlreadyExists";
    case kR22ErrorNoFreeFileEntriesInDirectory:
      return "NoFreeFileEntriesInDirectory";
    case kR22ErrorFileDoesNotExist:
      return "FileDoesNotExist";
    case kR22ErrorNoFreeSpaceInFileSystem:
      return "NoFreeSpaceInFileSystem";
    case kR22ErrorInvalidFileFormat:
      return "InvalidFileFormat";
    case kR22ErrorEndOfFileWhileReading:
      return "EndOfFileWhileReading";
    case kR22ErrorSendingCommandToEncoder:
      return "SendingCommandToEncoder";
    case kR22ErrorIllegalOperationInSerialMode:
      return "IllegalOperationInSerialMode";
    case kR22ErrorUnableToCalculateFilter:
      return "UnableToCalculateFilter";
    case kR22ErrorIndexerRegister31NotSet:
      return "IndexerRegister31NotSet";
    case kR22ErrorTimeout:
      return "Timeout";
    default:
      return "<Unknown>";
  }
}

const char *R22StatusBitName(R22StatusBit code) {
  switch (code) {
    case kR22StatusBitShortCircuitDetected:
      return "ShortCircuitDetected";
    case kR22StatusBitDriveOverTemperature:
      return "DriveOverTemperature";
    case kR22StatusBitOverVoltage:
      return "OverVoltage";
    case kR22StatusBitUnderVoltage:
      return "UnderVoltage";
    case kR22StatusBitMotorTemperatureSensorActive:
      return "MotorTemperatureSensorActive";
    case kR22StatusBitFeedbackError:
      return "MotorFeedbackError";
    case kR22StatusBitMotorPhasingError:
      return "MotorPhasingError";
    case kR22StatusBitCurrentOutputLimited:
      return "CurrentOutputLimited";
    case kR22StatusBitVoltageOutputLimited:
      return "VoltageOutputLimited";
    case kR22StatusBitPositiveLimitSwitchActive:
      return "PositiveLimitSwitchActive";
    case kR22StatusBitNegativeLimitSwitchActive:
      return "NegativeLimitSwitchActive";
    case kR22StatusBitEnableInputNotActive:
      return "EnableInputNotActive";
    case kR22StatusBitDriveDisabledBySoftware:
      return "DriveDisabledBySoftware";
    case kR22StatusBitTryingToStopMotor:
      return "TryingToStopMotor";
    case kR22StatusBitMotorBrakeActive:
      return "MotorBrakeActive";
    case kR22StatusBitPwmOutputDisabled:
      return "PwmOutputDisabled";
    case kR22StatusBitPositiveSoftwareLimitCondition:
      return "PositiveSoftwareLimitCondition";
    case kR22StatusBitNegativeSoftwareLimitCondition:
      return "NegativeSoftwareLimitCondition";
    case kR22StatusBitTrackingError:
      return "TrackingError";
    case kR22StatusBitTrackingWarning:
      return "TrackingWarning";
    case kR22StatusBitDriveHasBeenReset:
      return "DriveHasBeenReset";
    case kR22StatusBitPositionWrapper:
      return "PositionWrapper";
    case kR22StatusBitDriveFault:
      return "DriveFault";
    case kR22StatusBitVelocityLimitReached:
      return "VelocityLimitReached";
    case kR22StatusBitAccelerationLimitReached:
      return "AccelerationLimitReached";
    case kR22StatusBitPositionOutsideTrackingWindow:
      return "PositionOutsideTrackingWindow";
    case kR22StatusBitHomeSwitchActive:
      return "HomeSwitchActive";
    case kR22StatusBitTrajectoryRunning:
      return "TrajectoryRunning";
    case kR22StatusBitVelocityWindowExceeded:
      return "VelocityWindowExceeded";
    case kR22StatusBitPhaseNotInitialized:
      return "PhaseNotInitialized";
    case kR22StatusBitCommandFault:
      return "CommandFault";
    case kR22StatusBitNotDefined:
      return "NotDefined";
    default:
      return "<Unknown>";
  }
}

void R22LogStatusBits(R22StatusBit mask) {
  while (mask) {
    R22StatusBit mask_1 = mask - 1;
    LOG_PRINTF("R22 status: %s\n", R22StatusBitName((mask ^ mask_1) & ~mask_1));
    mask &= mask_1;
  }
}


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ["page","perPage","sortByField"],
  page: 1,

  updatePaged: Ember.observer("sortByField", function() {
    var field = this.get('sortByField');
    var paged = this.get('model');
    if (paged && paged.setOtherParam) {
      paged.setOtherParam('sortByField',field);
    }
  })
});


text:
The Credence Database Abstraction Layer (DBAL) offers a lightwight runtime layer that provides common database
functionality that can be integrated into any number of drivers.  Adapters are currently provided naitively for the
following database vendors:

* SQLite

### Code Quality Report

### Contributing

There are many ways to contribute to Credence projects!  If you have an idea, or have discovered a bug, please
[Open an Issue](https://github.com/credence/credence-dbal/issues) so it can be addressed.

If you're interested in contributing to the project through design or development, please read our
[Contribution Guidelines](https://github.com/credence/credence-dbal/blob/master/CONTRIBUTING.md).

### Usage

Coming soon...

### Release Policy

Releases of Credence DBAL follow [Semantic Versioning](http://semver.org/) standards in a `MAJOR.MINOR.PATCH`
versioning scheme of the following format:

* `MAJOR` - modified when major, incompatible changes are made to the library,
* `MINOR` - modified when functionality is added in a backwards-compatible mannder, and
* `PATCH` - patches to existing functionality, such as documentation and bug fixes.

### License

Please refer to the Credence DBAL [license agreement](LICENSE).


text:
#ifndef STATE_ESTIMATOR_H
#define STATE_ESTIMATOR_H

#include "Sensor.h"
#include "Command.h"
#include "Modeling/Robot.h"
#include <robotics/Wrench.h>

class ODERobot;

/** @ingroup Control
 * @brief A generic state estimator base class.  Base class does nothing.
 *
 * Typical state estimators will update the robot state (q,dq, frames)
 * for the given sensor input.  They may also do more sophisticated things,
 * like calibrate the robot limb lengths, dynamic parameters, or even a
 * world model.
 *
 * The typical sensor loop is ReadSensors, UpdateModel, ReadCommand,
 * Advance.  A RobotController will call these manually.
 */
struct RobotStateEstimator
{
  RobotStateEstimator(Robot& _robot) :robot(_robot) {}
  virtual ~RobotStateEstimator() {}
  virtual void ReadSensors(RobotSensors& sensors) {}
  virtual void UpdateModel() {}
  virtual void ReadCommand(const RobotMotorCommand& command) {}
  virtual void Advance(Real dt) {}
  virtual void Reset() {}

  Robot& robot;
};

/** @ingroup Control
 * @brief A state estimator will full knowledge of the robot's simulated
 * state.  An ODERobot must be provided at initialization.
 */
struct OmniscientStateEstimator : public RobotStateEstimator
{
  OmniscientStateEstimator(Robot& _robot,ODERobot& _oderobot)
    :RobotStateEstimator(_robot),oderobot(_oderobot) {}
  virtual ~OmniscientStateEstimator();
  virtual void UpdateModel();

  ODERobot& oderobot;
};

/** @ingroup Control
 * @brief A state estimator that integrates information from accelerometers
 * (i.e., an Inertial Measurement Unit) and gravity sensors.
 *
 * It may also integrate a predicted acceleration ddq_predicted through
 * time, although this is not as accurate as a Kalman filter.
 */
struct IntegratedStateEstimator : public RobotStateEstimator
{
  IntegratedStateEstimator(Robot& _robot);
  virtual ~IntegratedStateEstimator() {}
  virtual void ReadSensors(RobotSensors& sensors);
  virtual void UpdateModel() {
    robot.UpdateConfig(q_predicted);
    robot.dq = dq_predicted;
  }
  virtual void ReadCommand(const RobotMotorCommand& command);
  virtual void Advance(Real dt);
  virtual void Reset();

  //instead of ReadCommand, this estimator uses SetDDQ
  void SetDDQ(const Vector& ddq) { ddq_predicted = ddq; }

  Real last_dt;
  Vector q_predicted,dq_predicted,ddq_predicted;
  Vector q_sensed,dq_sensed;
  //these correspond to the world positions of the accelerometers in the sensors
  vector<RigidTransform> accelerometerFrames;
  vector<RigidBodyVelocity> accelerometerVels;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleStarter.apps.calculator
{
    class Subtraction
    {
        static public int sub(int Num1, int Num2)
        {
            return Num1 - Num2;
        }
    }
}


text:
from django.shortcuts import render_to_response

def about(request):
    return render_to_response('about.html')


text:
module.exports = function Thing() {
	return "thing";
}

module.exports.Other = "other";


text:
package resourcemetrics

import (
	"fmt"
	"html/template"
	"reflect"
	ttemplate "text/template"

	"kmodules.xyz/resource-metrics/api"

	"gomodules.xyz/encoding/json"
	core "k8s.io/api/core/v1"
)

// TxtFuncMap returns a 'text/template'.FuncMap
func TxtFuncMap() ttemplate.FuncMap {
	return ttemplate.FuncMap(GenericFuncMap())
}

// HtmlFuncMap returns an 'html/template'.Funcmap
func HtmlFuncMap() template.FuncMap {
	return template.FuncMap(GenericFuncMap())
}

// GenericFuncMap returns a copy of the basic function map as a map[string]interface{}.
func GenericFuncMap() map[string]interface{} {
	return map[string]interface{}{
		"k8s_resource_replicas":          tplReplicaFn,
		"k8s_resource_replicas_by_roles": tplRoleReplicaFn,
		"k8s_resource_mode":              tplModeFn,
		"k8s_resource_uses_tls":          tplUsesTLSFn,
		"k8s_total_resource_limits":      tplTotalResourceLimitsFn,
		"k8s_total_resource_requests":    tplTotalResourceRequestsFn,
		"k8s_app_resource_limits":        tplAppResourceLimitsFn,
		"k8s_app_resource_requests":      tplAppResourceRequestsFn,
	}
}

func tplReplicaFn(data interface{}) (int64, error) {
	obj, err := toObject(data)
	if err != nil {
		return 0, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return 0, err
	}
	return c.Replicas(obj)
}

func tplRoleReplicaFn(data interface{}) (interface{}, error) {
	obj, err := toObject(data)
	if err != nil {
		return nil, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return nil, err
	}
	replicaList, err := c.RoleReplicas(obj)
	if err != nil {
		return nil, err
	}

	has := func(role api.PodRole) bool {
		_, ok := replicaList[role]
		return ok
	}
	if has(api.PodRoleDefault) {
		if len(replicaList) == 1 {
			return replicaList[api.PodRoleDefault], nil
		} else {
			// case: elasticsearch
			delete(replicaList, api.PodRoleDefault)
			return replicaList, nil
		}
	} else if has(api.PodRoleTotalShard) {
		// case: mongodb, redis
		delete(replicaList, api.PodRoleTotalShard)
		return replicaList, nil
	}
	return replicaList, nil
}

func tplModeFn(data interface{}) (string, error) {
	obj, err := toObject(data)
	if err != nil {
		return "", err
	}

	c, err := api.Load(obj)
	if err != nil {
		return "", err
	}
	return c.Mode(obj)
}

func tplUsesTLSFn(data interface{}) (bool, error) {
	obj, err := toObject(data)
	if err != nil {
		return false, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return false, err
	}
	return c.UsesTLS(obj)
}

func tplTotalResourceLimitsFn(data interface{}) (core.ResourceList, error) {
	obj, err := toObject(data)
	if err != nil {
		return nil, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return nil, err
	}
	return c.TotalResourceLimits(obj)
}

func tplTotalResourceRequestsFn(data interface{}) (core.ResourceList, error) {
	obj, err := toObject(data)
	if err != nil {
		return nil, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return nil, err
	}
	return c.TotalResourceRequests(obj)
}

func tplAppResourceLimitsFn(data interface{}) (core.ResourceList, error) {
	obj, err := toObject(data)
	if err != nil {
		return nil, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return nil, err
	}
	return c.AppResourceLimits(obj)
}

func tplAppResourceRequestsFn(data interface{}) (core.ResourceList, error) {
	obj, err := toObject(data)
	if err != nil {
		return nil, err
	}

	c, err := api.Load(obj)
	if err != nil {
		return nil, err
	}
	return c.AppResourceRequests(obj)
}

func toObject(data interface{}) (map[string]interface{}, error) {
	var obj map[string]interface{}
	if v, ok := data.(map[string]interface{}); ok {
		obj = v
	} else if str, ok := data.(string); ok {
		err := json.Unmarshal([]byte(str), &obj)
		if err != nil {
			return nil, err
		}
	} else {
		return nil, fmt.Errorf("unknown obj type %v", reflect.TypeOf(data).String())
	}
	return obj, nil
}


text:
$.validator.addMethod('blackword',
function (value, element, param) {
    value = $.trim(value);
    if (value === '') { return true; }

    var list = param.split(',');
    for (var i = 0, len = list.length; i < len; i++) {
        if (value.indexOf(list[i]) !== -1)
        {
            return false;
        }
    }
    return true;
});

$.validator.unobtrusive.adapters.addSingleVal('blackword', 'opts');


text:
require File.dirname(__FILE__) + '/../lib/sensu/base.rb'
require File.dirname(__FILE__) + '/helpers.rb'

describe 'Sensu::Extensions' do
  include Helpers

  before do
    @extensions = Sensu::Extensions.new
  end

  it 'can load the default extensions' do
    @extensions.should respond_to(:[], :mutator_exists?, :handler_exists?)
    @extensions[:mutators].should be_kind_of(Hash)
    @extensions[:mutators].should be_empty
    @extensions[:handlers].should be_kind_of(Hash)
    @extensions[:handlers].should be_empty
    @extensions.load_all
    @extensions[:mutators]['only_check_output'].should be_an_instance_of(Sensu::Extension::OnlyCheckOutput)
    @extensions[:handlers]['debug'].should be_an_instance_of(Sensu::Extension::Debug)
  end

  it 'can load custom extensions and ignore those with syntax errors' do
    @extensions.require_directory(options[:extension_dir])
    @extensions.load_all
    @extensions.mutator_exists?('opentsdb')
    @extensions[:mutators]['opentsdb'].should be_an_instance_of(Sensu::Extension::OpenTSDB)
  end

  it 'can stop all extensions for cleanup purposes' do
    @extensions.load_all
    stopped_all = false
    @extensions.stop_all do
      stopped_all = true
    end
    stopped_all.should be_true
  end
end


text:
#ifndef basic_child_node_H_INCLUDED
#define basic_child_node_H_INCLUDED

namespace xml {
    template <typename charT>
    class basic_child_node;
}

#include <node-interface.h>
#include <child-node.h>
#include <iterator.h>

namespace xml {
    //! \brief An abstract XML node that has a parent and siblings.
    /*!
     *  This class represents an abstract XML node that has a parent
     *  and possibly two siblings : one before and one after.
     *
     *  \sa xml::basic_parent_node
     *
     *  \tparam charT The type of character used in the XML node.
     *                By default, char and wchar_t are supported.
     */
    template <typename charT>
    class basic_child_node : public virtual basic_node_interface<charT> {
    public:
        //! \name Member types
        //!@{
        typedef basic_node_interface<charT> node_interface_t; //!< The base type of this node.

        typedef basic_child_node<charT>   child_t;                 //!< The type of children this node is.
        typedef child_t*                  child_pointer_t;         //!< Pointer to \c child_t.
        typedef child_t&                  child_reference_t;       //!< Reference to \c child_t.
        typedef const child_t&            child_const_reference_t; //!< Constant reference to \c child_t.
        typedef child_t&&                 child_move_t;            //!< Move a \c child_t.

        typedef          basic_parent_node<charT>     parent_t;           //!< The parent node type.
        typedef typename parent_t::parent_pointer_t   parent_pointer_t;   //!< A pointer to the parent type.
        typedef typename parent_t::parent_reference_t parent_reference_t; //!< A reference to the parent type.

        //!@}

        //! \brief Default constructor
        /*!
         *  This constructor initialise the internals of a child node
         *  (i.e. its parent, and its next and previous child node).
         *
         *  \param[in] parent The parent node of this one.
         */
        basic_child_node(parent_pointer_t parent = nullptr)
        :
            node_interface_t(),
            mParent(parent),
            mPrevious(nullptr),
            mNext(nullptr)
        {}

        //! \brief Copy constructor
        /*!
         *  This constructor initialise the internals of a child node
         *  (i.e. its parent, and its next and previous child node).
         *
         *  \param [in] rhs A constant reference to a \c child_t.
         */
        basic_child_node(child_const_reference_t rhs)
        :
            node_interface_t(rhs),
            mParent(nullptr),
            mPrevious(nullptr),
            mNext(nullptr)
        {}

        //! \brief Move constructor
        /*!
         *  This constructor initialise the internals of a child node
         *  (i.e.  its parent, and its next and previous child node),
         *  and takes the place of \c rhs.
         *
         *  \param [in] rhs A rvalue reference to a \c child_t.
         */
        basic_child_node(child_move_t rhs)
        :
            node_interface_t(rhs),
            mParent(rhs.mParent),
            mPrevious(rhs.mPrevious),
            mNext(rhs.mNext)
        {
            if (mPrevious)
                mPrevious->mNext = this;
            else
                mParent->mFirst = this;

            if (mNext)
                mNext->mPrevious = this;
            else
                mParent->mLast = this;
        }

        //! \brief Default destructor
        /*!
         *  This destructor reset all the internal values.
         */
        virtual ~basic_child_node()
        {
            mNext = nullptr;
            mPrevious = nullptr;
            mParent = nullptr;
        }

        //! \brief Clone the current \c basic_child_node.
        /*!
         *  This function creates a deep copy of this \c basic_child_node,
         *  and returns a pointer to it. It is used when copying element in
         *  parent node.
         */
        virtual child_pointer_t clone() const = 0;

        //! \brief Clone the given \c basic_child_node using move syntax.
        /*!
         *  This function creates a deep copy of the given\c basic_child_node,
         *  and returns a pointer to it. It is used when copying element in
         *  parent node.
         */
        virtual child_pointer_t clone(child_move_t rhs) const = 0;

        //! \brief Returns the node's parent.
        /*!
         *  This function returns a \c const reference to the node's parent.
         *  Note that a \c basic_child_node belongs to its parent node, and
         *  that the parent node will always be defined.
         *
         *  \return A \c const reference to the node's parent.
         */
        const parent_reference_t parent() const { return *mParent; }

        //! \brief Returns the node's parent.
        /*!
         *  This function returns a reference to the node's parent.
         *  Note that a \c basic_child_node belongs to its parent node, and
         *  that the parent node will always be defined.
         *
         *  \return A reference to the node's parent.
         */
        parent_reference_t parent() { return *mParent; }

    protected:
        parent_pointer_t mParent;  //!< A pointer to the current node's parent

        child_pointer_t mPrevious; //!< A pointer to the current previous node sibling. Might be \c null
        child_pointer_t mNext;     //!< A pointer to the current next node sibling. Might be \c null

        template <typename charU, class classT>
        friend class xml::basic_iterator;

        friend class basic_parent_node<charT>;
    };

    typedef basic_child_node<char>    child_node;  //!< A specialized \c basic_child_node for char.
    typedef basic_child_node<wchar_t> wchild_node; //!< A specialized \c basic_child_node for wchar_t.
}

#endif /* basic_child_node_H_INCLUDED */


text:
class Integer
  unless public_method_defined?('ord') then
    # Returns the int itself.
    #
    # This method is defined here only if not already defined elsewhere, such as
    # versions of Ruby prior to 1.8.7.
    def ord
      self
    end
  end
end


text:
const colors = require('colors');
const path = require('path');
const dir = require('../lib/node-dir');

class TemplateManager {
  constructor(templateSrcFolder) {
    this.templateSrcFolder = templateSrcFolder;
  }

  static getLocalTemplates(rootTemplateFolder) {
    const hasFiles = dir.files(rootTemplateFolder, {
      sync: true,
    });
    if (!hasFiles) {
      return [];
    }

    const files = dir
      .files(rootTemplateFolder, {
        sync: true,
      })
      .filter(function (file) {
        return file.indexOf('template.json') > -1;
      })
      .filter(function (file) {
        return file.indexOf('__MACOSX') === -1;
      })
      .map((f) =>
        f
          .replace(path.join(rootTemplateFolder, '/'), '')
          .replace('\\', '/') // for windows
          .replace('/template.json', '')
      );

    return files;
  }

  get() {
    const template = {
      f: this.templateSrcFolder,
      dir: this.templateSrcFolder,
      files: [],
    };
    const files = this.builder({
      dir: template.dir,
    });
    template.files = files;

    return template;
  }

  builder(options) {
    const hasFiles = dir.files(options.dir, {
      sync: true,
    });
    if (!hasFiles) {
      console.log(colors.yellow('Template folder is empty.'));
      return [];
    }

    const files = dir
      .files(options.dir, {
        sync: true,
      })
      .filter(function (file) {
        return file.indexOf('.DS_Store') === -1;
      })
      .map((f) => ({
        src: f,
      }))
      .map((f) => ({
        src: f.src,
        dist: f.src
          .replace(path.join(options.dir, '/'), '')
          .replace('.sd', '')
          .replace('.java.txt', '.java')
          .replace('.css.txt', '.css')
          .replace('.html.txt', '.html')
          .replace('.ts.txt', '.ts')
          .replace('.js.txt', '.js')
          .replace('.cs.txt', '.cs')
          .replace('.scss.txt', '.scss')
          .replace('.json.txt', '.json'),
      }));

    return files;
  }
}

module.exports = TemplateManager;


text:
/**
 * Step 8
 * Called last, cleanup, say good bye, etc
 */

import chalk from 'chalk';
import printMessage from 'print-message';

export default function () {
  printMessage([
    `Your ${chalk.green('Hapi')} Application has been created!`,
    `---`,
    `To start your application, run: ${chalk.red('npm start')}`,
    `Main URL: http://localhost:3000/api/v1`
  ], {
    printFn: this.log
  });
};


text:
package org.apache.hadoop.hbase.ipc;

import java.net.InetSocketAddress;

import org.apache.yetus.audience.InterfaceAudience;

@InterfaceAudience.Private
class RpcSchedulerContext extends RpcScheduler.Context {
  private final RpcServer rpcServer;

  /**
   * @param rpcServer
   */
  RpcSchedulerContext(final RpcServer rpcServer) {
    this.rpcServer = rpcServer;
  }

  @Override
  public InetSocketAddress getListenerAddress() {
    return this.rpcServer.getListenerAddress();
  }
}


text:
#include "Kdtree.h"
#include <cstdio>
#include <algorithm>
#include <numeric>
#include <cmath>

namespace P_RVD{
	// Eww global. Need this for the sort function
	// A pointer to the class itself, allows the sort function to determine the splitting axis to sort by
	static KDtree *myself = NULL;

	KDtree::KDtree()
	{
		myself = this;
		m_id = 0;
	}

	KDtree::~KDtree()
	{
		// Delete all the ndoes
		std::vector <KDNode*> to_visit;

		to_visit.push_back(m_root);

		while (to_visit.size()) {
			std::vector <KDNode*> next_search;

			while (to_visit.size()) {
				KDNode *cur = to_visit.back();
				to_visit.pop_back();

				if (cur->left)
					next_search.push_back(cur->left);

				if (cur->right)
					next_search.push_back(cur->right);

				delete cur;
			}

			to_visit = next_search;
		}

		m_root = NULL;
	}

	void KDtree::Create_kdtree(std::vector<Kd_tree_point> &pts, int max_levels)
	{
		m_pts = &pts;
		m_levels = max_levels;

		m_root = new KDNode();
		m_root->id = m_id++;
		m_root->index.resize(pts.size());

		//init the index
		for (unsigned int i = 0; i < pts.size(); ++i)
		{
			m_root->index[i] = i;
		}

		std::vector<KDNode*> to_visit;
		to_visit.push_back(m_root);

		while (to_visit.size())
		{
			std::vector<KDNode*> next_search;
			while (to_visit.size())
			{
				KDNode *node = to_visit.back();
				to_visit.pop_back();;

				if (node->level < max_levels)
				{
					//if current node's index size > 1
					//it has more than 1 point in this space
					//So split it
					if (node->index.size() > 1)
					{
						KDNode *left = new KDNode();
						KDNode *right = new KDNode();

						left->id = m_id++;
						right->id = m_id++;

						Split(node, left, right);

						//Claer current index
						{
							//std::vector<int> dummy;
							//node->index.swap(dummy);
						}

						node->left = left;
						node->right = right;

						node->_left = left->id;
						node->_right = right->id;

						if (left->index.size())
							next_search.push_back(left);

						if (right->index.size())
							next_search.push_back(right);
					}
				}
			}
			to_visit = next_search;
		}
	}

	/*
		compare the data of 2 points with the index
	*/
	bool KDtree::SortPoints(const int a, const int b)
	{
		std::vector<Kd_tree_point> &pts = *myself->m_pts;

		return pts[a].coords[myself->m_current_axis] < pts[b].coords[myself->m_current_axis];
	}

	/*
		Split the current node into 2 part: left and right

		we assume that the left and right nodes are already created
	*/
	void KDtree::Split(KDNode *cur, KDNode *left, KDNode *right)
	{
		std::vector<Kd_tree_point> &pts = *m_pts;
		m_current_axis = cur->level % KDTREE_DIM;

		//sort the points by the axis value
		std::sort(cur->index.begin(), cur->index.end(), KDtree::SortPoints);

		int mid = cur->index[cur->index.size() / 2];
		cur->split_value = pts[mid].coords[m_current_axis];

		left->parent = cur;
		right->parent = cur;

		left->level = cur->level + 1;
		right->level = cur->level + 1;

		left->_parent = cur->id;
		right->_parent = cur->id;

		for (unsigned int i = 0; i < cur->index.size(); ++i)
		{
			int idx = cur->index[i];
			if (pts[idx].coords[m_current_axis] < cur->split_value)
				left->index.push_back(idx);
			else
				right->index.push_back(idx);
		}
	}

	/*
		search the best node
		return the index and distance square of the closed point in this node
	*/
	void KDtree::SearchAtNode(KDNode *cur, const Kd_tree_point &query, int *ret_index, double *ret_dist, KDNode **ret_node)
	{
		int best_idx = 0;
		// if the range the coords is larger than 100,best_dist should be adjusted
		double best_dist_Squa = 100.0;

		std::vector<Kd_tree_point> &pts = *m_pts;

		//First pass
		while (true)
		{
			int split_axis = cur->level % KDTREE_DIM;
			m_cmps++;

			if (cur->left == NULL)
			{
				*ret_node = cur;

				for (unsigned int i = 0; i < cur->index.size(); ++i)
				{
					m_cmps++;

					int idx = cur->index[i];

					double distSqua = DistanceSquare(query, pts[idx]);
					if (distSqua < best_dist_Squa)
					{
						best_dist_Squa = distSqua;
						best_idx = idx;
					}
				}
				break;
			}
			else if (query.coords[split_axis] < cur->split_value)
			{
				cur = cur->left;
			}
			else
			{
				cur = cur->right;
			}
		}
		*ret_index = best_idx;
		*ret_dist = best_dist_Squa;
	}

	void KDtree::SearchAtNodeRange(KDNode *cur, const Kd_tree_point &query, double range, int *ret_index, double *ret_dist)
	{
		int best_idx = 0;
		double best_dist = 100.0;

		std::vector<Kd_tree_point> &pts = *m_pts;
		std::vector<KDNode* > to_visit;

		to_visit.push_back(cur);
		while (to_visit.size() > 0)
		{
			std::vector<KDNode*> next_search;
			while (to_visit.size())
			{
				cur = to_visit.back();
				to_visit.pop_back();

				int split_axis = cur->level % KDTREE_DIM;

				if (cur->left == NULL)
				{
					for (unsigned int i = 0; i < cur->index.size(); i++) {
						m_cmps++;

						int idx = cur->index[i];
						double d = DistanceSquare(query, pts[idx]);

						if (d < best_dist) {
							best_dist = d;
							best_idx = idx;
						}
					}
				}
				else
				{
					double d = query.coords[split_axis] - cur->split_value;

					// There are 3 possible scenarios
					// The hypercircle only intersects the left region
					// The hypercircle only intersects the right region
					// The hypercricle intersects both

					m_cmps++;

					if (fabs(d) > range) {
						if (d < 0)
							next_search.push_back(cur->left);
						else
							next_search.push_back(cur->right);
					}
					else {
						next_search.push_back(cur->left);
						next_search.push_back(cur->right);
					}
				}
			}
		}

	}

	void KDtree::Search(const Kd_tree_point &query, int *ret_index, double *ret_dist)
	{
		//First pass
		//Find the first closest node, this will be the upper bound for the next searches
		std::vector<Kd_tree_point> &pts = *m_pts;
		KDNode *best_node = NULL;
		int best_idx = 0;
		double best_dist = 100.0;
		double radius = 0.0;
		m_cmps = 0;

		SearchAtNode(m_root, query, &best_idx, &best_dist, &best_node);
		radius = sqrt(best_dist);

		//Second pss
		//Find ohter possible candidates
		KDNode *cur = best_node;
		while (cur->parent != NULL)
		{
			//Go up
			KDNode *parent = cur->parent;
			int split_axis = (parent->level) % KDTREE_DIM;

			//Search the other node
			int temp_idx;
			double temp_dist = 100.0;
			KDNode *temp_node;
			KDNode *search_node = NULL;

			if (fabs(parent->split_value - query.coords[split_axis]) <= radius)
			{
				//Search opposite node
				if (parent->left != cur)
					SearchAtNodeRange(parent->left, query, radius, &temp_idx, &temp_dist);
				else
					SearchAtNodeRange(parent->right, query, radius, &temp_idx, &temp_dist);
			}

			if (temp_dist < best_dist)
			{
				best_idx = temp_idx;
				best_dist = temp_dist;
			}
			cur = parent;
		}
		*ret_index = best_idx;
		*ret_dist = best_dist;
	}

	inline double KDtree::DistanceSquare(const Kd_tree_point &a, const Kd_tree_point &b) const
	{
		double dist = 0.0;

		for (int i = 0; i < KDTREE_DIM; ++i)
		{
			double d = a.coords[i] - b.coords[i];
			dist += d * d;
		}
		return dist;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Reflection;

namespace OpenRiaServices.DomainServices.Tools
{
    /// <summary>
    /// Type used to represent an <see cref="Attribute"/> declaration and its requirements.
    /// </summary>
    internal sealed class AttributeDeclaration
    {
        private readonly Type _attributeType;
        private List<object> _constructorArguments;
        private Dictionary<string, object> _namedParameters;
        private readonly List<string> _errors;
        private List<Type> _requiredTypes;
        private List<PropertyInfo> _requiredProperties;
        private List<MethodInfo> _requiredMethods;

        /// <summary>
        /// Constructor accepting the <see cref="Attribute"/> <see cref="Type"/>.
        /// </summary>
        /// <param name="attributeType">The <see cref="Attribute"/> <see cref="Type"/> to represent. Cannot be null.</param>
        public AttributeDeclaration(Type attributeType)
        {
            if (attributeType == null)
            {
                throw new ArgumentNullException("attributeType");
            }

            this._attributeType = attributeType;
            this._errors = new List<string>();
        }

        /// <summary>
        /// Gets a boolean indicating whether or not the <see cref="AttributeDeclaration"/> has errors.
        /// </summary>
        public bool HasErrors
        {
            get
            {
                return this._errors.Count > 0;
            }
        }

        /// <summary>
        /// Gets the <see cref="Attribute"/> <see cref="Type"/>.
        /// </summary>
        public Type AttributeType
        {
            get
            {
                return this._attributeType;
            }
        }

        /// <summary>
        /// Gets a collection of constructor arguments.
        /// </summary>
        public IList<object> ConstructorArguments
        {
            get
            {
                if (this._constructorArguments == null)
                {
                    this._constructorArguments = new List<object>();
                }

                return this._constructorArguments;
            }
        }

        /// <summary>
        /// Gets a collection of error messages.
        /// </summary>
        public IList<string> Errors
        {
            get
            {
                return this._errors;
            }
        }

        /// <summary>
        /// Gets a dictionary of named parameters.
        /// </summary>
        public IDictionary<string, object> NamedParameters
        {
            get
            {
                if (this._namedParameters == null)
                {
                    this._namedParameters = new Dictionary<string, object>(StringComparer.Ordinal);
                }

                return this._namedParameters;
            }
        }

        /// <summary>
        /// Gets a collection of required shared types.
        /// </summary>
        public IList<Type> RequiredTypes
        {
            get
            {
                if (this._requiredTypes == null)
                {
                    this._requiredTypes = new List<Type>();
                }

                return this._requiredTypes;
            }
        }

        /// <summary>
        /// Gets a collection of required shared methods.
        /// </summary>
        public IList<MethodInfo> RequiredMethods
        {
            get
            {
                if (this._requiredMethods == null)
                {
                    this._requiredMethods = new List<MethodInfo>();
                }

                return this._requiredMethods;
            }
        }

        /// <summary>
        /// Gets a collection of required shared properties.
        /// </summary>
        public IList<PropertyInfo> RequiredProperties
        {
            get
            {
                if (this._requiredProperties == null)
                {
                    this._requiredProperties = new List<PropertyInfo>();
                }

                return this._requiredProperties;
            }
        }
    }
}


text:
/**
 * Provides the output records in the browser console, if the application is assembled in the development mode.
 */
export default class Debug {

  public static get LogLevels(): Array<{ [key: string]: any }> {
    if (DEV_MODE) {
      return LOG_LEVELS;
    }
  }

  public static Log(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('log', message, params); }
  }

  public static Level1(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('level1', message, params); }
  }

  public static Level2(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('level2', message, params); }
  }

  public static Level3(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('level3', message, params); }
  }

  public static Init(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('init', message, params); }
  }

  public static Init1(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('init1', message, params); }
  }

  public static Init2(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('init2', message, params); }
  }

  public static Init3(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('init3', message, params); }
  }

  public static Call(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('call', message, params); }
  }

  public static Call1(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('call1', message, params); }
  }

  public static Call2(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('call2', message, params); }
  }

  public static Call3(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('call3', message, params); }
  }

  public static Render(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('render', message, params); }
  }

  public static Render1(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('render1', message, params); }
  }

  public static Render2(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('render2', message, params); }
  }

  public static Render3(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('render3', message, params); }
  }

  public static Request(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('request', message, params); }
  }

  public static Response(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('response', message, params); }
  }

  public static Action(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('action', message, params); }
  }

  public static Reducer(message?: any, ...params: any[]): void {
    if (DEV_MODE) { Debug.Level('reducer', message, params); }
  }

  public static Error(message?: any, ...params: any[]): void {
    if (DEV_MODE) {
      console.error = Function.bind.call(console.error, console);
      console.error.apply(this, arguments);
    }
  }

  public static Warn(message?: any, ...params: any[]): void {
    Debug.Warning.apply(this, arguments);
  }

  public static Warning(message?: any, ...params: any[]): void {
    if (DEV_MODE) {
      console.warn = Function.bind.call(console.warn, console);
      console.warn.apply(this, arguments);
    }
  }

  public static Info(message?: any, ...params: any[]): void {
    if (DEV_MODE) {
      console.info = Function.bind.call(console.info, console);
      console.info.apply(this, arguments);
    }
  }

  private static Level(level: string, message?: any, ...params: any[]) {
    if (DEV_MODE) {
      if (Debug.LogLevels['all'] != undefined || Debug.LogLevels[level] != undefined) {
        console.log = Function.bind.call(console.log, console);

        let args: Array<any> = Array.prototype.slice.call(arguments);

        // remove <level>
        args.shift();

        if (args && args.length > 0 && !Debug.UserAgentIsIE()) {
          if (typeof args[0] === 'object' && args[0].constructor && args[0].constructor.name) {
            args.splice(0, 1, '%c' + level + ':%c ' + args[0].constructor.name);
          } else {
            args.splice(0, 1, '%c' + level + ':%c ' + args[0]);
          }

          if (args.length > 1 && $.isArray(args[1])) {
            // move items to external array
            let a = args[1];
            args.splice(1, 1);
            args = args.concat(a);
          }

          if ($.isArray(Debug.LogLevels[level])) {
            args.splice(1, 0, Debug.LogLevels[level][0]);

            if (Debug.LogLevels[level][1] != null && Debug.LogLevels[level][1] != '') {
              args.splice(2, 0, Debug.LogLevels[level][1]);
            } else {
              args.splice(2, 0, 'color: black;');
            }
          } else {
            args.splice(1, 0, 'background-color: #999999; color:white;');

            if (Debug.LogLevels[level] != null && Debug.LogLevels[level] != '') {
              args.splice(2, 0, Debug.LogLevels[level]);
            } else {
              args.splice(2, 0, 'color: black;');
            }
          }
        }

        // console.log(args);

        console.log.apply(this, args);
      }
    }
  }

  private static UserAgentIsIE(): boolean {
    const ua = window.navigator.userAgent;
    const msie = ua.indexOf('MSIE ');

    if (msie > 0) {
      // IE 10 or older
      return true;
    }

    const trident = ua.indexOf('Trident/');

    if (trident > 0) {
      // IE 11
      return true;
    }

    const edge = ua.indexOf('Edge/');

    if (edge > 0) {
      // Edge (IE 12+)
      return true;
    }

    // other browser
    return false;
  }

}

module.exports = Debug;


text:
package io.reneses.tela.modules.instagram.models;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * User class.
 */
@JsonIgnoreProperties(ignoreUnknown=true)
public class User {

    // Baisc user: username, picture, id and full name

    private String username, bio, website;

    @JsonProperty("id")
    private long id;

    @JsonProperty("profile_picture")
    private String picture;

    @JsonProperty("full_name")
    private String fullName;

    @JsonProperty("counts")
    private Counts counts;

    /**
     * Getter for the field username.
     *
     * @return a {@link java.lang.String} object.
     */
    public String getUsername() {
        return username;
    }

    /**
     * Setter for the field username.
     *
     * @param username a {@link java.lang.String} object.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Getter for the field bio.
     *
     * @return a {@link java.lang.String} object.
     */
    public String getBio() {
        return bio;
    }

    /**
     * Setter for the field bio.
     *
     * @param bio a {@link java.lang.String} object.
     */
    public void setBio(String bio) {
        this.bio = bio;
    }

    /**
     * Getter for the field website.
     *
     * @return a {@link java.lang.String} object.
     */
    public String getWebsite() {
        return website;
    }

    /**
     * Setter for the field website.
     *
     * @param website a {@link java.lang.String} object.
     */
    public void setWebsite(String website) {
        this.website = website;
    }

    /**
     * Getter for the field picture.
     *
     * @return a {@link java.lang.String} object.
     */
    public String getPicture() {
        return picture;
    }

    /**
     * Setter for the field picture.
     *
     * @param picture a {@link java.lang.String} object.
     */
    public void setPicture(String picture) {
        this.picture = picture;
    }

    /**
     * Getter for the field fullName.
     *
     * @return a {@link java.lang.String} object.
     */
    public String getFullName() {
        return fullName;
    }

    /**
     * Setter for the field fullName.
     *
     * @param fullName a {@link java.lang.String} object.
     */
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    /**
     * Getter for the field id.
     *
     * @return a long.
     */
    public long getId() {
        return id;
    }

    /**
     * Setter for the field id.
     *
     * @param id a long.
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * Getter for the field counts.
     *
     * @return a {@link io.reneses.tela.modules.instagram.models.Counts} object.
     */
    public Counts getCounts() {
        return counts;
    }

    /**
     * Setter for the field counts.
     *
     * @param counts a {@link io.reneses.tela.modules.instagram.models.Counts} object.
     */
    public void setCounts(Counts counts) {
        this.counts = counts;
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", bio='" + bio + '\'' +
                ", website='" + website + '\'' +
                ", id='" + id + '\'' +
                ", picture='" + picture + '\'' +
                ", fullName='" + fullName + '\'' +
                ", counts=" + counts +
                '}';
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User user = (User) o;

        return id == user.id;

    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        return (int) (id ^ (id >>> 32));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Himmelsk.Social.Api.Core.LinkedIn.UserFriendly;

namespace Himmelsk.Social.Api.Core.LinkedIn {
    public interface ILinkedInClient {
        ILinkedInCredentials GetCredentials(string consumerKey, string consumerSecret, string token, string tokenSecret);
        ILinkedInCompaniesCommands Companies { get; }
        ILinkedInPeopleCommands People { get; }
    }
}


text:
/******************************************************************************
 * @section DESCRIPTION
 *
 * Functions to support reading from netCDF field.
 *****************************************************************************/

#include <vic_driver_shared_image.h>

/******************************************************************************
 * @brief    Read double precision netCDF field from file.
 *****************************************************************************/
int
get_nc_field_double(nameid_struct *nc_nameid,
                    char          *var_name,
                    size_t        *start,
                    size_t        *count,
                    double        *var)
{
    int status;
    int var_id;

    /* get NetCDF variable */
    status = nc_inq_varid(nc_nameid->nc_id, var_name, &var_id);
    check_nc_status(status, "Error getting variable id for %s in %s", var_name,
                    nc_nameid->nc_filename);

    status = nc_get_vara_double(nc_nameid->nc_id, var_id, start, count, var);
    check_nc_status(status, "Error getting values for %s in %s", var_name,
                    nc_nameid->nc_filename);

    return status;
}

/******************************************************************************
 * @brief    Read single precision netCDF field from file.
 *****************************************************************************/
int
get_nc_field_float(nameid_struct *nc_nameid,
                   char          *var_name,
                   size_t        *start,
                   size_t        *count,
                   float         *var)
{
    int status;
    int var_id;

    /* get NetCDF variable */
    status = nc_inq_varid(nc_nameid->nc_id, var_name, &var_id);
    check_nc_status(status, "Error getting variable id for %s in %s", var_name,
                    nc_nameid->nc_filename);

    status = nc_get_vara_float(nc_nameid->nc_id, var_id, start, count, var);
    check_nc_status(status, "Error getting values for %s in %s", var_name,
                    nc_nameid->nc_filename);

    return status;
}

/******************************************************************************
 * @brief    Read integer netCDF field from file.
 *****************************************************************************/
int
get_nc_field_int(nameid_struct *nc_nameid,
                 char          *var_name,
                 size_t        *start,
                 size_t        *count,
                 int           *var)
{
    int status;
    int var_id;

    /* get NetCDF variable */
    status = nc_inq_varid(nc_nameid->nc_id, var_name, &var_id);
    check_nc_status(status, "Error getting variable id for %s in %s", var_name,
                    nc_nameid->nc_filename);

    status = nc_get_vara_int(nc_nameid->nc_id, var_id, start, count, var);
    check_nc_status(status, "Error getting values for %s in %s", var_name,
                    nc_nameid->nc_filename);

    return status;
}


text:
<?PHP

class Zend_View_Helper_TranslateLeague
{

    public function TranslateLeague(array $league)
    {
        $language = new Language;
        $language = $language->getLang();

        $name = '';

        switch ($language) {
            case 'en':
                $name = $league['name'];
                break;
            case 'fr':
                $name = empty($league['name_fr'])?: $league['name'];
                break;
            default:
                $name = $league['name'];
                break;
        }

        return ($name != '') ? $name : $league['name'];
    }

}


text:
""" Charm utilities

Api for the charmstore:
https://github.com/juju/charmstore/blob/v5/docs/API.md
"""
import os.path as path

import requests
import yaml

cs = 'https://api.jujucharms.com/v5'
CHANNELS = ['stable', 'candidate', 'beta', 'edge']

def get_file(bundle, dst):
    """ Pulls a single file from the charmstore
    """
    bundle = path.join(cs, bundle, 'archive', dst)
    req = requests.get(bundle)
    if not req.ok:
        raise Exception("Could not query file in charmstore: {}".format(req))
    return req.text

def get_bundle(bundle_name, channel='stable'):
    """ Attempts to grab the bundle.yaml

    Arguments:
    bundle_name: name of bundle (ie canonical-kubernetes)
    channel: Which channel to pull the bundle from

    Returns:
    Dictionary of bundle's yaml unless to_file is True,
    then returns the path to the downloaded bundle
    """
    bundle_channel_info = get_channel_info(bundle_name, channel)
    bundle = "{}-{}".format(bundle_name,
                            bundle_channel_info['Revision'])
    return yaml.safe_load(get_file(bundle, 'bundle.yaml'))

def get_channel_info(bundle_name, channel='stable'):
    """ Grabs the channel information for a bundle

    Usage:
    https://api.jujucharms.com/charmstore/v5/canonical-kubernetes/meta/id?channel=edge

    Arguments:
    bundle_name: name of bundle (ie canonical-kubernetes)
    channel: the release channel (ie stable, candidate, beta, edge)
    """
    query = path.join(cs, bundle_name,
                      "meta/id?channel={}".format(channel))
    req = requests.get(query)
    if not req.ok:
        raise Exception(
            "Problem getting channel information: {}".format(req)
        )
    return req.json()

def search(tags, promulgated=True):
    """ Search charmstore by tag(s)

    Usage:
    https://api.jujucharms.com/charmstore/v5/search?tags=conjure-up-openstack
    &include=id&include=extra-info/conjure-up&type=bundle

    Arguments:
    tags: single or list of tags to search for
    promulgated: search only blessed bundles
    """
    if not isinstance(tags, list):
        tags = [tags]

    tags = ["conjure-up-{}".format(t) for t in tags]
    query_str = "&tags=".join(tags)
    if promulgated:
        query_str += "&promulgated=1"
    query_str += "&include=bundle-metadata"
    query_str += "&include=id"
    query_str += "&include=extra-info/conjure-up"
    query_str += "&type=bundle"
    query = path.join(cs, 'search?tags={}'.format(query_str))
    req = requests.get(query)
    if not req.ok:
        raise Exception(
            "Problem getting tagged bundles: {}".format(req))
    return req.json()


text:
const { declareEmptyArrayVariable } = require('./utils')

const lifecyles = ['afterAll', 'beforeAll', 'afterEach', 'beforeEach']

module.exports = (programBody, t) => {
  lifecyles.forEach(lifecycle => {
    const varName = `__skpm_${lifecycle}s__`

    // var __skpm_afterAlls__ = []
    declareEmptyArrayVariable(programBody, t, varName)

    /**
     *
     * var afterAll = function (fn) => {
     *   function withLogs() {
     *     console.log = __hookedLogs
     *     return fn()
     *   }
     *   __skpm_afterAlls__.push(withLogs)
     * }
     */
    programBody.insertBefore(
      t.variableDeclaration('var', [
        t.variableDeclarator(
          t.identifier(lifecycle),
          t.functionExpression(
            null,
            [t.identifier('fn')],
            t.blockStatement([
              t.functionDeclaration(
                t.identifier('withLogs'),
                [],
                t.blockStatement([
                  t.expressionStatement(
                    t.assignmentExpression(
                      '=',
                      t.memberExpression(
                        t.identifier('console'),
                        t.identifier('log')
                      ),
                      t.identifier('__hookedLogs')
                    )
                  ),
                  t.returnStatement(t.callExpression(t.identifier('fn'), [])),
                ])
              ),
              t.expressionStatement(
                t.callExpression(
                  t.memberExpression(
                    t.identifier(varName),
                    t.identifier('push')
                  ),
                  [t.identifier('withLogs')]
                )
              ),
            ])
          )
        ),
      ])
    )
  })
}


text:
@import UIKit;

@interface MainViewController : UIViewController
@end


text:
<!DOCTYPE html>

  <title ng-bind="pageTitle + ' - App'">Loading... - App</title>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="description" content="" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,500,700,400italic" />
  <link rel="stylesheet" href="assets/angular-material.min.css" />
  <link rel="stylesheet" href="assets/css/app.css" />

    <cl-toolbar></cl-toolbar>

    <md-content flex id="content" ng-cloak ng-view></md-content>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/abstract-patterns#knotted-rope-760417" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">knotted-rope-760417</uri-title>
      <source>knotted-rope-760417</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>still life</subject>
          <subject>rope</subject>
          <subject>wood</subject>
          <subject>board</subject>
          <subject>box</subject>
          <subject>knot</subject>
          <subject>fray</subject>
          <subject>old</subject>
          <subject>faded</subject>
          <subject>knotted rope</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>505 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>668 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>1.4 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>2.4 MB</size>
                  <path>http://media.ldscdn.org/images/media-library/abstract-patterns/knotted-rope-760417-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="knotted-rope-760417" locale="eng" uri="/media-library/images/abstract-patterns#knotted-rope-760417" status="publish" site="ldsorg" source="chq" words="127" tgp="0.4441"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:12.550235-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
package org.maproulette.framework.model

import org.maproulette.framework.psql.CommonField

/**
  * @author mcuthbert
  */
object VirtualProject extends CommonField {
  val TABLE = "virtual_project_challenges"

  val FIELD_PROJECT_ID   = "project_id"
  val FIELD_CHALLENGE_ID = "challenge_id"
}


text:
class timer_sheduler
{
public:
	timer_sheduler();
	virtual ~timer_sheduler();

	void	tick();
	void	clear();
	void	start_timer(timer_helper* timer_id, const std::chrono::system_clock::time_point& begin, const std::chrono::milliseconds& interval);
	void	start_timer(timer_helper* timer_id, const std::chrono::milliseconds& begin, const std::chrono::milliseconds& interval);
	void	stop_timer(timer_helper* timer_id);
	bool	exist_timer(timer_helper* timer_id);
	std::chrono::milliseconds	min_interval();

private:
	struct timer_key
	{
		std::chrono::system_clock::time_point	triggle;
		uint64_t								unique_seq;	//±ÜÃâÏàͬµÄmap key
		timer_helper*							id;
		timer_key(const std::chrono::system_clock::time_point& triggle_, const uint64_t& unique_seq_, timer_helper* timer_id = nullptr)
		{
			triggle = triggle_;
			unique_seq = unique_seq_;
			id = timer_id;
		}
		timer_key()
		{
			unique_seq = 0;
			id = nullptr;
		}
		bool operator < (const timer_key& a) const
		{
			return triggle < a.triggle;
		}
		bool operator > (const timer_key& a) const
		{
			return triggle > a.triggle;
		}
	};
	struct timer_item
	{
		std::chrono::milliseconds				interval;
		timer_item()
		{

		}
		timer_item(const std::chrono::milliseconds& interval_)
		{
			interval = interval_;
		}
	};

	uint64_t									_unique_seq;
	std::map<timer_helper*, timer_key>			_object_list;
	std::map<timer_key, timer_item>				_timer_list;
	std::recursive_mutex						_mutex_timer;

	void	start_timer_inlock(timer_helper* timer_id, const std::chrono::system_clock::time_point& begin, const std::chrono::milliseconds& interval);
	void	stop_timer_inlock(timer_helper* timer_id);
};


text:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Location } from '../_models/index';

@Injectable()
export class LocationSevice {
    constructor(private http: Http) { }

    getAll() {
        return this.http.get('/locations').map((response: Response) => response.json());
    }

    getById(_id: string) {
        return this.http.get('/locations/' + _id).map((response: Response) => response.json());
    }

    create(location: Location) {
        return this.http.post('/locations/add', location);
    }

    update(location: Location) {
        return this.http.put('/locations/' + location._id, location);
    }

    delete(_id: string) {
        return this.http.delete('/locations/' + _id);
    }
}


text:
package com.mararok.epiccore.misc;

public interface Disposable {
  public void dispose();
}


text:
package org.apache.spark.sql.execution.datasources.v2.csv

import scala.collection.JavaConverters._

import org.apache.hadoop.fs.FileStatus

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.csv.CSVOptions
import org.apache.spark.sql.connector.write.{LogicalWriteInfo, WriteBuilder}
import org.apache.spark.sql.execution.datasources.FileFormat
import org.apache.spark.sql.execution.datasources.csv.CSVDataSource
import org.apache.spark.sql.execution.datasources.v2.FileTable
import org.apache.spark.sql.types.{AtomicType, DataType, StructType, UserDefinedType}
import org.apache.spark.sql.util.CaseInsensitiveStringMap

case class CSVTable(
    name: String,
    sparkSession: SparkSession,
    options: CaseInsensitiveStringMap,
    paths: Seq[String],
    userSpecifiedSchema: Option[StructType],
    fallbackFileFormat: Class[_ <: FileFormat])
  extends FileTable(sparkSession, options, paths, userSpecifiedSchema) {
  override def newScanBuilder(options: CaseInsensitiveStringMap): CSVScanBuilder =
    CSVScanBuilder(sparkSession, fileIndex, schema, dataSchema, options)

  override def inferSchema(files: Seq[FileStatus]): Option[StructType] = {
    val parsedOptions = new CSVOptions(
      options.asScala.toMap,
      columnPruning = sparkSession.sessionState.conf.csvColumnPruning,
      sparkSession.sessionState.conf.sessionLocalTimeZone)

    CSVDataSource(parsedOptions).inferSchema(sparkSession, files, parsedOptions)
  }

  override def newWriteBuilder(info: LogicalWriteInfo): WriteBuilder =
    new CSVWriteBuilder(paths, formatName, supportsDataType, info)

  override def supportsDataType(dataType: DataType): Boolean = dataType match {
    case _: AtomicType => true

    case udt: UserDefinedType[_] => supportsDataType(udt.sqlType)

    case _ => false
  }

  override def formatName: String = "CSV"
}


text:
package org.openecard.addon.ifd;

import iso.std.iso_iec._24727.tech.schema.EstablishChannel;
import iso.std.iso_iec._24727.tech.schema.EstablishChannelResponse;
import org.openecard.addon.AbstractFactory;
import org.openecard.addon.Context;
import org.openecard.addon.ActionInitializationException;

/**
 *
 * @author Tobias Wich <tobias.wich@ecsec.de>
 * @author Dirk Petrautzki <petrautzki@hs-coburg.de>
 */
public class IFDProtocolProxy extends AbstractFactory<IFDProtocol> implements IFDProtocol {

    private IFDProtocol c;

    public IFDProtocolProxy(String protocolClass, ClassLoader classLoader) {
	super(protocolClass, classLoader);
    }

    @Override
    public EstablishChannelResponse establish(EstablishChannel req) {
	return c.establish(req);
    }

    @Override
    public byte[] applySM(byte[] commandAPDU) {
	return c.applySM(commandAPDU);
    }

    @Override
    public byte[] removeSM(byte[] responseAPDU) {
	return c.removeSM(responseAPDU);
    }

    @Override
    public void init(Context aCtx) throws ActionInitializationException {
	c = loadInstance(aCtx, IFDProtocol.class);
    }

    @Override
    public void destroy() {
	c.destroy();
    }

}


text:
// ---------------------------------------------------------------------------------------------------------------
//
//     XNSPZ.    qXFXZ:   LPPN@:             N0kXSk5kSPkPqM:                                 .
//     @B@B@.   B@B@B@7   B@B@B             r@@@B@B@B@B@B@B                              UM@@@
//     B@B@B   G@B@B@B:  B@B@@              uBMEqB@B@@E8MMS                              B@@@J
//     BB@B@  L@B@O@@@: :@@@B    r8@B@B@Mi       @B@B5       :P@B@B@BY  L@B@BB   @B@B@u@B@B@B@B@
//     G@B@B  @@@iL@@B, @B@B.  :@B@B2j@B@@i     EB@B@.      @B@BN7@@@BX  @@B@B  @B@BO O@@B@B@B@E
//     0B@BN @B@M J@B@ rB@B7  ,@B@B. :B@@@:     B@B@B      @@@B7  B@B@S   B@B@M@B@B,   :B@B@r
//     F@B@2E@@B  UB@BvB@Bq   @B@B@B@B@BO:     r@B@@L     XB@B@B@B@BB7    vB@B@B@B     F@B@B
//     5@@B@B@B.  v@B@B@B@    B@B@O            @B@B@      M@B@B:         Z@@B@B@B@i    @B@BM
//     2@B@B@B;   vB@B@B@     2B@@@J:iPBZ     .B@@@@      :B@@@q:i2B@  7@B@BB @@@B@.  .B@B@B@B
//     uB@B@@X    r@B@B@,      rB@B@@@B@.     X@B@Br       ,M@B@B@B@; M@B@BO  i@B@B@   XB@B@BM
//
// WeText - A simple application that demonstrates the DDD, CQRS, Event Sourcing and Microservices architecture.
//
// Copyright (C) by daxnet 2016
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------------------------------------------------------------------------------------------------------

using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using WeText.Common;
using WeText.Common.Commands;
using WeText.Common.Config;
using WeText.Common.Events;
using WeText.Common.Messaging;
using WeText.Common.Querying;
using WeText.Common.Repositories;
using WeText.Common.Services;

namespace WeText.Services.Common
{
    /// <summary>
    /// Represents that the derived types are microservice registers.
    /// </summary>
    /// <typeparam name="TService">The type of the microservice.</typeparam>
    /// <seealso cref="Autofac.Module" />
    public abstract class MicroserviceRegister<TService> : Module
        where TService : Microservice
    {
        private readonly WeTextConfiguration configuration;

        /// <summary>
        /// Initializes a new instance of the <see cref="MicroserviceRegister{TService}"/> class.
        /// </summary>
        /// <param name="configuration">The instance of WeText configuration.</param>
        protected MicroserviceRegister(WeTextConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// Gets the WeText configuration specific for the current service.
        /// </summary>
        /// <value>
        /// The configuration instance.
        /// </value>
        protected ServiceElement ThisConfiguration => this.configuration.Services.GetItemByKey(typeof(TService).FullName);

        /// <summary>
        /// Resolves the instance of <see cref="IDomainRepository"/> that has been registered globally from the Autofac container.
        /// </summary>
        /// <param name="context">The <see cref="IComponentContext"/> instance that handles the Autofac registration.</param>
        /// <returns></returns>
        protected IDomainRepository ResolveGlobalDomainRepository(IComponentContext context) => context.Resolve<IDomainRepository>();

        protected ICommandSender ResolveGlobalCommandSender(IComponentContext context) => context.Resolve<ICommandSender>();

        protected IEventPublisher ResolveGlobalEventPublisher(IComponentContext context) => context.Resolve<IEventPublisher>();

        protected ITableDataGateway ResolveTableDataGateway(IComponentContext context) => context.Resolve<IEnumerable<Lazy<ITableDataGateway, NamedMetadata>>>().First(p => p.Metadata.Name == $"{ThisConfiguration.Type}.TableDataGateway").Value;

        protected virtual Func<IComponentContext, ITableDataGateway> TableDataGatewayInitializer => null;

        protected virtual IEnumerable<Func<IComponentContext, ICommandHandler>> CommandHandlersInitializer => null;

        protected virtual IEnumerable<Func<IComponentContext, IDomainEventHandler>> EventHandlersInitializer => null;

        protected abstract Func<ICommandConsumer, IEventConsumer, TService> ServiceInitializer { get; }

        /// <summary>
        /// Override to add registrations to the container.
        /// </summary>
        /// <param name="builder">The builder through which components can be
        /// registered.</param>
        /// <remarks>
        /// Note that the ContainerBuilder parameter is unique to this module.
        /// </remarks>
        protected override void Load(ContainerBuilder builder)
        {
            this.RegisterTableDataGateway(builder, this.TableDataGatewayInitializer);
            this.RegisterCommandHandlers(builder, this.CommandHandlersInitializer);
            this.RegisterEventHandlers(builder, this.EventHandlersInitializer);
            this.RegisterLocalCommandConsumer(builder);
            this.RegisterLocalEventConsumer(builder);
            this.RegisterService(builder, this.ServiceInitializer);

            base.Load(builder);
        }

        private void RegisterTableDataGateway(ContainerBuilder builder,
            Func<IComponentContext, ITableDataGateway> initializer)
        {
            if (initializer != null)
            {
                builder
                    .Register(x => initializer(x))
                    .As<ITableDataGateway>()
                    .WithMetadata<NamedMetadata>(x => x.For(y => y.Name, $"{ThisConfiguration.Type}.TableDataGateway"));
            }
        }

        private void RegisterCommandHandlers(ContainerBuilder builder,
            IEnumerable<Func<IComponentContext, ICommandHandler>> initializer)
        {
            if (initializer != null)
            {
                foreach (var value in initializer)
                {
                    builder.Register(x => value(x))
                        .Named<ICommandHandler>($"{ThisConfiguration.Type}.CommandHandlers");
                }
            }
        }

        private void RegisterEventHandlers(ContainerBuilder builder,
            IEnumerable<Func<IComponentContext, IDomainEventHandler>> initializer)
        {
            if (initializer != null)
            {
                foreach (var value in initializer)
                {
                    builder.Register(x => value(x))
                        .Named<IDomainEventHandler>($"{ThisConfiguration.Type}.EventHandlers");
                }
            }
        }

        private void RegisterLocalCommandConsumer(ContainerBuilder builder)
        {
            var commandQueueConnectionUri = ThisConfiguration?.LocalCommandQueue?.ConnectionUri;
            var commandQueueExchangeName = ThisConfiguration?.LocalCommandQueue?.ExchangeName;
            var commandQueueName = ThisConfiguration?.LocalCommandQueue?.QueueName;

            if (string.IsNullOrEmpty(commandQueueConnectionUri) ||
                string.IsNullOrEmpty(commandQueueExchangeName) ||
                string.IsNullOrEmpty(commandQueueName))
            {
                throw new ServiceRegistrationException("Either of the settings for Command Queue is empty (HostName, ExchangeName or QueueName).");
            }

            Func<IComponentContext, IEnumerable<ICommandHandler>> commandHandlersResolver = (context) =>
            {
                object result;
                if (context.TryResolveNamed($"{ThisConfiguration.Type}.CommandHandlers", typeof(IEnumerable<ICommandHandler>), out result))
                {
                    return (IEnumerable<ICommandHandler>)result;
                }
                return null;
            };

            builder
                .Register(x => new CommandConsumer(x.ResolveNamed<IMessageSubscriber>("CommandSubscriber",
                                new NamedParameter("uri", commandQueueConnectionUri),
                                new NamedParameter("exchangeName", commandQueueExchangeName),
                                new NamedParameter("queueName", commandQueueName)
                            ),
                        commandHandlersResolver(x)))
                .Named<ICommandConsumer>($"{ThisConfiguration.Type}.LocalCommandConsumer");
        }

        private void RegisterLocalEventConsumer(ContainerBuilder builder)
        {
            var eventQueueConnectionUri = ThisConfiguration?.LocalEventQueue?.ConnectionUri;
            var eventQueueExchangeName = ThisConfiguration?.LocalEventQueue?.ExchangeName;
            var eventQueueName = ThisConfiguration?.LocalEventQueue?.QueueName;

            if (string.IsNullOrEmpty(eventQueueConnectionUri) ||
                string.IsNullOrEmpty(eventQueueExchangeName) ||
                string.IsNullOrEmpty(eventQueueName))
            {
                throw new ServiceRegistrationException("Either of the settings for Command Queue is empty (HostName, ExchangeName or QueueName).");
            }

            Func<IComponentContext, IEnumerable<IDomainEventHandler>> eventHandlersResolver = (context) =>
            {
                object result;
                if (context.TryResolveNamed($"{ThisConfiguration.Type}.EventHandlers", typeof(IEnumerable<IDomainEventHandler>), out result))
                {
                    return (IEnumerable<IDomainEventHandler>)result;
                }
                return null;
            };

            builder
                .Register(x => new EventConsumer(x.ResolveNamed<IMessageSubscriber>("EventSubscriber",
                                new NamedParameter("uri", eventQueueConnectionUri),
                                new NamedParameter("exchangeName", eventQueueExchangeName),
                                new NamedParameter("queueName", eventQueueName)
                            ),
                            eventHandlersResolver(x)))
                .Named<IEventConsumer>($"{ThisConfiguration.Type}.LocalEventConsumer");
        }

        private void RegisterService(ContainerBuilder builder,
            Func<ICommandConsumer, IEventConsumer, TService> serviceInitializer)
        {
            Func<IComponentContext, ICommandConsumer> localCommandConsumerResolver = context =>
                context.ResolveNamed<ICommandConsumer>($"{ThisConfiguration.Type}.LocalCommandConsumer");
            Func<IComponentContext, IEventConsumer> localEventConsumerResolver = context =>
                context.ResolveNamed<IEventConsumer>($"{ThisConfiguration.Type}.LocalEventConsumer");

            builder.Register(x => serviceInitializer(localCommandConsumerResolver(x), localEventConsumerResolver(x)))
                .As<IService>()
                .SingleInstance();
        }
    }
}


text:
const { resolveCwd } = require("./lib/utils");
const config = require(resolveCwd(".dioconfig/config"));

module.exports = {
  dev: {
    env: { NODE_ENV: '"development"' },
    port: config.devPort,
    autoOpenBrowser: true,
    assetsSubDirectory: "static",
    assetsPublicPath: "/",
    proxyTable: config.devProxy
  },
  build: {
    env: { NODE_ENV: '"production"' },
    index: resolveCwd("./dist/index.html"),
    assetsRoot: resolveCwd("./dist"),
    assetsSubDirectory: "static",
    assetsPublicPath: "",
    productionSourceMap: config.productionSourceMap
  }
};


text:
package org.spongepowered.common.accessor.world.level.block;

import net.minecraft.world.level.block.AbstractSkullBlock;
import net.minecraft.world.level.block.SkullBlock;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;

@Mixin(AbstractSkullBlock.class)
public interface AbstractSkullBlockAccessor {

    @Accessor("type") SkullBlock.Type accessor$type();

}


text:
package com.gyf.ec.controller;

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gohuinuo.common.base.BaseController;
import com.gohuinuo.web.sys.utils.SysUserUtils;
import com.gyf.ec.model.EcTaskType;
import com.gyf.ec.service.EcTaskTypeService;

/**
 * 任务类型管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("ecTaskType")
public class EcTaskTypeController extends BaseController {

	@Resource
	private EcTaskTypeService service;

	/**
	 * 跳转到模块页面
	* @param model
	* @return 模块html
	 */
	@RequestMapping
	public String toEcTaskType(Model model){
		return "ec/taskType/ecTaskType";
	}

	/**
	 * 分页显示区域table
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public String list(@RequestParam Map<String, Object> params, Model model) {
		PageHelper.startPage(params);
		long userId = SysUserUtils.getCacheLoginUser().getId();
		params.put("userId", userId);
		List<EcTaskType> list = service.findTaskTypeList(params);
		model.addAttribute("page", new PageInfo<EcTaskType>(list));
		return "ec/taskType/ecTaskType-list";
	}

	/**
	 * 弹窗
	 *
	 * @param id
	 * @param skuId
	 *            skuId
	 * @param mode
	 *            模式(add,edit,detail)
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{mode}/showlayer", method = RequestMethod.POST)
	public String showLayer(Long id, Long skuId,
			@PathVariable("mode") String mode, Model model) {
		EcTaskType ecTaskType = null;
		String url = "";
		if (StringUtils.equalsIgnoreCase(mode, "add")) {
			url =  "ec/taskType/ecTaskType-save";
		} else if (StringUtils.equalsIgnoreCase(mode, "edit")) {
			ecTaskType = service.findTaskType(id);
			url =  "ec/taskType/ecTaskType-edit";
		} else if (StringUtils.equalsIgnoreCase(mode, "detail")) {
			ecTaskType = service.findTaskType(id);
			url =  "ec/taskType/ecTaskType-detail";
		}
		model.addAttribute("ecTaskType", ecTaskType);
		return url;
	}

	/**
	 * 添加或更新
	* @param params
	* @return
	 */
	@RequestMapping(value="save",method=RequestMethod.POST)
	public @ResponseBody Integer save(@ModelAttribute EcTaskType ecTaskType){
		return service.saveEcTaskType(ecTaskType);
	}

	/**
	 * 删除
	* @param
	* @return
	 */
	@RequestMapping(value="delete",method=RequestMethod.POST)
	public @ResponseBody Integer del(Long id){
		return service.deleteEcTaskType(id);
	}

}


text:
package aima.test.core.unit.learning.learners;

import java.util.ArrayList;

import org.junit.Assert;
import org.junit.Test;

import aima.core.learning.framework.DataSet;
import aima.core.learning.framework.DataSetFactory;
import aima.core.learning.inductive.DLTest;
import aima.core.learning.inductive.DLTestFactory;
import aima.core.learning.learners.CurrentBestLearner;
import aima.core.learning.learners.DecisionListLearner;
import aima.core.learning.learners.DecisionTreeLearner;
import aima.core.learning.learners.MajorityLearner;
import aima.test.core.unit.learning.framework.MockDataSetSpecification;
import aima.test.core.unit.learning.inductive.MockDLTestFactory;

/**
 * @author Ravi Mohan
 *
 */
public class LearnerTest {

	@Test
	public void testMajorityLearner() throws Exception {
		MajorityLearner learner = new MajorityLearner();
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		learner.train(ds);
		int[] result = learner.test(ds);
		Assert.assertEquals(6, result[0]);
		Assert.assertEquals(6, result[1]);
	}

	@Test
	public void testDefaultUsedWhenTrainingDataSetHasNoExamples()
			throws Exception {
		// tests RecursionBaseCase#1
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DecisionTreeLearner learner = new DecisionTreeLearner();

		DataSet ds2 = ds.emptyDataSet();
		Assert.assertEquals(0, ds2.size());

		learner.train(ds2);
		Assert.assertEquals("Unable To Classify",
				learner.predict(ds.getExample(0)));
	}

	@Test
	public void testClassificationReturnedWhenAllExamplesHaveTheSameClassification()
			throws Exception {
		// tests RecursionBaseCase#2
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DecisionTreeLearner learner = new DecisionTreeLearner();

		DataSet ds2 = ds.emptyDataSet();

		// all 3 examples have the same classification (willWait = yes)
		ds2.add(ds.getExample(0));
		ds2.add(ds.getExample(2));
		ds2.add(ds.getExample(3));

		learner.train(ds2);
		Assert.assertEquals("Yes", learner.predict(ds.getExample(0)));
	}

	@Test
	public void testMajorityReturnedWhenAttributesToExamineIsEmpty()
			throws Exception {
		// tests RecursionBaseCase#2
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DecisionTreeLearner learner = new DecisionTreeLearner();

		DataSet ds2 = ds.emptyDataSet();

		// 3 examples have classification = "yes" and one ,"no"
		ds2.add(ds.getExample(0));
		ds2.add(ds.getExample(1));// "no"
		ds2.add(ds.getExample(2));
		ds2.add(ds.getExample(3));
		ds2.setSpecification(new MockDataSetSpecification("will_wait"));

		learner.train(ds2);
		Assert.assertEquals("Yes", learner.predict(ds.getExample(1)));
	}

	@Test
	public void testInducedTreeClassifiesDataSetCorrectly() throws Exception {
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DecisionTreeLearner learner = new DecisionTreeLearner();
		learner.train(ds);
		int[] result = learner.test(ds);
		Assert.assertEquals(12, result[0]);
		Assert.assertEquals(0, result[1]);
	}

	@Test
	public void testDecisionListLearnerReturnsNegativeDLWhenDataSetEmpty()
			throws Exception {
		// tests first base case of DL Learner
		DecisionListLearner learner = new DecisionListLearner("Yes", "No",
				new MockDLTestFactory(null));
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DataSet empty = ds.emptyDataSet();
		learner.train(empty);
		Assert.assertEquals("No", learner.predict(ds.getExample(0)));
		Assert.assertEquals("No", learner.predict(ds.getExample(1)));
		Assert.assertEquals("No", learner.predict(ds.getExample(2)));
	}

	@Test
	public void testDecisionListLearnerReturnsFailureWhenTestsEmpty()
			throws Exception {
		// tests second base case of DL Learner
		DecisionListLearner learner = new DecisionListLearner("Yes", "No",
				new MockDLTestFactory(new ArrayList<DLTest>()));
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		learner.train(ds);
		Assert.assertEquals(DecisionListLearner.FAILURE,
				learner.predict(ds.getExample(0)));
	}

	@Test
	public void testDecisionListTestRunOnRestaurantDataSet() throws Exception {
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		DecisionListLearner learner = new DecisionListLearner("Yes", "No",
				new DLTestFactory());
		learner.train(ds);

		int[] result = learner.test(ds);
		Assert.assertEquals(12, result[0]);
		Assert.assertEquals(0, result[1]);
	}

	@Test
	public void testCurrentBestLearnerOnRestaurantDataSet() throws Exception {
		DataSet ds = DataSetFactory.getRestaurantDataSet();
		CurrentBestLearner learner = new CurrentBestLearner("Yes");
		learner.train(ds);

		int[] result = learner.test(ds);
		Assert.assertEquals(12, result[0]);
		Assert.assertEquals(0, result[1]);
	}
}