text:
using System.Linq;
using Assets.Characters.AiScripts;
using Assets.Characters.AiScripts.States;
using Assets.Core.Configuration;
using Assets.Core.InteractableObjects;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Assets.Characters.Player.Scripts
{
    public class PlayerMovement : MonoBehaviour
    {
        private NavMeshAgent _agent;
        private AiMovement _ai;

        public GameObject MovementLight;
        private GameObject movementLight;

      //  private UiController _uiControl;
		private float _touchCounter = 0;
		public bool _tap = false;			// detecting tap
		private bool _canMove = false;		// allowing player to move
        // Use this for initialization
        void Start ()
        {
            _agent = GetComponent<NavMeshAgent>();
            _ai = GetComponent<AiMovement>();
        //    _uiControl = GameObject.FindGameObjectWithTag(Constants.Tags.GameUI).GetComponent<UiController>();

           movementLight = (GameObject)Instantiate(MovementLight, Vector3.zero, Quaternion.identity);
        }

        // Update is called once per frame
        void Update ()
        {

#if UNITY_EDITOR
            if (Input.GetMouseButtonUp(0))
			{
				if(!EventSystem.current.IsPointerOverGameObject(-1))
                	_canMove = true;
            }
#endif
            if (Input.touchCount == 1 )
            {
				if (Input.GetTouch(0).phase == TouchPhase.Began)
					if(!EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
						_tap = true;

                if (Input.GetTouch(0).phase == TouchPhase.Moved)
                    _tap = false;

                if (Input.GetTouch(0).phase == TouchPhase.Ended)
                {
                    if (_tap)
                        _canMove = true;
                }
            }

        }

		void LateUpdate()
		{
			if (!_canMove) return;

			_tap = false;
			_canMove = false;
			// if (!Input.GetMouseButtonUp(0)) return;

			var ts = Input.touches;

		//	Debug.Log ("touches " + EventSystem.current.IsPointerOverGameObject());

			if (ts.Length > 1 || (ts.Length > 0 && EventSystem.current.IsPointerOverGameObject(ts[0].fingerId))
			    || EventSystem.current.IsPointerOverGameObject())	return;

			// Find all object in ray, and sort them by distance to object.
			var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit[] hits = Physics.RaycastAll(ray, 100);
			hits = hits.OrderBy(h => h.distance).ToArray();

			var state = hits.Select(hit => GameObjectToState(hit.transform.gameObject, hit))
				.FirstOrDefault(s => s != null);

			if (state != null)
				_ai.AssignNewState(state);
		}

        IState GameObjectToState(GameObject other, RaycastHit hit)
        {
            if (other.GetComponent<IInteractable>() != null)
            {
                return new InteractWithNearestState(_agent, other);
            }
            if (other.GetComponent<ICollectable>() != null)
            {
                return new PickupItemState(_agent, hit.transform.gameObject);
            }
            if(other.tag == Constants.Tags.Floor)
            {
                movementLight.transform.position = hit.point;
                movementLight.GetComponent<Animator>().SetTrigger("Light");
                return new GoSomewhereAndWaitState(_agent, hit.point);
            }
            return null;
        }
    }
}


text:
% Section 11.8.4: Network rate optimization
% Boyd & Vandenberghe "Convex Optimization"
% Argyrios Zymnis - 05/03/08
%
% We consider a network with n flows and L links. Each flow i,
% moves along a fixed predetermined path (i.e. a subset of the links)
% and has an associated rate x_i. Each link j has an associated capacity
% c_j. The total rate of all flows travelling along a link cannot exceed
% the link capacity. We can describe these link capacity limits using the
% flow-link incidence matrix A \in \reals^{L \times n}, where
% A_{ij} = 1, if flow j passes through link i and 0 otherwise.
% The link capacity constraints can be expressed as A*x <= c
% In the network rate problem the variables are the flow rates x. The
% objective is to choose the flow rates to maximize a separate utility
% function U, given by
%           U(x) = U_1(x_1)+U_2(x_2)+...+U_n(x_n)
% The network rate optimization problem is then
%           maximize    U(x)
%           subject to  A*x <= c
% Here we use U_i(x_i) = log x_i for all i

% Input data
rand('state',1)
L = 20;
n = 10;
k = 7; %average links per flow
A = double(rand(L,n) <= k/L);
c = 0.9*rand(L,1)+0.1;

% Solve network rate problem
cvx_begin
    variable x(n);
    maximize(sum(log(x)))
    subject to
        A*x <= c
cvx_end
primal_obj = cvx_optval;

% Solve dual problem to obtain link prices
cvx_begin
    variable lambda(L);
    minimize(c'*lambda-sum(log(A'*lambda))-n)
    subject to
        lambda >= 0
cvx_end
dual_obj = cvx_optval;

redpajama_set_name: RedPajamaGithub


text:
goog.provide('shaka.ui.SmallPlayButton');

goog.require('shaka.ui.Controls');
goog.require('shaka.ui.Enums');
goog.require('shaka.ui.Locales');
goog.require('shaka.ui.PlayButton');

/**
 * @extends {shaka.ui.PlayButton}
 * @final
 * @export
 */
shaka.ui.SmallPlayButton = class extends shaka.ui.PlayButton {
  /**
   * @param {!HTMLElement} parent
   * @param {!shaka.ui.Controls} controls
   */
  constructor(parent, controls) {
    super(parent, controls);

    this.button.classList.add('shaka-small-play-button');
    this.button.classList.add('material-icons-round');
    this.button.classList.add('shaka-tooltip');

    this.updateIcon();
    this.updateAriaLabel();
  }

  /** @override */
  updateIcon() {
    const Icons = shaka.ui.Enums.MaterialDesignIcons;
    if (this.video.ended) {
      this.button.textContent = Icons.REPLAY;
    } else {
      this.button.textContent = this.isPaused() ? Icons.PLAY : Icons.PAUSE;
    }
  }

  /** @override */
  updateAriaLabel() {
    const LocIds = shaka.ui.Locales.Ids;
    if (this.video.ended) {
      this.button.ariaLabel = this.localization.resolve(LocIds.REPLAY);
    } else {
      const label = this.isPaused() ? LocIds.PLAY : LocIds.PAUSE;
      this.button.ariaLabel = this.localization.resolve(label);
    }
  }
};

/**
 * @implements {shaka.extern.IUIElement.Factory}
 * @final
 */
shaka.ui.SmallPlayButton.Factory = class {
  /** @override */
  create(rootElement, controls) {
    return new shaka.ui.SmallPlayButton(rootElement, controls);
  }
};

shaka.ui.Controls.registerElement(
    'play_pause', new shaka.ui.SmallPlayButton.Factory());


text:
package com.facebook.swift.codec;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Marks a field or method as the field containing the state of an union.
 */
@Documented
@Retention(RUNTIME)
@Target({METHOD, FIELD})
public @interface ThriftUnionId
{
}


text:
package kafka.security.authorizer

import kafka.utils.Json
import org.apache.kafka.common.acl.{AccessControlEntry, AclOperation, AclPermissionType}
import org.apache.kafka.common.acl.AclOperation.{READ, WRITE, CREATE, DESCRIBE, DELETE, ALTER, DESCRIBE_CONFIGS, ALTER_CONFIGS, CLUSTER_ACTION, IDEMPOTENT_WRITE}
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.resource.{ResourcePattern, ResourceType}
import org.apache.kafka.common.security.auth.KafkaPrincipal
import org.apache.kafka.common.utils.SecurityUtils

import scala.jdk.CollectionConverters._

object AclEntry {
  val WildcardPrincipal: KafkaPrincipal = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "*")
  val WildcardPrincipalString: String = WildcardPrincipal.toString
  val WildcardHost: String = "*"
  val WildcardResource: String = ResourcePattern.WILDCARD_RESOURCE

  val ResourceSeparator = ":"
  val ResourceTypes: Set[ResourceType] = ResourceType.values.toSet
    .filterNot(t => t == ResourceType.UNKNOWN || t == ResourceType.ANY)
  val AclOperations: Set[AclOperation] = AclOperation.values.toSet
    .filterNot(t => t == AclOperation.UNKNOWN || t == AclOperation.ANY)

  val PrincipalKey = "principal"
  val PermissionTypeKey = "permissionType"
  val OperationKey = "operation"
  val HostsKey = "host"
  val VersionKey = "version"
  val CurrentVersion = 1
  val AclsKey = "acls"

  def apply(principal: KafkaPrincipal,
            permissionType: AclPermissionType,
            host: String,
            operation: AclOperation): AclEntry = {
    new AclEntry(new AccessControlEntry(if (principal == null) null else principal.toString,
      host, operation, permissionType))
  }

  /**
   * Parse JSON representation of ACLs
   * @param bytes of acls json string
   *
   * <p>
      {
        "version": 1,
        "acls": [
          {
            "host":"host1",
            "permissionType": "Deny",
            "operation": "Read",
            "principal": "User:alice"
          }
        ]
      }
   * </p>
   *
   * @return set of AclEntry objects from the JSON string
   */
  def fromBytes(bytes: Array[Byte]): Set[AclEntry] = {
    if (bytes == null || bytes.isEmpty)
      return collection.immutable.Set.empty[AclEntry]

    Json.parseBytes(bytes).map(_.asJsonObject).map { js =>
      //the acl json version.
      require(js(VersionKey).to[Int] == CurrentVersion)
      js(AclsKey).asJsonArray.iterator.map(_.asJsonObject).map { itemJs =>
        val principal = SecurityUtils.parseKafkaPrincipal(itemJs(PrincipalKey).to[String])
        val permissionType = SecurityUtils.permissionType(itemJs(PermissionTypeKey).to[String])
        val host = itemJs(HostsKey).to[String]
        val operation = SecurityUtils.operation(itemJs(OperationKey).to[String])
        AclEntry(principal, permissionType, host, operation)
      }.toSet
    }.getOrElse(Set.empty)
  }

  def toJsonCompatibleMap(acls: Set[AclEntry]): Map[String, Any] = {
    Map(AclEntry.VersionKey -> AclEntry.CurrentVersion, AclEntry.AclsKey -> acls.map(acl => acl.toMap.asJava).toList.asJava)
  }

  def supportedOperations(resourceType: ResourceType): Set[AclOperation] = {
    resourceType match {
      case ResourceType.TOPIC => Set(READ, WRITE, CREATE, DESCRIBE, DELETE, ALTER, DESCRIBE_CONFIGS, ALTER_CONFIGS)
      case ResourceType.GROUP => Set(READ, DESCRIBE, DELETE)
      case ResourceType.CLUSTER => Set(CREATE, CLUSTER_ACTION, DESCRIBE_CONFIGS, ALTER_CONFIGS, IDEMPOTENT_WRITE, ALTER, DESCRIBE)
      case ResourceType.TRANSACTIONAL_ID => Set(DESCRIBE, WRITE)
      case ResourceType.DELEGATION_TOKEN => Set(DESCRIBE)
      case _ => throw new IllegalArgumentException("Not a concrete resource type")
    }
  }

  def authorizationError(resourceType: ResourceType): Errors = {
    resourceType match {
      case ResourceType.TOPIC => Errors.TOPIC_AUTHORIZATION_FAILED
      case ResourceType.GROUP => Errors.GROUP_AUTHORIZATION_FAILED
      case ResourceType.CLUSTER => Errors.CLUSTER_AUTHORIZATION_FAILED
      case ResourceType.TRANSACTIONAL_ID => Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED
      case ResourceType.DELEGATION_TOKEN => Errors.DELEGATION_TOKEN_AUTHORIZATION_FAILED
      case _ => throw new IllegalArgumentException("Authorization error type not known")
    }
  }
}

class AclEntry(val ace: AccessControlEntry)
  extends AccessControlEntry(ace.principal, ace.host, ace.operation, ace.permissionType) {

  val kafkaPrincipal: KafkaPrincipal = if (principal == null)
    null
  else
    SecurityUtils.parseKafkaPrincipal(principal)

  def toMap: Map[String, Any] = {
    Map(AclEntry.PrincipalKey -> principal,
      AclEntry.PermissionTypeKey -> SecurityUtils.permissionTypeName(permissionType),
      AclEntry.OperationKey -> SecurityUtils.operationName(operation),
      AclEntry.HostsKey -> host)
  }

  override def hashCode(): Int = ace.hashCode()

  override def equals(o: scala.Any): Boolean = super.equals(o) // to keep spotbugs happy

  override def toString: String = {
    "%s has %s permission for operations: %s from hosts: %s".format(principal, permissionType.name, operation, host)
  }

}


text:
package com.example.android.kvs;

import com.rejasupotaro.android.kvs.annotations.Key;
import com.rejasupotaro.android.kvs.annotations.Table;

import java.util.Set;

@Table(name = "example", builder = ExamplePrefsBuilder.class)
public abstract class ExamplePrefsSchema {
    @Key("user_id")
    long userId;
    @Key("user_name")
    String userName;
    @Key("user_age")
    int userAge;
    @Key("guest_flag")
    boolean guestFlag;
    @Key("search_history")
    Set<String> searchHistory;
}


text:
#ifndef DRON_PLAYER_H_
#define DRON_PLAYER_H_

#include "../Vector2D.h"

#include "PlayerController.h"
#include "Item.h"

#include <SFML/Graphics/Color.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/Rect.hpp>

#include <string>
#include <list>
#include <memory>
#include <vector>

namespace Dron
{

class Player;

typedef std::shared_ptr<Player> PlayerPtr;
typedef std::shared_ptr<const Player> ConstPlayerPtr;
typedef std::vector<PlayerPtr> PlayerPtrs;
typedef std::vector<ConstPlayerPtr> ConstPlayerPtrs;

/*
 * A player inside the tron world
 *
 * The first position in the list of elements marks the head.
 */
class Player
{
public:
	typedef Vector2D<int> Position;
	typedef Vector2D<int> Vector;
	typedef sf::Rect<int> Rect;
	typedef std::list<Position> Positions;

	Player(const std::string& name, const Position& initialPosition, const sf::Color& color,
			const PlayerControllerPtr& controllerPtr, ItemPtrs::size_type maxItems, Positions::size_type minLength = 8);

	// Forward keyboard inputs to controller.
	void PushKeyInput(const sf::Key::Code& keyCode);

	// Forward joypad inputs to controller.
	void PushJoyInput(const sf::Event::JoyMoveEvent& jobMoveEvent);

	// Let the controller tell us what to do next.
	void CalculateNextStep(const World& world, ConstPlayerPtrs otherPlayerPtrs);
	bool RemovePosition(const Position& pos, World& world);
	void ExecuteNextStep(const World& world);

	// returns true if item is collected, false if not
	bool HitItem(const Position& pos, ItemPtr itemPtr, World& world);
	void HitWall(const Position& pos, World& world);
	void HitSelf(const Position& pos, World& world);
	void HitOtherPlayer(const Position& pos, Player& other, World& world);

	// Reduze tail length every nth step
	void ShrinkTail(std::size_t n = 2);
	bool IsAlive() const
	{
		return alive_;
	}

	// Where will his head be in the next time step in a given workd?
	const Position NextPosition(const World& world) const;

	// The head's position.
	const Position& GetFrontPosition() const;
	const Position& GetBackPosition() const;
	const sf::Color& GetColor() const
	{
		return color_;
	}
	const Positions& GetPositions() const
	{
		return positions_;
	}
	void SetPositions(const Positions& positions)
	{
		positions_ = positions;
	}
	const ItemPtrs& GetItemPtrs() const
	{
		return itemPtrs_;
	}

	const PlayerControllerPtr GetControllerPtr() const
	{
		return controllerPtr_;
	}
	Vector GetLastDirection() const
	{
		return lastDirection_;
	}
	void ShrinkToMinLength();
	const std::string& GetName() const
	{
		return name_;
	}
protected:
	void Die(const Position& position, World& world);
	std::string name_;
	Positions positions_;
	sf::Color color_;
	PlayerControllerPtr controllerPtr_;
	Vector lastDirection_;
	bool alive_;
	ItemPtrs::size_type maxItems_;
	Positions::size_type minLength_;
	ItemPtrs itemPtrs_;
	int shrinkTailStepNum_;
};

} /* namespace Dron */

#endif /* DRON_PLAYER_H_ */


text:
require "spec_helper"

describe BazaModels::Validators::LengthValidator do
  include DatabaseHelper

  it "validates minimum length" do
    user = User.new(email: "a")

    expect(user.valid?).to be false
    expect(user.errors.full_messages).to include "Email is too short"
  end

  it "validates maximum length" do
    user = User.new(email: "a" * 101)

    expect(user.valid?).to be false
    expect(user.errors.full_messages).to include "Email is too long"
  end
end


text:
using System;
using System.Web.UI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;

namespace Nucleo.Web.Templates
{
	[TestClass]
	public class ControlElementTemplateTest
	{
		#region " Tests "

		[TestMethod]
		public void CreatingEmptyTemplateAssignsNull()
		{
			//Arrange

			//Act
			var template = new ControlElementTemplate();

			//Assert
			Assert.IsNull(template.Template);
		}

		[TestMethod]
		public void CreatingTemplateAssignsToTemplateProperty()
		{
			//Arrange
			var temp = Isolate.Fake.Instance<ITemplate>();

			//Act
			var template = new ControlElementTemplate(temp);

			//Assert
			Assert.IsNotNull(template.Template);
		}

		[TestMethod]
		public void GettingTemplateReturnsWHenTemplateAssigned()
		{
			//Arrange
			var temp = Isolate.Fake.Instance<ITemplate>();

			//Act
			var template = new ControlElementTemplate();
			template.Template = temp;

			//Assert
			Assert.IsNotNull(template.GetTemplate());
		}

		#endregion
	}
}


text:
// @flow
/* global SETTINGS:false */
import { assert } from "chai"
import sinon from "sinon"
import R from "ramda"

import { actions } from "../../actions"
import { SET_BANNER_MESSAGE } from "../../actions/ui"
import { FLOW_REGISTER, STATE_REGISTER_CONFIRM_SENT } from "../../reducers/auth"
import IntegrationTestHelper from "../../util/integration_test_helper"
import ConnectedRegisterPage, { RegisterPage, FORM_KEY } from "./RegisterPage"
import { FRONTPAGE_URL, LOGIN_URL } from "../../lib/url"

const email = "test@example.com"
const recaptcha = "recaptcha_response"

const DEFAULT_STATE = {
  auth: {
    data:       {},
    processing: false
  },
  forms: {
    [FORM_KEY]: {
      value: {
        email,
        recaptcha
      },
      errors: {}
    }
  }
}
describe("RegisterPage", () => {
  let helper, renderPage

  beforeEach(() => {
    helper = new IntegrationTestHelper()
    helper.postEmailRegisterStub.returns(
      Promise.resolve({
        flow:  FLOW_REGISTER,
        state: STATE_REGISTER_CONFIRM_SENT,
        email
      })
    )
    renderPage = helper.configureHOCRenderer(
      ConnectedRegisterPage,
      RegisterPage,
      DEFAULT_STATE,
      { location: {} }
    )
  })

  afterEach(() => {
    helper.cleanup()
  })

  it("should render an initial form", async () => {
    const { inner } = await renderPage({
      auth: {
        data: {
          errors: ["error"]
        }
      }
    })

    const form = inner.find("AuthEmailForm")
    assert.ok(form.exists())
    assert.equal(form.props().formError, "error")
  })

  it("should render an ExternalLogins component", async () => {
    const { inner } = await renderPage({
      auth: {
        data: {
          errors: ["error"]
        }
      }
    })

    const link = inner.find("ExternalLogins")
    assert.ok(link.exists())
  })

  it("should contain a link to the login page", async () => {
    const { inner } = await renderPage()
    const link = inner
      .find("Link")
      .findWhere(c => c.prop("to") === `${LOGIN_URL}?next=%2F`)
    assert.ok(link.exists())
  })

  it("form onSubmit prop calls api correctly", async () => {
    const { inner, store } = await renderPage()

    const { onSubmit } = inner.find("AuthEmailForm").props()

    await onSubmit()

    const dispatchedActions = store.getActions()

    assert.isAtLeast(dispatchedActions.length, 3)
    assert.equal(
      dispatchedActions[2].type,
      actions.auth.registerEmail.requestType
    )
    sinon.assert.calledOnce(helper.postEmailRegisterStub)
    sinon.assert.calledWith(
      helper.postEmailRegisterStub,
      FLOW_REGISTER,
      "test@example.com"
    )
  })

  it("form onSubmitResult prop redirects and sets a banner message", async () => {
    const { inner, store } = await renderPage()

    const { onSubmitResult } = inner.props()

    onSubmitResult({
      state:  STATE_REGISTER_CONFIRM_SENT,
      flow:   "register",
      email:  email,
      errors: []
    })

    const historyEntries = helper.browserHistory.entries
    assert.equal(historyEntries.length, 2)
    assert.equal(R.last(historyEntries).pathname, FRONTPAGE_URL)
    const dispatchedActions = store.getActions()
    assert.equal(R.last(dispatchedActions).type, SET_BANNER_MESSAGE)
  })
})


text:
/*	Id: racoonctl.c,v 1.11 2006/04/06 17:06:25 manubsd Exp */

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * Copyright (C) 2008 Timo Teras.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
	setenv("POSIXLY_CORRECT", "1", 0);
#endif
	while ((c = getopt(ac, av, "lds:")) != -1) {
		switch(c) {
		case 'l':
			long_format++;


text:
var dataUri = require('../lib/dataUri.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['dataUri'] = {
  setUp: function(done) {
    // setup here
    done();
  }
};


text:
package com.ocdsoft.bacta.swg.server.object.sui;

public class SuiEventType {
    public static final byte none = 0x0;
    public static final byte onButton = 0x1;
    public static final byte onCheckbox = 0x2;
    public static final byte onEnabledChanged = 0x3;
    public static final byte onGenericSelection = 0x4;
    public static final byte onSliderbar = 0x5;
    public static final byte onTabbedPane = 0x6;
    public static final byte onTextbox = 0x7;
    public static final byte onVisibilityChanged = 0x8;
    public static final byte onClosedOk = 0x9;
    public static final byte onClosedCancel = 0xA;
    public static final byte numEventTypes = 0xB;
}


text:
package org.hcjf.layers.query;

import java.util.Map;

/**
 * Evaluate if the field's value of the instance is greater than the
 * parameter value.
 * @author javaito
 */
public class GreaterThan extends FieldEvaluator {

    private final boolean orEquals;

    protected GreaterThan(Query.QueryParameter parameter, Object value, boolean orEquals) {
        super(parameter, value);
        this.orEquals = orEquals;
    }

    protected GreaterThan(String fieldName, Object value, boolean orEquals) {
        this(new Query.QueryField(fieldName), value, orEquals);
    }

    public GreaterThan(Query.QueryParameter parameter, Object value) {
        this(parameter, value, false);
    }

    public GreaterThan(String fieldName, Object value) {
        this(new Query.QueryField(fieldName), value, false);
    }

    /**
     * Evaluate if the field's value of the instance is greater than the
     * parameter value.
     * @param object Object of the data collection.
     * @param consumer Data source consumer
     * @param valuesMap Values
     * @return True if he field's value is greater than the parameter value and
     * false in the other ways.
     * @throws IllegalArgumentException
     * If the introspection accessor fail: 'Greater than evaluator fail'
     * If the parameter value or field's value are not comparable: 'Unsupported evaluator type'
     * If the parameter value and field's value are incompatible: 'Incompatible types between value and field's value'
     */
    @Override
    public boolean evaluate(Object object, Query.Consumer consumer, Map<Evaluator, Object> valuesMap) {
        boolean result;
        try {
            Object value = valuesMap.get(this);
            if(value instanceof Query.QueryParameter) {
                value = consumer.get(object, ((Query.QueryParameter)value));
            }
            Object fieldValue = consumer.get(object, getQueryParameter());

            if(fieldValue instanceof Number && value instanceof Number) {
                if(fieldValue instanceof Double || fieldValue instanceof Float ||
                        value instanceof Double || value instanceof Float) {
                    fieldValue = new Double(((Number)fieldValue).doubleValue());
                    value = new Double(((Number)value).doubleValue());
                } else {
                    fieldValue = new Long(((Number)fieldValue).longValue());
                    value = new Long(((Number)value).longValue());
                }
            }

            if(Comparable.class.isAssignableFrom(value.getClass()) &&
                    Comparable.class.isAssignableFrom(fieldValue.getClass())) {
                if(fieldValue.getClass().isAssignableFrom(value.getClass()) ||
                        value.getClass().isAssignableFrom(fieldValue.getClass())) {
                    if(orEquals) {
                        result = ((Comparable)fieldValue).compareTo(value) >= 0;
                    } else {
                        result = ((Comparable)fieldValue).compareTo(value) > 0;
                    }
                } else {
                    throw new IllegalArgumentException("Incompatible types between value and field's value ("
                            + getQueryParameter().toString() + "): " + value.getClass() + " != " + fieldValue.getClass());
                }
            } else {
                throw new IllegalArgumentException("Unsupported evaluator type: " + value.getClass());
            }
        } catch (Exception ex) {
            throw new IllegalArgumentException("Greater than evaluator fail", ex);
        }
        return result;
    }

}


text:
package Shared.Networking;

/**
 *
 * @author Geerard
 */
public class TurnMessage extends Message {

    private boolean myTurn;

    public TurnMessage(boolean myTurn) {
        this.myTurn = myTurn;
    }

    public boolean isMyTurn() {
        return myTurn;
    }

    @Override
    public void handleSelf(MessageHandler m) {
        m.handleTurnMessage(this);
    }

}


text:
var CONST = require('../../../constants');
var io = require('socket.io-client');
var events = require('events');

/**
 * @constructor
 * @fires QuizJsPlayer#EVENT.PLAYER.REGISTER
 * @fires QuizJsPlayer#EVENT.STATE.UPDATE
 * @fires QuizJsPlayer#EVENT.STATE.RESET
 */
var QuizJsPlayer = function() {
	this._emitter = new events.EventEmitter();
};

/**
 * Connects to the socket.io server.
 *
 * @param {string} url The address to connect to
 */
QuizJsPlayer.prototype.connect = function(url) {
	var self = this;
	var socket = this._socket = io(url);

	socket.on('connect', function() {
		socket.emit(CONST.ACTION.PLAYER.CONNECT);
	});

	socket.on(CONST.EVENT.PLAYER.REGISTER, function(data) {
		self._connected = true;
		self._playerId = data.playerId;
		self._emitter.emit(CONST.EVENT.PLAYER.REGISTER, data);
	});

	socket.on(CONST.EVENT.STATE.UPDATE, function(data) {
		self._emitter.emit(CONST.EVENT.STATE.UPDATE, data);
	});

	socket.on(CONST.EVENT.STATE.RESET, function(data) {
		self._emitter.emit(CONST.EVENT.STATE.RESET, data);
	});
};

/**
 * Subscribes the player to the current question.
 */
QuizJsPlayer.prototype.subscribe = function() {
	if (this._connected) {
		this._socket.emit(CONST.ACTION.PLAYER.SUBSCRIBE, {
			playerId: this._playerId
		});
	} else {
		console.error('Player not connected!');
	}
};

QuizJsPlayer.prototype._socket = null;

QuizJsPlayer.prototype._connected = false;

QuizJsPlayer.prototype._playerId = undefined;

QuizJsPlayer.prototype._emitter = null;

QuizJsPlayer.prototype.on = function() {
    this._emitter.on.apply(this._emitter, arguments);
};

QuizJsPlayer.prototype.once = function() {
    this._emitter.once.apply(this._emitter, arguments);
};

QuizJsPlayer.prototype.removeListener = function() {
    this._emitter.removeListener.apply(this._emitter, arguments);
};

QuizJsPlayer.prototype.removeAllListener = function() {
    this._emitter.removeAllListeners.apply(this._emitter, arguments);
};

QuizJsPlayer.ACTION = CONST.ACTION;

QuizJsPlayer.EVENT = CONST.EVENT;

module.exports = QuizJsPlayer;


text:
@implementation UIImage (Extension)

- (NSData *)compressWithMaxLength:(NSInteger)maxLength
{
    CGFloat compress = 0.9f;
    NSData *data = UIImageJPEGRepresentation(self, compress);

    while (data.length > maxLength && compress > 0.01)
    {
        compress -= 0.02f;

        data = UIImageJPEGRepresentation(self, compress);
    }

    return data;
}

@end


text:
package headfirst.iterator.dinermergercafe;

import java.util.*;

public class CafeMenu implements Menu {
    Hashtable menuItems = new Hashtable();

    public CafeMenu() {
        addItem("Veggie Burger and Air Fries",
            "Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
            true, 3.99);
        addItem("Soup of the day",
            "A cup of the soup of the day, with a side salad",
            false, 3.69);
        addItem("Burrito",
            "A large burrito, with whole pinto beans, salsa, guacamole",
            true, 4.29);
    }

    public void addItem(String name, String description,
                         boolean vegetarian, double price)
    {
        MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
        menuItems.put(menuItem.getName(), menuItem);
    }

    public Hashtable getItems() {
        return menuItems;
    }

    public Iterator createIterator() {
        return menuItems.values().iterator();
    }
}


text:
package org.jenkinsci.remoting.protocol;

import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.jcip.annotations.GuardedBy;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

/**
 * The highest {@link ProtocolLayer} in a {@link ProtocolStack}. This layer is responsible for translating the protocol stack
 * into the application specific API.
 *
 * @param <T> the application specific API.
 *
 * @since 3.0
 */
public abstract class ApplicationLayer<T> implements ProtocolLayer, ProtocolLayer.Recv {

    /**
     * Our logger.
     */
    private static final Logger LOGGER = Logger.getLogger(ApplicationLayer.class.getName());
    /**
     * Lock to guard access to the {@link #sendClosed} and {@link #recvClosed} fields.
     */
    private final Object closedLock = new Object();
    /**
     * Our {@link ProtocolStack.Ptr}.
     */
    private ProtocolStack<?>.Ptr ptr;
    /**
     * Flag to track that the send path is closed.
     */
    @GuardedBy("closedLock")
    private boolean sendClosed;
    /**
     * Flag to track that the recv path is closed.
     */
    @GuardedBy("closedLock")
    private boolean recvClosed;

    /**
     * SPI: Returns the application specific API instance.
     *
     * @return the application specific API instance.
     */
    public abstract T get();

    /**
     * SPI: Implementations of {@link ApplicationLayer} must ensure this method either returns {@code true} while the
     * application specific API instance ({@link #get}) is accepting data via {@link #onRead(ByteBuffer)} or
     * returns {@code false} once it is permanently closed to incoming data. If the application specific API instance
     * is temporarily not accepting data then this method should return {@code true} and the implementation is
     * responsible for caching the data submitted in calls to {@link #onRead(ByteBuffer)}
     * Once this method returns {@code false} it must always return {@code false} and can be assumed to behave in
     * this way.
     *
     * @return {@code true} if the application specific API instance ({@link #get()} is accepting data via
     * {@link #onRead(ByteBuffer)}
     */
    public abstract boolean isReadOpen();

    /**
     * SPI: Callback on data being received from the protocol stack.
     *
     * @param data the data received. Any data consumed from the {@link ByteBuffer} can be assumed as processed.
     *             Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller
     *             to resubmit in subsequent calls.
     * @throws IOException if there was an error during processing of the received data.
     */
    public abstract void onRead(@NonNull ByteBuffer data) throws IOException;

    /**
     * Callback on the lower layer's source of data being closed.
     *
     * @param cause the cause of the lower layer being closed or {@code null}.
     * @throws IOException if there was an error during the processing of the close notification.
     */
    public abstract void onReadClosed(IOException cause) throws IOException;

    /**
     * {@inheritDoc}
     */
    @Override
    public final void init(@NonNull ProtocolStack<?>.Ptr ptr) throws IOException {
        if (this.ptr != null && this.ptr != ptr) {
            throw new IllegalStateException("Already initialized");
        }
        this.ptr = ptr;
    }

    /**
     * SPI: Implementations of {@link ApplicationLayer} should use method to detect if the {@link ProtocolStack} is
     * open for writing via {@link #write(ByteBuffer)} or has been closed.
     * Once this method returns {@code false} it will always return {@code false} and can be assumed to behave in
     * this way.
     *
     * @return {@code true} if the {@link ProtocolStack} is open for writing via {@link #write(ByteBuffer)}.
     */
    public final boolean isWriteOpen() {
        if (ptr == null) {
            throw new IllegalStateException();
        }
        synchronized (closedLock) {
            if (sendClosed) {
                return false;
            }
        }
        if (ptr.isSendOpen()) {
            return true;
        }
        synchronized (closedLock) {
            sendClosed = true;
            return false;
        }
    }

    /**
     * SPI: Implementations of {@link ApplicationLayer} should use this method to write data through the
     * {@link ProtocolStack}.
     *
     * @param data the data to write. Any data consumed from the {@link ByteBuffer} can be assumed as processed.
     *             Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller
     *             to resubmit in subsequent calls.
     * @throws IOException if there was an error during processing of the data.
     */
    public final void write(@NonNull ByteBuffer data) throws IOException {
        ptr.doSend(data);
    }

    /**
     * SPI: Implementations of {@link ApplicationLayer} should use this method to request that the write path of the
     * {@link ProtocolStack} be closed. Depending on the nature of the {@link NetworkLayer} this may force closed
     * the read path (e.g. if the backing transport is using a {@link SocketChannel}).
     *
     * @throws IOException if there was an error during the closing of the write path.
     */
    public final void doCloseWrite() throws IOException {
        synchronized (closedLock) {
            sendClosed = true;
        }
        if (ptr.isSendOpen()) {
            LOGGER.log(Level.FINE, "[{0}] Closing SEND", ptr.stack().name());
            ptr.doCloseSend();
        }
    }

    /**
     * SPI: Implementations of {@link ApplicationLayer} should use this method to request that the read path of the
     * {@link ProtocolStack} be closed. Depending on the nature of the {@link NetworkLayer} this may force closed
     * the write path (e.g. if the backing transport is using a {@link SocketChannel}).
     *
     * @throws IOException if there was an error during the closing of the read path.
     */
    public final void doCloseRead() throws IOException {
        if (ptr.stack().isRecvOpen()) {
            LOGGER.log(Level.FINE, "[{0}] Closing RECV", ptr.stack().name());
            ptr.stack().doCloseRecv();
        }
    }

    /**
     * Accessor for the {@link ProtocolStack} that we are bound to.
     *
     * @return the {@link ProtocolStack} that we are bound to or {@code null} if we are not currently bound to a stack.
     */
    @Nullable
    protected ProtocolStack<?> stack() {
        return ptr == null ? null : ptr.stack();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Restricted(NoExternalUse.class)
    public final void onRecv(@NonNull ByteBuffer data) throws IOException {
        onRead(data);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Restricted(NoExternalUse.class)
    public final void onRecvClosed(IOException cause) throws IOException {
        LOGGER.log(Level.FINE, "[{0}] RECV Closed", ptr.stack().name());
        synchronized (closedLock) {
            recvClosed = true;
        }
        IOException ioe = null;
        try {
            onReadClosed(cause);
            stack().onClosed(cause);
        } catch (IOException e) {
            ioe = e;
        } finally {
            try {
                doCloseWrite();
            } catch (IOException e) {
                if (ioe != null) {
                    ioe.addSuppressed(e);
                    throw ioe;
                }
                throw e;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Restricted(NoExternalUse.class)
    public final boolean isRecvOpen() {
        synchronized (closedLock) {
            if (recvClosed) {
                return false;
            }
        }
        if (isReadOpen()) {
            return true;
        }
        synchronized (closedLock) {
            recvClosed = true;
            return false;
        }
    }

}


text:
module Codeforces
  module Viewer
    module Utils
      def self.get_problem_url contest_id, problem_id
        "http://codeforces.com/contest/#{contest_id}/problem/#{problem_id}"
      end
    end
  end
end


text:
namespace onnxruntime {
namespace contrib {
namespace snpe {

constexpr const char* OPT_RUNTIME = "runtime";
constexpr const char* OPT_PRIORITY = "priority";
constexpr const char* BUFFER_TYPE = "buffer_type";

void SnpeRuntimeOptions::ParseOptions() {
  if (const auto runtime_opt_it = runtime_options_.find(OPT_RUNTIME); runtime_opt_it != runtime_options_.end()) {
    runtime_target_ = SnpeRuntimeWrapper(runtime_opt_it->second);
    LOGS_DEFAULT(INFO) << "Located user specified runtime target: " << runtime_opt_it->second;
  }
  LOGS_DEFAULT(INFO) << "Runtime target: " << runtime_target_.ToString();

  // Option Priority
  if (const auto priority_opt_it = runtime_options_.find(OPT_PRIORITY); priority_opt_it != runtime_options_.end()) {
    if (priority_opt_it->second == "low") {
      execution_priority_ = zdl::DlSystem::ExecutionPriorityHint_t::LOW;
    } else if (priority_opt_it->second == "normal") {
      execution_priority_ = zdl::DlSystem::ExecutionPriorityHint_t::NORMAL;
    } else {
      LOGS_DEFAULT(INFO) << "Invalid execution priority, defaulting to LOW";
      execution_priority_ = zdl::DlSystem::ExecutionPriorityHint_t::LOW;
    }

    LOGS_DEFAULT(INFO) << "Located user specified execution priority " << priority_opt_it->second;
  }

  // buffer type
  if (const auto buffer_type_it = runtime_options_.find(BUFFER_TYPE); buffer_type_it != runtime_options_.end()) {
    if (buffer_type_it->second == "TF8") {
      buffer_type_ = BufferType::TF8;
    } else if (buffer_type_it->second == "TF16") {
      buffer_type_ = BufferType::TF16;
    } else if (buffer_type_it->second == "ITENSOR") {
      buffer_type_ = BufferType::ITENSOR;
    } else if (buffer_type_it->second == "UINT8") {
      buffer_type_ = BufferType::UINT8;
    } else if (buffer_type_it->second == "FLOAT") {
      buffer_type_ = BufferType::FLOAT;
    } else {
      LOGS_DEFAULT(ERROR) << "Invalid buffer type: " << buffer_type_it->second;
      buffer_type_ = BufferType::UNKNOWN;
    }
  }
}

}  // namespace snpe
}  // namespace contrib
}  // namespace onnxruntime


text:
package cn.itcast.shop.utils;

import java.util.List;

import org.hibernate.dialect.Ingres10Dialect;

import cn.itcast.shop.product.vo.Product;

/**
 * 分页类的封装
 * @author Administrator
 *
 */
public class PageBean<T> {

	private int page;//当前页数
	private int totalCount;//总记录数
	private int totalPage;//总页数
	private int limit;//每页显示的记录数
	private List<T> list;
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getTotalPage() {
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public int getLimit() {
		return limit;
	}
	public void setLimit(int limit) {
		this.limit = limit;
	}
	public List<T> getList() {
		return list;
	}
	public void setList(List<T> list) {
		this.list = list;
	}

}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 9.5.5
description: >
    Trap is called with hander context and parameters are target and P
info: >
    [[GetOwnProperty]] (P)

    ...
    9. Let trapResultObj be Call(trap, handler, «target, P»).
    ...
---*/

var _target, _handler, _prop;
var target = {attr: 1};
var handler = {
    getOwnPropertyDescriptor: function(t, prop) {
        _target = t;
        _handler = this;
        _prop = prop;

        return Object.getOwnPropertyDescriptor(t);
    }
};
var p = new Proxy(target, handler);

Object.getOwnPropertyDescriptor(p, "attr");

assert.sameValue(_handler, handler);
assert.sameValue(_target, target);
assert.sameValue(_prop, "attr");


text:
require 'datamix'
using DataMix

sp500 = file '../_data/basic.csv'
sp500.preview


text:
package org.pantsbuild.zinc.analysis

import java.io.File

/**
 * Configuration for sbt analysis and analysis output options.
 */
case class AnalysisOptions(
  _cache: Option[File]         = None,
  cacheMap: Map[File, File]    = Map.empty,
  rebaseMap: Map[File, File]   = Map.empty,
  clearInvalid: Boolean        = true
) {
  lazy val cache: File =
    _cache.getOrElse {
      throw new RuntimeException(s"An analysis cache file is required.")
    }
}


text:
#include "LinRank.hpp"

//! Calculate rank NOT based on a wavelet tree
//! Linear computation of rank, runs in O(n)
/*!
 *  \param index        Index of the end of a sequence we are searching the rank for
 *  \param symbol       Symbol in the sequence we are searching the rank for
 */
index_type LinRank::rank(index_type index, symbol_type symbol) {
    index_type count = 0;
    for(index_type i=0; i<index; i++) {
        if(BWT[i] == symbol) {
            count++;
        }
    }
    return count;
}


text:
// Defines the base class for filter operations performed on I/Q SDR data
class FilterBase
{
    SdrBuffer* dataBuffer;
    unsigned int localBlockId;

    std::vector<unsigned char> currentBlock;

    bool acquiringBlocks;
    std::future<void> acquisitionThread;

    // Continually acquire blocks, sending them to the associated process function in a mirrored data set.
    void AcquireBlocks()
    {
        bool wasEnabled = true;
        while (acquiringBlocks)
        {
            if (enabled)
            {
                if (!wasEnabled)
                {
                    localBlockId = dataBuffer->GetCurrentBlockId();
                    wasEnabled = true;
                }

                while (acquiringBlocks && localBlockId != dataBuffer->GetCurrentBlockId())
                {
                    // Acquire and process the new block.
                    int idx = (localBlockId % dataBuffer->GetReadBlocks());
                    int startOffset = idx * dataBuffer->GetReadSize();
                    int endOffset = (idx + 1) * dataBuffer->GetReadSize();
                    currentBlock.clear();
                    currentBlock.insert(currentBlock.begin(), dataBuffer->GetBuffer().begin() + startOffset, dataBuffer->GetBuffer().begin() + endOffset);

                    // Logger::Log("Filter '", GetName(), "' processing new block ID ", (int)localBlockId, ".");
                    this->Process(&currentBlock);

                    ++localBlockId;
                }

                // Sleep for a half of the time it takes to acquire a block, so we don't leave the processing step with insufficient leeway in time.
                float currentSampleRate = dataBuffer->GetCurrentSampleRate();
                if (currentSampleRate > 1e4)
                {
                    // If the sample rate is lower, we're still initializing. Don't wait.
                    float sleepInMicroseconds = (1e6f * (float)dataBuffer->GetReadSize()) / (currentSampleRate * 2.0f);
                    // Logger::Log("Filter '", GetName(), "' sleeping for ", sleepInMicroseconds, " us.");
                    std::this_thread::sleep_for(std::chrono::microseconds((long)sleepInMicroseconds));
                }
            }
            else
            {
                wasEnabled = false;
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
                Logger::Log("Sleeing for 500 ms as the '", GetName(), "' filter was disabled.");
            }
        }
    }

protected:
    bool enabled;

    void StopFilter()
    {
        if (acquiringBlocks)
        {
            acquiringBlocks = false;
            acquisitionThread.wait();
        }
    }

public:
    FilterBase(SdrBuffer* dataBuffer)
        : dataBuffer(dataBuffer), acquiringBlocks(true)
    {
        localBlockId = dataBuffer->GetCurrentBlockId();
        currentBlock.reserve(dataBuffer->GetReadSize());

        enabled = false;
        acquisitionThread = std::async(std::launch::async, &FilterBase::AcquireBlocks, this);
    }

    virtual std::string GetName() const = 0;

    // Performs filter-specific short-term processing. Called for every new block.
    // Processes that need several blocks, or are expected to acquire blocks and then
    //  perform extensive processing them (discarding or caching new blocks during the extensive processing),
    //  should use a dedicated thread to perform said processing.
    virtual void Process(std::vector<unsigned char>* block) = 0;

    virtual ~FilterBase()
    {
        StopFilter();
    }
};


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class LikePost(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the LikePost Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(LikePost, self).__init__(temboo_session, '/Library/Tumblr/Post/LikePost')

    def new_input_set(self):
        return LikePostInputSet()

    def _make_result_set(self, result, path):
        return LikePostResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return LikePostChoreographyExecution(session, exec_id, path)

class LikePostInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the LikePost
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_APIKey(self, value):
        """
        Set the value of the APIKey input for this Choreo. ((required, string) The API Key provided by Tumblr (AKA the OAuth Consumer Key).)
        """
        super(LikePostInputSet, self)._set_input('APIKey', value)
    def set_AccessTokenSecret(self, value):
        """
        Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.)
        """
        super(LikePostInputSet, self)._set_input('AccessTokenSecret', value)
    def set_AccessToken(self, value):
        """
        Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.)
        """
        super(LikePostInputSet, self)._set_input('AccessToken', value)
    def set_ID(self, value):
        """
        Set the value of the ID input for this Choreo. ((required, integer) The ID of the post you want to like.)
        """
        super(LikePostInputSet, self)._set_input('ID', value)
    def set_ReblogKey(self, value):
        """
        Set the value of the ReblogKey input for this Choreo. ((required, string) The reblog key for the post id. This can be retrieved with the RetrievePublishedPosts Choreo.)
        """
        super(LikePostInputSet, self)._set_input('ReblogKey', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.)
        """
        super(LikePostInputSet, self)._set_input('ResponseFormat', value)
    def set_SecretKey(self, value):
        """
        Set the value of the SecretKey input for this Choreo. ((required, string) The Secret Key provided by Tumblr (AKA the OAuth Consumer Secret).)
        """
        super(LikePostInputSet, self)._set_input('SecretKey', value)

class LikePostResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the LikePost Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Tumblr. Default is JSON, can be set to XML by entering 'xml' in ResponseFormat.)
        """
        return self._output.get('Response', None)

class LikePostChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return LikePostResultSet(response, path)


text:
using System;
using Gtk;

using Banshee.ServiceStack;
using Banshee.MediaEngine;

namespace Banshee.NowPlaying
{
    public class XOverlayVideoDisplay : VideoDisplay
    {
        private Gdk.Window video_window;
        protected override Gdk.Window RenderWindow {
            get { return video_window; }
        }

        public XOverlayVideoDisplay () : base ()
        {
            HasWindow = false;
            CreateVideoWindow ();
        }

        protected override void OnRealized ()
        {
            IsRealized = true;
            CreateVideoWindow ();
            Window = Parent.Window;
            video_window.Reparent (Window, 0, 0);
            video_window.MoveResize (Allocation.X, Allocation.Y, Allocation.Width, Allocation.Height);
            video_window.ShowUnraised ();
        }

        private void CreateVideoWindow ()
        {
            if (video_window != null) {
                return;
            }

            var attributes = new Gdk.WindowAttr () {
                WindowType = Gdk.WindowType.Child,
                X = 0,
                Y = 0,
                Width = 0,
                Height = 0,
                Visual = Visual,
                Wclass = Gdk.WindowWindowClass.InputOutput,
                EventMask = (int)(Gdk.EventMask.ExposureMask | Gdk.EventMask.VisibilityNotifyMask)
            };

            Gdk.WindowAttributesType attributes_mask =
                Gdk.WindowAttributesType.X |
                Gdk.WindowAttributesType.Y |
                Gdk.WindowAttributesType.Visual;

            video_window = new Gdk.Window (null, attributes, attributes_mask);
            video_window.UserData = Handle;

            video_window.BackgroundPattern = null;

            if (ServiceManager.PlayerEngine.VideoDisplayContextType == VideoDisplayContextType.GdkWindow) {
                ServiceManager.PlayerEngine.VideoDisplayContext = video_window.Handle;
                ServiceManager.PlayerEngine.VideoWindowRealize (video_window.Handle);
            } else {
                ServiceManager.PlayerEngine.VideoDisplayContext = IntPtr.Zero;
            }
        }

        protected override void OnUnrealized ()
        {
            video_window.Hide ();
            video_window.Reparent (null, 0, 0);

            base.OnUnrealized ();
        }

        protected override void OnMapped ()
        {
            base.OnMapped ();
            video_window.ShowUnraised ();
        }

        protected override void OnUnmapped ()
        {
            video_window.Hide ();
            base.OnUnmapped ();
        }

        protected override void OnSizeAllocated (Gdk.Rectangle allocation)
        {
            if (!IsRealized) {
                return;
            }

            Gdk.Rectangle rect = new Gdk.Rectangle (allocation.X, allocation.Y, allocation.Width, allocation.Height);
            video_window.MoveResize (rect);

            base.OnSizeAllocated (allocation);

            QueueDraw ();
        }

        protected override bool OnConfigureEvent (Gdk.EventConfigure evnt)
        {
            if (video_window != null && ServiceManager.PlayerEngine.VideoDisplayContextType == VideoDisplayContextType.GdkWindow) {
                ServiceManager.PlayerEngine.VideoExpose (video_window.Handle, true);
            }

            return false;
        }

        protected override void ExposeVideo ()
        {
            if (ServiceManager.PlayerEngine.VideoDisplayContextType == VideoDisplayContextType.GdkWindow) {
                ServiceManager.PlayerEngine.VideoExpose (video_window.Handle, true);
            }
        }
    }
}


text:
package com.xjeffrose.xio.http.internal;

import com.xjeffrose.xio.http.FullResponse;
import com.xjeffrose.xio.http.Headers;
import com.xjeffrose.xio.http.TraceInfo;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

/** Wrap an incoming FullHttpResponse, for use in a client. */
public class FullHttp1Response implements FullResponse {

  private final FullHttpResponse delegate;
  private final Headers headers;
  private final TraceInfo traceInfo;

  public FullHttp1Response(FullHttpResponse delegate, TraceInfo traceInfo) {
    this.delegate = delegate;
    this.headers = new Http1Headers(delegate.headers());
    this.traceInfo = traceInfo == null ? new TraceInfo(headers) : traceInfo;
  }

  public FullHttp1Response(FullHttpResponse delegate) {
    this(delegate, null);
  }

  // region Response

  @Override
  public boolean startOfMessage() {
    return true;
  }

  @Override
  public boolean endOfMessage() {
    return true;
  }

  public HttpResponseStatus status() {
    return delegate.status();
  }

  public String version() {
    return delegate.protocolVersion().text();
  }

  public Headers headers() {
    return headers;
  }

  public boolean hasBody() {
    return delegate.content() != null && delegate.content().readableBytes() > 0;
  }

  public ByteBuf body() {
    return delegate.content();
  }

  // endregion

  // region Traceable

  @Override
  public TraceInfo httpTraceInfo() {
    return traceInfo;
  }

  // endregion
}


text:
package com.haulmont.cuba.web.gui.components;

import com.google.common.base.Strings;
import com.haulmont.cuba.core.global.BeanLocator;
import com.haulmont.cuba.core.global.Configuration;
import com.haulmont.cuba.gui.components.TabWindow;
import com.haulmont.cuba.web.WebConfig;
import com.haulmont.cuba.web.gui.MainTabSheetMode;
import com.haulmont.cuba.web.gui.WebWindow;
import com.haulmont.cuba.web.gui.icons.IconResolver;
import com.vaadin.ui.TabSheet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.inject.Inject;

import static com.haulmont.bali.util.Preconditions.checkNotNullArgument;

public class WebTabWindow extends WebWindow implements TabWindow {

    private static final Logger log = LoggerFactory.getLogger(WebTabWindow.class);

    protected ContentSwitchMode contentSwitchMode = ContentSwitchMode.DEFAULT;

    protected BeanLocator beanLocator;

    public WebTabWindow() {
        setSizeFull();

        // default caption for Tab is not empty
        setCaption(" ");
    }

    @Inject
    public void setBeanLocator(BeanLocator beanLocator) {
        this.beanLocator = beanLocator;
    }

    @Override
    public void setIcon(String icon) {
        super.setIcon(icon);

        if (component.isAttached()) {
            TabSheet.Tab tabWindow = findTab();
            if (tabWindow != null) {
                IconResolver iconResolver = beanLocator.get(IconResolver.NAME);
                tabWindow.setIcon(iconResolver.getIconResource(icon));
            }
        }
    }

    @Nullable
    protected TabSheet.Tab findTab() {
        if (component.isAttached()) {
            com.vaadin.ui.Component parent = component;
            while (parent != null) {
                if (parent.getParent() instanceof TabSheet) {
                    return ((TabSheet) parent.getParent()).getTab(parent);
                }

                parent = parent.getParent();
            }
        }
        return null;
    }

    @Override
    public String formatTabCaption() {
        String s = formatTabDescription();

        WebConfig webConfig = beanLocator.get(Configuration.class)
                .getConfig(WebConfig.class);

        int maxLength = webConfig.getMainTabCaptionLength();
        if (s.length() > maxLength) {
            return s.substring(0, maxLength) + "...";
        } else {
            return s;
        }
    }

    @Override
    public String formatTabDescription() {
        if (!StringUtils.isEmpty(getDescription())) {
            return String.format("%s: %s", getCaption(), getDescription());
        } else {
            return Strings.nullToEmpty(getCaption());
        }
    }

    @Override
    public ContentSwitchMode getContentSwitchMode() {
        return contentSwitchMode;
    }

    @Override
    public void setContentSwitchMode(ContentSwitchMode mode) {
        checkNotNullArgument(mode, "Content switch mode can't be null. Use ContentSwitchMode.DEFAULT option instead");

        MainTabSheetMode tabSheetMode = beanLocator.get(Configuration.class)
                .getConfig(WebConfig.class)
                .getMainTabSheetMode();
        if (tabSheetMode != MainTabSheetMode.MANAGED) {
            log.debug("Content switch mode can be set only for the managed main TabSheet. Current invocation will be ignored.");
        }

        this.contentSwitchMode = mode;
    }
}


text:
namespace {

const char kBackground[] = "background";
const char kPersistent[] = "persistent";

}  // namespace

WindowContainerType WindowFeaturesToContainerType(
    const blink::WebWindowFeatures& window_features) {
  bool background = false;
  bool persistent = false;

  for (size_t i = 0; i < window_features.additionalFeatures.size(); ++i) {
    if (LowerCaseEqualsASCII(window_features.additionalFeatures[i],
                             kBackground))
      background = true;
    else if (LowerCaseEqualsASCII(window_features.additionalFeatures[i],
                                  kPersistent))
      persistent = true;
  }

  if (background) {
    if (persistent)
      return WINDOW_CONTAINER_TYPE_PERSISTENT;
    else
      return WINDOW_CONTAINER_TYPE_BACKGROUND;
  } else {
    return WINDOW_CONTAINER_TYPE_NORMAL;
  }
}


text:
import sys
from collections import namedtuple

Selection = namedtuple('Selection', ['start', 'end', 'is_caret'])

class View(object):
    """Represents a view into a buffer."""
    def __init__(self, view_id, lines):
        self.view_id = view_id
        self.lines = lines

    @property
    def path(self):
        return self.lines.path

    @property
    def syntax(self):
        return self.lines.syntax

    def get_selections(self):
        selections = self.lines.peer.get_selections(self.view_id)
        selections = selections['selections']
        return [Selection(s, e, (s == e)) for (s, e) in selections]

    def update_spans(self, *args, **kwargs):
        self.lines.peer.update_spans(self.view_id, *args, **kwargs)

    def add_scopes(self, *args, **kwargs):
        self.lines.peer.add_scopes(self.view_id, *args, **kwargs)

    def edit(self, *args, **kwargs):
        self.lines.peer.edit(self.view_id, *args, **kwargs)


text:
package me.heaton.profun.week2

import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class TailRecursionTest extends FunSuite {

  test("gcd of 14 and 21 is 7")(assert(TailRecursion.gcd(14, 21) === 7))

  test("factorial of 4 is 24")(assert(TailRecursion.factorial(4) === 24))

  test("tail_factorial of 4 is 24") {
    assert(TailRecursion.tailFactorial(4) === 24)
  }

}


text:
<?php

namespace Matteo\LearnBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Matteo\LearnBundle\Entity\Flashcard;
use Matteo\LearnBundle\Entity\FlashcardRepository;
use Matteo\LearnBundle\Form\FlashcardType;
use Matteo\LearnBundle\Entity\Cardbox;

/**
 * Flashcard controller.
 *
 */
class FlashcardController extends Controller
{

    /**
     * The action created for learning the flashcards
     *
     */
    public function learnAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $cardbox = $em->getRepository('MatteoLearnBundle:Cardbox')->find($id);

        if (!$cardbox) {
            throw $this->createNotFoundException('Unable to find Cardbox entity.');
        }

        $flashcards = $em->getRepository('MatteoLearnBundle:Flashcard')->findFlashcardsWithCardbox($id);

        return $this->render('MatteoLearnBundle:Flashcard:learn.html.twig', array(
            'cardbox'      => $cardbox,
            'flashcards'   => $flashcards,
        ));
    }

    /**
     * Create Form adding or editing existing Flashcards to a specified cardbox.
     *
     */
    public function addOrEditAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $currentCardbox = $em->getRepository('MatteoLearnBundle:Cardbox')->find($id);
        $entity = new Flashcard();

        // Create a form for creating a new Flashcard
        $newFlashcard = new FlashcardType();
        $newFlashcard->setName('learn_flashcard_new0');
        $newFlashcardForm = $this->createForm($newFlashcard, $entity);
        // Get all the existing flashcards in the $currentCardbox
        $flashcards = $em->getRepository('MatteoLearnBundle:Flashcard')->findFlashcardsWithCardbox($id);
        // If there aren't any, just display the form without any prerenderd forms
        if (!$flashcards) {
            return $this->render('MatteoLearnBundle:Flashcard:edit.html.twig', array(
                'entity' => $entity,
                'form'   => $newFlashcardForm->createView(),
                'cardbox'=> $currentCardbox,
            ));
        }

        $forms = array();
        foreach ($flashcards as $key => $flashcard) {
            $formType = new FlashcardType();
            // Change the name, so the id's and name's won't be the same in the html markup
            $formType->setName('learn_flashcard_' . $key);
            // Create a form and put it all together in the $forms array
            $form    = $this->createForm($formType, $flashcard);
            $form    = $form->createView();
            $forms[] = $form;
        }

        return $this->render('MatteoLearnBundle:Flashcard:edit.html.twig', array(
            'entity' => $entity,
            'forms'  => $forms,
            'form'   => $newFlashcardForm->createView(),
            'cardbox'=> $currentCardbox,
        ));

    }

    /**
     * Create Action for a specified cardbox.
     *
     */
    public function updateAction(Request $request, $id, $cardbox)
    {
        $em = $this->getDoctrine()->getManager();

        $currentCardbox = $em->getRepository('MatteoLearnBundle:Cardbox')->find($id);
        if (!$currentCardbox) {
            throw $this->createNotFoundException('Unable to find Cardbox entity.');
        }

        $flashcards = $em->getRepository('MatteoLearnBundle:Flashcard')->findFlashcardsWithCardbox($id);

        if ($flashcards) {
            // Delete existing entries
            foreach ($flashcards as $flashcard) {
                $em->remove($flashcard);
            }
        }

        // Add edited + new cards
        $newCards = $request->request->all();

        foreach($newCards as $card) {
            $flashcard = new Flashcard();
            $flashcard->setFront($card['front']);
            $flashcard->setBack($card['back']);
            // Since it's optional
            if (isset($card['declaration'])) {
                $flashcard->setDeclaration($card['declaration']);
            }
            $flashcard->setCardbox($currentCardbox);

            $em->persist($flashcard);
        }

        // Finally flush everything
        $em->flush();

        return $this->redirect($this->generateUrl('learn_cardbox_show', array('id' => $id, 'cardbox' => $cardbox)));
    }
}


text:
#region License

#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace QueryMaster.GameServer
{
    /// <summary>
    /// Represents a filter that filters by provided regex filter pattern.
    /// </summary>
   public class RegexFilter:LogFilter
    {
       /// <summary>
       /// Regex pattern.
       /// </summary>
       public string RegexPattern { get; set; }
       /// <summary>
       /// Regex filter pattern.
       /// </summary>
       /// <returns>Regex filter pattern.</returns>
       public override string ToString()
       {
           return RegexPattern;
       }
    }
}


text:
"""
Image caching and management.
"""
import os

from nova.openstack.common import lockutils
from nova.openstack.common import log as logging
from nova.virt.hyperv import pathutils
from nova.virt.hyperv import vhdutils
from nova.virt.hyperv import vmutils
from nova.virt import images

LOG = logging.getLogger(__name__)

class ImageCache(object):
    def __init__(self):
        self._pathutils = pathutils.PathUtils()
        self._vhdutils = vhdutils.VHDUtils()

    def _validate_vhd_image(self, vhd_path):
        try:
            self._vhdutils.get_vhd_info(vhd_path)
        except Exception as ex:
            LOG.exception(ex)
            raise vmutils.HyperVException(_('The image is not a valid VHD: %s')
                                          % vhd_path)

    def get_cached_image(self, context, instance):
        image_id = instance['image_ref']

        base_vhd_dir = self._pathutils.get_base_vhd_dir()
        vhd_path = os.path.join(base_vhd_dir, image_id + ".vhd")

        @lockutils.synchronized(vhd_path, 'nova-')
        def fetch_image_if_not_existing():
            if not self._pathutils.exists(vhd_path):
                images.fetch(context, image_id, vhd_path,
                             instance['user_id'],
                             instance['project_id'])
                self._validate_vhd_image(vhd_path)

        fetch_image_if_not_existing()
        return vhd_path


text:
require 'active_scraper/response_object/basic'

module ActiveScraper
  module ResponseObject

    def self.factory(obj)
      ActiveScraper::ResponseObject::Basic.new(obj)
    end

  end
end


text:
<?php

/**
 * @group pholio
 */
final class PholioInlineCommentEditView extends AphrontView {

  private $inputs = array();
  private $uri;
  private $title;

  private $inlineComment;

  public function addHiddenInput($key, $value) {
    $this->inputs[] = array($key, $value);
    return $this;
  }

  public function setSubmitURI($uri) {
    $this->uri = $uri;
    return $this;
  }

  public function setTitle($title) {
    $this->title = $title;
    return $this;
  }

  public function setInlineComment($inline_comment) {
    $this->inlineComment = $inline_comment;
    return $this;
  }

  public function render() {
    if (!$this->uri) {
      throw new Exception("Call setSubmitURI() before render()!");
    }
    if (!$this->user) {
      throw new Exception("Call setUser() before render()!");
    }

    $content = phabricator_form(
      $this->user,
      array(
        'action'    => $this->uri,
        'method'    => 'POST',
        'sigil'     => 'inline-edit-form',
      ),
      array(
        $this->renderInputs(),
        $this->renderBody(),
      ));

    return $content;
  }

  private function renderInputs() {
    $out = array();
    foreach ($this->inputs as $input) {
      list($name, $value) = $input;
      $out[] = phutil_tag(
        'input',
        array(
          'type'  => 'hidden',
          'name'  => $name,
          'value' => $value,
        ));
    }
    return $out;
  }

  private function renderBody() {
    $buttons = array();

    $buttons[] = javelin_tag(
      'button',
      array(
        'sigil' => 'inline-edit-submit',
        'meta' => array(
          'id' => $this->inlineComment->getID(),
          'phid' => $this->inlineComment->getPHID()
        )
      ),
      pht('Ready'));
    $buttons[] = javelin_tag(
      'button',
      array(
        'sigil' => 'inline-edit-cancel',
        'meta' => array(
          'id' => $this->inlineComment->getID()
        ),
        'class' => 'grey',
      ),
      pht('Cancel'));

    $formatting = phutil_tag(
      'a',
      array(
        'href' => PhabricatorEnv::getDoclink(
          'article/Remarkup_Reference.html'),
        'tabindex' => '-1',
        'target' => '_blank',
      ),
      pht('Formatting Reference'));

    $title = phutil_tag(
      'div',
      array(
        'class' => 'pholio-inline-comment-dialog-title',
      ),
      $this->title);

    $body = phutil_tag(
      'div',
      array(),
      $this->renderChildren());

    $edit = phutil_tag(
      'edit',
      array(
        'class' => 'pholio-inline-comment-dialog-buttons',
      ),
      array(
        $formatting,
        $buttons,
        phutil_tag('div', array('style' => 'clear: both'), ''),
      ));

    return javelin_tag(
      'div',
      array(
        'class' => 'pholio-inline-comment-dialog',
      ),
      array(
        $title,
        $body,
        $edit,
      ));
  }

}


text:
- IoT data collection and analytics software tool-kit based on RaspberryPi which is driven from IoT level computing system
- Software stack for physical computing and intelligent SW service based on IoT data collection & processing (Big data)
- is based on RaspberryPi distribution (hardware and software)
- supports Ubuntu64_ARM
  - previous version : Raspbian OS, Buster (ver 2019.09.12), with RaspBerryPi4 (input hangul mode, 한글모드)

##### Contribution
  - Jeonghoon Kang(https://github.com/jeonghoonkang), Philman Jeong(https://github.com/ipmstyle), Sukun Kim(https://github.com/sukunkim)

### DiskPi which is a new direction for secure pi computing
- After 2021, not long ago, RaspberryPi started to support SSD/HDD Booting by USB link. It gives us a new approach which has a very quick booting speed and secure, nice non-breakable booting code, rather than beaten by electricity accident such as SD card crash.
- more detail new hardware, please visit https://polarized-poppyseed-8e0.notion.site/0c68de4668d74bb58c526406ec78d47d

### Old documents which is still valid.

#### Wiki doc
  - RaspberryPi OS installation and setup to run the SDH sensors
  - It shows basic installation process for Raspberyypi Sensor System
    - [BerePi Wiki](https://github.com/jeonghoonkang/BerePi/wiki)
  - Installation Image for RaspberryPi4 (2020.08)
    - RaspberryPi image install (use your computer to copy raspberrypi OS in SD card)
      - https://www.raspberrypi.org/downloads/
    - important first setup check steps:
      1. use American English language, US keyboard, US timezone (like LA)
      2. change hostname by editing /etc/hostname (like tinygw-4b-0820-31)
      3. raspberrypi config run to setup SSH connection
    - if you want to install Ubuntu 64-bit, follow the instruction, it needs 8G sd card.

#### Wireless Sensor Network (WSN) using RaspberryPi
You can connect wireless sensors to your cyber space easily, just trying to add BerePi module sensor, to your RaspberryPi.
BerePi project opens software which using BerePi hardware modules.
  - Simple LED video 01 (YouTube : https://youtu.be/ygJ3qMiGQvw)
  - BereCO2 HW module
  - BereCO2 update with enclosure
    - ![BereCO2 Enclosure](https://raw.githubusercontent.com/jeonghoonkang/BerePi/master/files/CO2/CO2_inside_01.JPG)
    - ![BereCO2 Enclosure](https://raw.githubusercontent.com/jeonghoonkang/BerePi/master/files/CO2/CO2_inside_02.JPG)
- [Previous Enclosure](https://github.com/jeonghoonkang/BerePi/blob/master/files/RPi2_case.png)
  - BereCO2 update with SHT20 (KETI motes sensor board)
   - SHT20 board photo and connection : (https://raw.githubusercontent.com/jeonghoonkang/BerePi/master/files/Raspi_temp_humi_sht20_keti_motes_bd_00.jpg), (https://raw.githubusercontent.com/jeonghoonkang/BerePi/master/files/Raspi_temp_humi_sht20_keti_motes_bd_01.jpg)

## Installation
  - Please follow Wiki(https://github.com/jeonghoonkang/BerePi/wiki) to download and install pre-configured SD image
  - Old Installation note
    - Download OS image and set up scripts and environemnt, automatically
    - https://github.com/jeonghoonkang/BerePi/blob/master/Install_Raspi_OS.md

## Links
 - nice additional external works :
  1. http://www.raspberrypi-spy.co.uk/
  1. http://www.raspberrypi-spy.co.uk/berryclip-6-led-add-on-board/berryclip-6-led-add-on-board-instructions/

- If you want to setup BerePi with your own Ubuntu Linux, please run below shell script files to setup packages, development environment
  - Raspi init setting : same in the installation instruction
    - please use, wget https://raw.githubusercontent.com/jeonghoonkang/BerePi/master/setup/init.sh
     - short URL is https://goo.gl/GDiYfN
     - It downloads init.sh file
     - download and run : source init.sh
  - Raspi2 PinOut:http://www.element14.com/community/docs/DOC-73950/l/raspberry-pi-2-model-b-gpio-40-pin-block-pinout


text:
/**
 * Enforce tabindex value is **not greater than zero**
 */

import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';

import { ExtendedMetadata } from './utils/ExtendedMetadata';
import { getPropName, getStringLiteral, getNumericLiteral, isEmpty } from './utils/JsxAttribute';

export function getFailureString(): string {
    return 'The value of tabindex attribute is invalid or undefined. It must be either -1 or 0.';
}

export class Rule extends Lint.Rules.AbstractRule {
    public static metadata: ExtendedMetadata = {
        ruleName: 'react-a11y-tabindex-no-positive',
        type: 'maintainability',
        description: 'Enforce tabindex value is **not greater than zero**.',
        rationale: `References:

WCAG 2.4.3 - Focus Order

Audit Rules - tabindex-usage

Avoid positive integer values for tabIndex

`,
        options: null, // tslint:disable-line:no-null-keyword
        optionsDescription: '',
        typescriptOnly: true,
        issueClass: 'Non-SDL',
        issueType: 'Warning',
        severity: 'Important',
        level: 'Opportunity for Excellence',
        group: 'Accessibility'
    };

    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return sourceFile.languageVariant === ts.LanguageVariant.JSX ? this.applyWithFunction(sourceFile, walk) : [];
    }
}

function walk(ctx: Lint.WalkContext<void>) {
    function cb(node: ts.Node): void {
        if (tsutils.isJsxAttribute(node)) {
            const name = getPropName(node);

            if (!name || name.toLowerCase() !== 'tabindex') {
                return;
            }

            const literalString = getNumericLiteral(node) || getStringLiteral(node);

            // In case the attribute has no value of empty value.
            if (literalString === '') {
                ctx.addFailureAt(node.getStart(), node.getWidth(), getFailureString());
            } else if (literalString && literalString !== '-1' && literalString !== '0') {
                ctx.addFailureAt(node.getStart(), node.getWidth(), getFailureString());
            } else if (isEmpty(node)) {
                ctx.addFailureAt(node.getStart(), node.getWidth(), getFailureString());
            }
        }

        return ts.forEachChild(node, cb);
    }

    return ts.forEachChild(ctx.sourceFile, cb);
}


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

namespace NiL.JS.Expressions
{
    public sealed class ExtractStoredValue : Expression
    {
        protected internal override bool ContextIndependent
        {
            get
            {
                return false;
            }
        }

        protected internal override bool NeedDecompose
        {
            get
            {
                return false;
            }
        }

        public ExtractStoredValue(Expression source)
            : base(source, null, false)
        {

        }

        protected internal override JSValue EvaluateForWrite(Context context)
        {
            return Evaluate(context);
        }

        public override JSValue Evaluate(Context context)
        {
            return (JSValue)context.SuspendData[_left];
        }

        public override bool Build(ref CodeNode _this, int expressionDepth, Dictionary<string, VariableDescriptor> variables, CodeContext codeContext, CompilerMessageCallback message, FunctionInfo stats, Options opts)
        {
            return false;
        }

        public override string ToString()
        {
            return _left.ToString();
        }

        public override void Decompose(ref Expression self, IList<CodeNode> result)
        {

        }
    }
}


text:
import unittest
import mock

from django.core.urlresolvers import reverse
from django import forms

from ..views import AddEmployeeQuestionnaireFromSignUpFormView
from .. import constants
from libs import constants as lib_constants

class AddAddEmployeeQuestionnaireFromSignUpFormViewTestCase(unittest.TestCase):
    @mock.patch('employee.forms.ResumeForQuestionnaireForm')
    def test_get_should_call_render_to_response_with_questionnaire_form(
            self, resume_form):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        view.render_to_response = mock.Mock()
        request = self.get_request()
        view.request = request

        # action
        view.get(request)

        # assert
        self.assertEqual(1, view.render_to_response.call_count)
        context = view.render_to_response.call_args[0][0]
        self.assertTrue('form' in context.keys())
        form = context['form']
        ### Personal Info
        self.assertTrue('first_name' in form.fields.keys())
        self.assertTrue('last_name' in form.fields.keys())
        self.assertTrue('personal_address' in form.fields.keys())
        self.assertTrue('personal_zip_code' in form.fields.keys())
        self.assertTrue('personal_city' in form.fields.keys())
        self.assertTrue('personal_state' in form.fields.keys())
        ### Job Position you're looking for
        self.assertTrue('job_position' in form.fields.keys())
        ### Type of Practice
        self.assertTrue('solo_practitioner' in form.fields.keys())
        self.assertTrue('multi_practitioner' in form.fields.keys())
        self.assertTrue('corporate' in form.fields.keys())
        ### Patients' Method of Payment
        self.assertTrue('fee_for_service' in form.fields.keys())
        self.assertTrue('insurance' in form.fields.keys())
        self.assertTrue('capitation_medicaid' in form.fields.keys())
        ### Location
        self.assertTrue('zip_code' in form.fields.keys())
        self.assertTrue('city' in form.fields.keys())
        self.assertTrue('state' in form.fields.keys())
        self.assertTrue('distance' in form.fields.keys())
        ### Type of schedule required
        self.assertTrue('schedule_type' in form.fields.keys())
        self.assertTrue('monday_daytime' in form.fields.keys())
        self.assertTrue('monday_evening' in form.fields.keys())
        self.assertTrue('tuesday_daytime' in form.fields.keys())
        self.assertTrue('tuesday_evening' in form.fields.keys())
        self.assertTrue('wednesday_daytime' in form.fields.keys())
        self.assertTrue('wednesday_evening' in form.fields.keys())
        self.assertTrue('thursday_daytime' in form.fields.keys())
        self.assertTrue('thursday_evening' in form.fields.keys())
        self.assertTrue('friday_daytime' in form.fields.keys())
        self.assertTrue('friday_evening' in form.fields.keys())
        self.assertTrue('saturday_daytime' in form.fields.keys())
        self.assertTrue('saturday_evening' in form.fields.keys())
        self.assertTrue('sunday_daytime' in form.fields.keys())
        self.assertTrue('sunday_evening' in form.fields.keys())
        ### Compensation
        self.assertTrue('compensation_type' in form.fields.keys())
        self.assertTrue('hourly_wage' in form.fields.keys())
        self.assertTrue('annualy_wage' in form.fields.keys())
        self.assertTrue('production' in form.fields.keys())
        self.assertTrue('collection' in form.fields.keys())
        ### Experience
        self.assertTrue('experience_years' in form.fields.keys())
        ### Education
        self.assertTrue('dental_school' in form.fields.keys())
        self.assertTrue('graduation_year' in form.fields.keys())
        ### Visa
        self.assertTrue('visa' in form.fields.keys())
        ### Specific Strengths
        self.assertTrue('specific_strengths' in form.fields.keys())
        ### Visibility
        self.assertTrue('is_private' in form.fields.keys())

    @mock.patch('employee.forms.ResumeForQuestionnaireForm')
    def test_get_should_call_template_response_with_template(
            self, resume_form):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        request = self.get_request()
        view.request = request
        view.response_class = mock.Mock()
        template_name = 'employee/add_employee_questionnaire_form.html'

        # action
        view.get(request)

        # assert
        self.assertEqual(1, view.response_class.call_count)
        self.assertEqual(template_name,
            view.response_class.call_args[1]['template'][0])

    def test_form_valid_should_redirect_to_success_url(self):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()

        # assert
        self.assertEqual('membership:home', view.success_url_alias)

    def test_get_initial_should_set_schedule_type_and_compensation_type_as_part_time(self):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()

        # action
        initial = view.get_initial()

        # assert
        self.assertDictEqual(dict(
            schedule_type=constants.SCHEDULE_TYPE_CHOICES.PART_TIME,
            compensation_type=constants.COMPENSATION_TYPE_CHOICES.HOURLY,
            visa=lib_constants.YES_NO_CHOICES.YES),
            initial)

    @mock.patch('employee.views.CreateView.get_form_kwargs')
    def test_get_form_kwargs_should_return_kwargs_with_skippable_set_to_true_when_skip_is_present_in_post(
            self, get_form_kwargs):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        request = mock.Mock()
        request.POST = dict(_skip=True)
        view.request = request
        get_form_kwargs.return_value = {}

        # action
        returned_value = view.get_form_kwargs()

        # assert
        self.assertTrue(returned_value['skippable'])
        self.assertEqual(id(get_form_kwargs.return_value), id(returned_value))

    @mock.patch('employee.views.CreateView.get_form_kwargs')
    def test_get_form_kwargs_should_return_kwargs_with_skippable_set_to_false_when_skip_isnt_present_in_post(
            self, get_form_kwargs):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        request = mock.Mock()
        request.POST = {}
        view.request = request
        get_form_kwargs.return_value = {}

        # action
        returned_value = view.get_form_kwargs()

        # assert
        self.assertFalse(returned_value['skippable'])
        self.assertEqual(id(get_form_kwargs.return_value), id(returned_value))

    @mock.patch('employee.views.CreateView.render_to_response')
    @mock.patch('employee.views.CreateView.get_context_data')
    @mock.patch('employee.views.CreateView.get_form')
    def test_form_invalid_calls_render_to_response_with_skippable_and_form_as_context(self,
            get_form, get_context_data, render_to_response):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        form = mock.Mock()

        # action
        response = view.form_invalid(form)

        # assert
        self.assertEqual(1, get_form.return_value.is_valid.call_count)
        self.assertDictEqual(dict(skippable=False, form=form),
            get_context_data.call_args[1])
        self.assertTupleEqual((get_context_data.return_value,),
            render_to_response.call_args[0])
        self.assertEqual(id(render_to_response.return_value), id(response))

    @mock.patch('employee.views.CreateView.render_to_response')
    @mock.patch('employee.views.CreateView.get_context_data')
    @mock.patch('employee.views.CreateView.get_form')
    def test_form_invalid_sets_skippable_true_when_incomplete_form_validation_error_is_raised(self,
            get_form, get_context_data, render_to_response):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        form = mock.Mock()
        get_form.return_value.clean.configure_mock(
            side_effect=forms.ValidationError('',
            code=constants.QUESTIONNAIRE_FORM_INCOMPLETE_FORM_ERROR_CODE))

        # action
        response = view.form_invalid(form)

        # assert
        self.assertDictEqual(dict(skippable=True, form=form),
            get_context_data.call_args[1])

    @mock.patch('employee.views.CreateView.render_to_response')
    @mock.patch('employee.views.CreateView.get_context_data')
    @mock.patch('employee.views.CreateView.get_form')
    def test_form_invalid_doesnt_set_skippable_true_when_generic_validation_error_is_raised(self,
            get_form, get_context_data, render_to_response):
        # setup
        view = AddEmployeeQuestionnaireFromSignUpFormView()
        form = mock.Mock()
        get_form.return_value.clean.configure_mock(
            side_effect=forms.ValidationError(''))

        # action
        response = view.form_invalid(form)

        # assert
        self.assertDictEqual(dict(skippable=False, form=form),
            get_context_data.call_args[1])

    def get_request(self):
        request = mock.Mock()
        request.path = reverse('employee:questionnaire_signup_add')
        request.META.get = mock.Mock(return_value='')
        request.POST = {}
        return request


text:
NSString *const UniDBErrorDomain = @"UniDBErrorDomain";

static __inline__ __attribute__((always_inline)) NSError * UniDBError(sqlite3* db){
    if (!db) return nil;
    return [NSError errorWithDomain:UniDBErrorDomain code:sqlite3_errcode(db) userInfo:@{NSLocalizedDescriptionKey:[[NSString alloc] initWithCString:sqlite3_errmsg(db) encoding:NSUTF8StringEncoding]}];
}

@interface UniStmt : NSObject

@property (nonatomic, assign) sqlite3_stmt *stmt;

@end

@implementation UniStmt

- (void)dealloc {
    if (self.stmt) sqlite3_finalize(self.stmt);
}

@end

@interface UniStmtPool : NSObject

@property (nonatomic,strong)NSMutableDictionary<NSString*,NSMutableArray<UniStmt*>*> *stmts;
@property (nonatomic,strong)dispatch_queue_t queue;

@end

@implementation UniStmtPool

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithSqlite3:(sqlite3*)db{
    if (!db){
        NSParameterAssert(0);
        return nil;
    }
    self=[self init];
    if (!self) return nil;
    self.stmts=[NSMutableDictionary dictionary];
    self.queue=dispatch_queue_create("com.retriable.pool", NULL);
#if TARGET_OS_IOS || TARGET_OS_TV
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
    return self;
}

- (UniStmt*)popStmt:(NSString*)sql{
    NSParameterAssert(sql);
    __block UniStmt *s;
    dispatch_sync(self.queue, ^{
        NSMutableArray * arr=self.stmts[sql];
        if (arr){
            s=arr.firstObject;
            if (s) [arr removeObjectAtIndex:0];
        }
    });
    return s;
}

- (void)push:(UniStmt*)s sql:(NSString*)sql{
    NSParameterAssert(s);
    sqlite3_reset(s.stmt);
    sqlite3_clear_bindings(s.stmt);
    dispatch_sync(self.queue, ^{
        NSMutableArray * arr=self.stmts[sql];
        if (!arr){
            arr=[NSMutableArray array];
            self.stmts[sql]=arr;
        }
        [arr addObject:s];
    });
}

- (void)applicationDidReceiveMemoryWarning:(NSNotification*)n{
    dispatch_sync(self.queue, ^{
        [self.stmts removeAllObjects];
    });
}

@end

@interface UniDB ()

@property (nonatomic, assign) sqlite3 *db;
@property (nonatomic, strong) UniStmtPool *pool;
@property (nonatomic, assign) UInt64 transactionReferenceCount;

@end

@implementation UniDB

- (void)dealloc {
    [self close];
}

- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    self.transactionReferenceCount = 0;
    return self;
}

#pragma mark--
#pragma mark-- open and close

- (BOOL)open:(NSString *)file error:(NSError **)error {
    [self close];
    if (!file) return NO;
    sqlite3 *db;
    if (sqlite3_open([file cStringUsingEncoding:NSUTF8StringEncoding], &db) != SQLITE_OK) {
        if (error) *error = UniDBError(db);
        return NO;
    }
    self.db = db;
    self.pool=[[UniStmtPool alloc]initWithSqlite3:db];
    return YES;
}

- (BOOL)close {
    if (self.db) {
        if (sqlite3_close(self.db) != SQLITE_OK) return NO;
        self.pool=nil;
        self.db = nil;
    }
    return YES;
}

#pragma mark--
#pragma mark-- stmt

- (UniStmt *)getStmtForSql:(NSString *)sql error:(NSError **)error {
    UniStmt *s = [self.pool popStmt:sql];
    if (s) return s;
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(self.db, [sql UTF8String], -1, &stmt, 0) != SQLITE_OK) {
        sqlite3_finalize(stmt);
        if (error) *error = UniDBError(self.db);
        return nil;
    }
    s = [[UniStmt alloc] init];
    s.stmt = stmt;
    return s;
}

- (void)putStmt:(UniStmt*)s forSql:(NSString*)sql{
    if (!s){
        NSParameterAssert(0);
        return;
    }
    [self.pool push:s sql:sql];
}

#pragma mark--
#pragma mark-- query

- (NSArray *)executeQuery:(NSString *)sql arguments:(NSArray *)arguments error:(NSError **)error {
    return [self executeQuery:sql stmtBlock:^(sqlite3_stmt *stmt, int idx) {
        [self _bindObject:arguments[idx - 1] toColumn:idx inStatement:stmt];
    } error:error];
}

- (NSArray *)executeQuery:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock error:(NSError **)error {
    __block NSMutableArray *array = [NSMutableArray array];
    [self executeQuery:sql stmtBlock:stmtBlock resultBlock:^(sqlite3_stmt *stmt, bool *stop) {
        int count = sqlite3_data_count(stmt);
        NSDictionary *dictionary = [self _dictionaryInStmt:stmt count:count];
        if (dictionary.count > 0) [array addObject:dictionary];
    } error:error];
    return array;
}

- (BOOL)executeQuery:(NSString *)sql arguments:(NSArray *)arguments resultBlock:(void (^)(sqlite3_stmt *stmt, bool *stop))resultBlock error:(NSError **)error {
    return [self executeQuery:sql stmtBlock:^(sqlite3_stmt *stmt, int idx) {
        [self _bindObject:arguments[idx-1] toColumn:idx inStatement:stmt];
    } resultBlock:resultBlock error:error];
}

- (BOOL)executeQuery:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock resultBlock:(void (^)(sqlite3_stmt *stmt, bool *stop))resultBlock error:(NSError **)error {
    NSParameterAssert(stmtBlock);
    NSParameterAssert(resultBlock);
    if (sql.length==0) return NO;
    UniStmt *stmt = [self getStmtForSql:sql error:error];
    if (!stmt) return NO;
    int count = sqlite3_bind_parameter_count(stmt.stmt);
    for (int i = 0; i < count; i++) stmtBlock(stmt.stmt, i + 1);
    bool stop = NO;
    int res=SQLITE_ROW;
    while (res==SQLITE_ROW) {
        res=sqlite3_step(stmt.stmt);
        if(res==SQLITE_ROW) resultBlock(stmt.stmt, &stop);
        else if (res==SQLITE_ERROR){
            if(error) *error=UniDBError(self.db);
        }
        if (stop) break;
    }
    [self putStmt:stmt forSql:sql];
    return YES;
}

#pragma mark--
#pragma mark-- update

- (BOOL)executeUpdate:(NSString *)sql arguments:(NSArray *)arguments error:(NSError **)error {
    return [self executeUpdate:sql stmtBlock:^(sqlite3_stmt *stmt, int idx) {
        [self _bindObject:arguments[idx-1] toColumn:idx inStatement:stmt];
    } error:error];
}

- (BOOL)executeUpdate:(NSString *)sql stmtBlock:(void (^)(sqlite3_stmt *stmt, int idx))stmtBlock error:(NSError **)error {
    if (sql.length==0) return NO;
    UniStmt *stmt = [self getStmtForSql:sql error:error];
    if (!stmt) return NO;
    int count = sqlite3_bind_parameter_count(stmt.stmt);
    for (int i = 0; i < count; i++) stmtBlock(stmt.stmt, i + 1);
    if (sqlite3_step(stmt.stmt) != SQLITE_DONE) {
        if (error) *error = UniDBError(self.db);
        [self putStmt:stmt forSql:sql];
        return NO;
    }
    [self putStmt:stmt forSql:sql];
    return YES;
}

#pragma mark--
#pragma mark--transaction

- (BOOL)beginTransaction {
    BOOL res=YES;
    self.transactionReferenceCount++;
    if (self.transactionReferenceCount == 1) res=[self executeUpdate:@"BEGIN" arguments:nil error:nil];
    return res;
}

- (BOOL)commit {
    BOOL res=YES;
    if (self.transactionReferenceCount > 0) {
        self.transactionReferenceCount--;
        if (self.transactionReferenceCount == 0) res= [self executeUpdate:@"COMMIT" arguments:nil error:nil];
    }
    return res;
}

#pragma mark--
#pragma mark-- bind object to column

- (int)_bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt *)stmt {
    int result = SQLITE_OK;
    if ((!obj) || obj == (id)kCFNull) result = sqlite3_bind_null(stmt, idx);
    else if ([obj isKindOfClass:NSNumber.class]) {
        if (strcmp([obj objCType], @encode(char)) == 0) result = sqlite3_bind_int(stmt, idx, [obj charValue]);
        else if (strcmp([obj objCType], @encode(unsigned char)) == 0) result = sqlite3_bind_int(stmt, idx, [obj unsignedCharValue]);
        else if (strcmp([obj objCType], @encode(short)) == 0) result = sqlite3_bind_int(stmt, idx, [obj shortValue]);
        else if (strcmp([obj objCType], @encode(unsigned short)) == 0) result = sqlite3_bind_int(stmt, idx, [obj unsignedShortValue]);
        else if (strcmp([obj objCType], @encode(int)) == 0) result = sqlite3_bind_int(stmt, idx, [obj intValue]);
        else if (strcmp([obj objCType], @encode(unsigned int)) == 0) result = sqlite3_bind_int64(stmt, idx, (long long)[obj unsignedIntValue]);
        else if (strcmp([obj objCType], @encode(long)) == 0) result = sqlite3_bind_int64(stmt, idx, [obj longValue]);
        else if (strcmp([obj objCType], @encode(unsigned long)) == 0) result = sqlite3_bind_int64(stmt, idx, (long long)[obj unsignedLongValue]);
        else if (strcmp([obj objCType], @encode(long long)) == 0) result = sqlite3_bind_int64(stmt, idx, [obj longLongValue]);
        else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) result = sqlite3_bind_int64(stmt, idx, (long long)[obj unsignedLongLongValue]);
        else if (strcmp([obj objCType], @encode(float)) == 0) result = sqlite3_bind_double(stmt, idx, [obj floatValue]);
        else if (strcmp([obj objCType], @encode(double)) == 0) result = sqlite3_bind_double(stmt, idx, [obj doubleValue]);
        else if (strcmp([obj objCType], @encode(bool)) == 0) result = sqlite3_bind_int(stmt, idx, ([obj boolValue] ? 1 : 0));
        else result = sqlite3_bind_text(stmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
    } else if ([obj isKindOfClass:NSData.class]) {
        const void *bytes = [obj bytes];
        if (bytes) result = sqlite3_bind_blob(stmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
        else result = sqlite3_bind_null(stmt, idx);
    } else result = sqlite3_bind_text(stmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
    return result;
}

#pragma mark--
#pragma mark-- getter

- (NSDictionary *)_dictionaryInStmt:(sqlite3_stmt *)stmt count:(int)count {
    NSMutableDictionary *set = [NSMutableDictionary dictionary];
    for (int idx = 0; idx < count; idx++) {
        NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name(stmt, idx)];
        int type = sqlite3_column_type(stmt, idx);
        id value = nil;
        switch (type) {
            case SQLITE_INTEGER: value = @(sqlite3_column_int64(stmt, idx)); break;
            case SQLITE_FLOAT: value = @(sqlite3_column_double(stmt, idx)); break;
            case SQLITE_BLOB: {
                int bytes = sqlite3_column_bytes(stmt, idx);
                value = [NSData dataWithBytes:sqlite3_column_blob(stmt, idx) length:bytes];
            } break;
            case SQLITE_NULL: break;
            default: value = [[NSString alloc] initWithCString:(const char *)sqlite3_column_text(stmt, idx) encoding:NSUTF8StringEncoding]; break;
        }
        if (value && value != (id)kCFNull) set[columnName] = value;
    }
    return set;
}

@end