text:
"""IP address pool management functions.

"""

import ipaddr

from bitarray import bitarray

from ganeti import errors

def _ComputeIpv4NumHosts(network_size):
  """Derives the number of hosts in an IPv4 network from the size.

  """
  return 2 ** (32 - network_size)

IPV4_NETWORK_MIN_SIZE = 30
# FIXME: This limit is for performance reasons. Remove when refactoring
# for performance tuning was successful.
IPV4_NETWORK_MAX_SIZE = 16
IPV4_NETWORK_MIN_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MIN_SIZE)
IPV4_NETWORK_MAX_NUM_HOSTS = _ComputeIpv4NumHosts(IPV4_NETWORK_MAX_SIZE)

class AddressPool(object):
  """Address pool class, wrapping an C{objects.Network} object.

  This class provides methods to manipulate address pools, backed by
  L{objects.Network} objects.

  """
  FREE = bitarray("0")
  RESERVED = bitarray("1")

  def __init__(self, network):
    """Initialize a new IPv4 address pool from an L{objects.Network} object.

    @type network: L{objects.Network}
    @param network: the network object from which the pool will be generated

    """
    self.network = None
    self.gateway = None
    self.network6 = None
    self.gateway6 = None

    self.net = network

    self.network = ipaddr.IPNetwork(self.net.network)
    if self.network.numhosts > IPV4_NETWORK_MAX_NUM_HOSTS:
      raise errors.AddressPoolError("A big network with %s host(s) is currently"
                                    " not supported. please specify at most a"
                                    " /%s network" %
                                    (str(self.network.numhosts),
                                     IPV4_NETWORK_MAX_SIZE))

    if self.network.numhosts < IPV4_NETWORK_MIN_NUM_HOSTS:
      raise errors.AddressPoolError("A network with only %s host(s) is too"
                                    " small, please specify at least a /%s"
                                    " network" %
                                    (str(self.network.numhosts),
                                     IPV4_NETWORK_MIN_SIZE))
    if self.net.gateway:
      self.gateway = ipaddr.IPAddress(self.net.gateway)

    if self.net.network6:
      self.network6 = ipaddr.IPv6Network(self.net.network6)
    if self.net.gateway6:
      self.gateway6 = ipaddr.IPv6Address(self.net.gateway6)

    if self.net.reservations:
      self.reservations = bitarray(self.net.reservations)
    else:
      self.reservations = bitarray(self.network.numhosts)
      # pylint: disable=E1103
      self.reservations.setall(False)

    if self.net.ext_reservations:
      self.ext_reservations = bitarray(self.net.ext_reservations)
    else:
      self.ext_reservations = bitarray(self.network.numhosts)
      # pylint: disable=E1103
      self.ext_reservations.setall(False)

    assert len(self.reservations) == self.network.numhosts
    assert len(self.ext_reservations) == self.network.numhosts

  def Contains(self, address):
    if address is None:
      return False
    addr = ipaddr.IPAddress(address)

    return addr in self.network

  def _GetAddrIndex(self, address):
    addr = ipaddr.IPAddress(address)

    if not addr in self.network:
      raise errors.AddressPoolError("%s does not contain %s" %
                                    (self.network, addr))

    return int(addr) - int(self.network.network)

  def Update(self):
    """Write address pools back to the network object.

    """
    # pylint: disable=E1103
    self.net.ext_reservations = self.ext_reservations.to01()
    self.net.reservations = self.reservations.to01()

  def _Mark(self, address, value=True, external=False):
    idx = self._GetAddrIndex(address)
    if external:
      self.ext_reservations[idx] = value
    else:
      self.reservations[idx] = value
    self.Update()

  def _GetSize(self):
    return 2 ** (32 - self.network.prefixlen)

  @property
  def all_reservations(self):
    """Return a combined map of internal and external reservations.

    """
    return (self.reservations | self.ext_reservations)

  def Validate(self):
    assert len(self.reservations) == self._GetSize()
    assert len(self.ext_reservations) == self._GetSize()

    if self.gateway is not None:
      assert self.gateway in self.network

    if self.network6 and self.gateway6:
      assert self.gateway6 in self.network6 or self.gateway6.is_link_local

  def IsFull(self):
    """Check whether the network is full.

    """
    return self.all_reservations.all()

  def GetReservedCount(self):
    """Get the count of reserved addresses.

    """
    return self.all_reservations.count(True)

  def GetFreeCount(self):
    """Get the count of unused addresses.

    """
    return self.all_reservations.count(False)

  def GetMap(self):
    """Return a textual representation of the network's occupation status.

    """
    return self.all_reservations.to01().replace("1", "X").replace("0", ".")

  def IsReserved(self, address, external=False):
    """Checks if the given IP is reserved.

    """
    idx = self._GetAddrIndex(address)
    if external:
      return self.ext_reservations[idx]
    else:
      return self.reservations[idx]

  def Reserve(self, address, external=False):
    """Mark an address as used.

    """
    if self.IsReserved(address, external):
      if external:
        msg = "IP %s is already externally reserved" % address
      else:
        msg = "IP %s is already used by an instance" % address
      raise errors.AddressPoolError(msg)

    self._Mark(address, external=external)

  def Release(self, address, external=False):
    """Release a given address reservation.

    """
    if not self.IsReserved(address, external):
      if external:
        msg = "IP %s is not externally reserved" % address
      else:
        msg = "IP %s is not used by an instance" % address
      raise errors.AddressPoolError(msg)

    self._Mark(address, value=False, external=external)

  def GetFreeAddress(self):
    """Returns the first available address.

    """
    if self.IsFull():
      raise errors.AddressPoolError("%s is full" % self.network)

    idx = self.all_reservations.index(False)
    address = str(self.network[idx])
    self.Reserve(address)
    return address

  def GenerateFree(self):
    """Returns the first free address of the network.

    @raise errors.AddressPoolError: Pool is full

    """
    idx = self.all_reservations.search(self.FREE, 1)
    if idx:
      return str(self.network[idx[0]])
    else:
      raise errors.AddressPoolError("%s is full" % self.network)

  def GetExternalReservations(self):
    """Returns a list of all externally reserved addresses.

    """
    # pylint: disable=E1103
    idxs = self.ext_reservations.search(self.RESERVED)
    return [str(self.network[idx]) for idx in idxs]

  @classmethod
  def InitializeNetwork(cls, net):
    """Initialize an L{objects.Network} object.

    Reserve the network, broadcast and gateway IP addresses.

    """
    obj = cls(net)
    obj.Update()
    for ip in [obj.network[0], obj.network[-1]]:
      obj.Reserve(ip, external=True)
    if obj.net.gateway is not None:
      obj.Reserve(obj.net.gateway, external=True)
    obj.Validate()
    return obj


text:
Mobile-WhenIsGood
=================

For Discovery Labs

redpajama_set_name: RedPajamaGithub


text:
package com.abiodunajibike.app.expensestracker.helpers;

import java.text.DecimalFormat;

/**
 * Created by AJ on 24/05/2016.
 */
public class ReUsableClasses {

    public static String formatValue(Double val){
        DecimalFormat formatter = new DecimalFormat("#,###,###");
        String formattedString = formatter.format(val);
        return formattedString;
    }

}


text:
package org.yarlithub.yschool.repository.model.obj.yschool;

import com.felees.hbnpojogen.persistence.IPojoGenEntity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Embeddable;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import org.yarlithub.yschool.repository.model.obj.yschool.iface.IClassroomModuleHasStaffHasRolePK;

/**
 * Object mapping for hibernate-handled table: classroom_module_has_staff_has_role.
 * @author autogenerated
 */

@Embeddable
public class ClassroomModuleHasStaffHasRolePK implements Cloneable, Serializable,  IClassroomModuleHasStaffHasRolePK {

	/** Serial Version UID. */
	private static final long serialVersionUID = -558977433L;

	/** Field mapping. */
	@ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY )
	@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
	@Basic( optional = false )
	@JoinColumn(name = "classroom_module_idclassroom_module", nullable = false , insertable = false, updatable = false )
	private ClassroomModule classroomModuleIdclassroomModule;

	/** Field mapping. */
	@ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY )
	@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
	@Basic( optional = false )
	@JoinColumn(name = "staff_has_role_idstaff_has_role", nullable = false , insertable = false, updatable = false )
	private StaffHasRole staffHasRoleIdstaffHasRole;

	/** Return the type of this class. Useful for when dealing with proxies.
	* @return Defining class.
	*/
	@Transient
	public Class<?> getClassType() {
		return ClassroomModuleHasStaffHasRolePK.class;
	}

    /**
     * Return the value associated with the column: classroomModuleIdclassroomModule.
	 * @return A ClassroomModule object (this.classroomModuleIdclassroomModule)
	 */
	public ClassroomModule getClassroomModuleIdclassroomModule() {
		return this.classroomModuleIdclassroomModule;

	}

    /**
     * Set the value related to the column: classroomModuleIdclassroomModule.
	 * @param classroomModuleIdclassroomModule the classroomModuleIdclassroomModule value you wish to set
	 */
	public void setClassroomModuleIdclassroomModule(final ClassroomModule classroomModuleIdclassroomModule) {
		this.classroomModuleIdclassroomModule = classroomModuleIdclassroomModule;
	}

    /**
     * Return the value associated with the column: staffHasRoleIdstaffHasRole.
	 * @return A StaffHasRole object (this.staffHasRoleIdstaffHasRole)
	 */
	public StaffHasRole getStaffHasRoleIdstaffHasRole() {
		return this.staffHasRoleIdstaffHasRole;

	}

    /**
     * Set the value related to the column: staffHasRoleIdstaffHasRole.
	 * @param staffHasRoleIdstaffHasRole the staffHasRoleIdstaffHasRole value you wish to set
	 */
	public void setStaffHasRoleIdstaffHasRole(final StaffHasRole staffHasRoleIdstaffHasRole) {
		this.staffHasRoleIdstaffHasRole = staffHasRoleIdstaffHasRole;
	}

   /**
    * Deep copy.
	* @return cloned object
	* @throws CloneNotSupportedException on error
    */
    @Override
    public ClassroomModuleHasStaffHasRolePK clone() throws CloneNotSupportedException {

        final ClassroomModuleHasStaffHasRolePK copy = (ClassroomModuleHasStaffHasRolePK)super.clone();

		return copy;
	}

	/** Provides toString implementation.
	 * @see java.lang.Object#toString()
	 * @return String representation of this class.
	 */
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();

		return sb.toString();
	}

	/** Equals implementation.
	 * @see java.lang.Object#equals(java.lang.Object)
	 * @param aThat Object to compare with
	 * @return true/false
	 */
	@Override
	public boolean equals(final Object aThat) {
		Object proxyThat = aThat;

		if ( this == aThat ) {
			 return true;
		}

		if (aThat == null)  {
			 return false;
		}

		final ClassroomModuleHasStaffHasRolePK that;
		try {
			that = (ClassroomModuleHasStaffHasRolePK) proxyThat;
			if ( !(that.getClassType().equals(this.getClassType()))){
				return false;
			}
		} catch (org.hibernate.ObjectNotFoundException e) {
				return false;
		} catch (ClassCastException e) {
				return false;
		}

		boolean result = true;
		result = result && (((getClassroomModuleIdclassroomModule() == null) && (that.getClassroomModuleIdclassroomModule() == null)) || (getClassroomModuleIdclassroomModule() != null && getClassroomModuleIdclassroomModule().getId().equals(that.getClassroomModuleIdclassroomModule().getId())));
		result = result && (((getStaffHasRoleIdstaffHasRole() == null) && (that.getStaffHasRoleIdstaffHasRole() == null)) || (getStaffHasRoleIdstaffHasRole() != null && getStaffHasRoleIdstaffHasRole().getId().equals(that.getStaffHasRoleIdstaffHasRole().getId())));
		return result;
	}

	/** Calculate the hashcode.
	 * @see java.lang.Object#hashCode()
	 * @return a calculated number
	 */
	@Override
	public int hashCode() {
	int hash = 0;
		hash = hash + getClassroomModuleIdclassroomModule().hashCode();
		hash = hash + getStaffHasRoleIdstaffHasRole().hashCode();
	return hash;
	}

}


text:
import {IApp} from '../../IApp';
import Point = minerva.Point;

declare var App: IApp;

export class OptionSubHandle {

    public Position: Point;

    public Value: number;
    public Min: number;
    public Max: number;
    public RangeMin: number;
    public RangeMax: number;
    public Setting: string;

    public Selected: boolean;

    constructor(position: Point, val: number, min: number, max: number, rangemin: number, rangemax: number, setting: string) {

        this.Position = position;
        this.Value = val;
        this.Min = min;
        this.Max = max;
        this.RangeMin = rangemin;
        this.RangeMax = rangemax;
        this.Setting = setting;

        //this.Width = this.SetPos(val);

    }

    SetVal(pos){
        var scale = (this.Max - this.Min) / (this.RangeMax - this.RangeMin);
        return (pos - this.RangeMin) * scale + this.Min;
    }

    SetPos(value){
        var scale = (this.Max - this.Min) / (this.RangeMax - this.RangeMin);
        return this.RangeMin + (value - this.Min) / scale;
    }

    Draw(ctx,x,y,size,col) {

        var w = this.Position.x;
        //console.log(w);

        App.FillColor(ctx,col);
        ctx.beginPath();
        ctx.moveTo(x - w - size, y);
        ctx.lineTo(x - w, y - size);
        ctx.lineTo(x + w, y - size);
        ctx.lineTo(x + w + size, y);
        ctx.lineTo(x + w, y + size);
        ctx.lineTo(x - w, y + size);
        ctx.closePath();
        ctx.fill();

        App.FillColor(ctx,App.Palette[8]);
        ctx.beginPath();
        ctx.moveTo(x - w - size, y);
        ctx.lineTo(x - w, y - size);
        ctx.lineTo(x - w + (size * 0.5), y - (size * 0.5));
        ctx.lineTo(x - w - (size * 0.5), y + (size * 0.5));
        ctx.closePath();
        ctx.fill();

    }

}


text:
mod monster_test_serialize_generated;
pub use monster_test_serialize_generated::my_game;

fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) {
    let mon = {
        let s0 = builder.create_string("test1");
        let s1 = builder.create_string("test2");
        let fred_name = builder.create_string("Fred");

        // can't inline creation of this Vec3 because we refer to it by reference, so it must live
        // long enough to be used by MonsterArgs.
        let pos = my_game::example::Vec3::new(
            1.0,
            2.0,
            3.0,
            3.0,
            my_game::example::Color::Green,
            &my_game::example::Test::new(5i16, 6i8),
        );

        let args = my_game::example::MonsterArgs {
            hp: 80,
            mana: 150,
            name: Some(builder.create_string("MyMonster")),
            pos: Some(&pos),
            test_type: my_game::example::Any::Monster,
            test: Some(
                my_game::example::Monster::create(
                    builder,
                    &my_game::example::MonsterArgs {
                        name: Some(fred_name),
                        ..Default::default()
                    },
                )
                .as_union_value(),
            ),
            inventory: Some(builder.create_vector(&[0u8, 1, 2, 3, 4])),
            test4: Some(builder.create_vector(&[
                my_game::example::Test::new(10, 20),
                my_game::example::Test::new(30, 40),
            ])),
            testarrayofstring: Some(builder.create_vector(&[s0, s1])),
            ..Default::default()
        };
        my_game::example::Monster::create(builder, &args)
    };
    my_game::example::finish_monster_buffer(builder, mon);
}

fn main() {
    // This test is built into its own crate because it has a different set of
    // dependencies as the normal Rust tests; it requires that the `flatbuffer`
    // dependency have the "serialize" feature enabled. As this feature may
    // cause extra code gen and dependencies for those who do not need it, it
    // is disabled by default.
    let mut builder = flatbuffers::FlatBufferBuilder::new();
    create_serialized_example_with_generated_code(&mut builder);

    let data = builder.finished_data();
    let obj = my_game::example::root_as_monster(&data[..]).unwrap();
    let value = serde_json::to_value(&obj).unwrap();
    let o = value.as_object().unwrap();

    let pos = o.get("pos").unwrap().as_object().unwrap();
    assert_eq!(pos.get("x").unwrap().as_f64().unwrap(), 1.0);
    assert_eq!(pos.get("y").unwrap().as_f64().unwrap(), 2.0);
    assert_eq!(pos.get("z").unwrap().as_f64().unwrap(), 3.0);

    let mana = o.get("mana").unwrap();
    assert_eq!(mana.as_i64().unwrap(), 150);

    let hp = o.get("hp").unwrap();
    assert_eq!(hp.as_i64().unwrap(), 80);

    let name = o.get("name").unwrap();
    assert_eq!(name.as_str().unwrap(), "MyMonster");

    let test_type = o.get("test_type").unwrap();
    assert_eq!(test_type.as_str().unwrap(), "Monster");

    let testarrayofstring = o.get("testarrayofstring").unwrap().as_array().unwrap();
    let t0 = testarrayofstring[0].as_str().unwrap();
    assert_eq!(t0, "test1");

    let t1 = testarrayofstring[1].as_str().unwrap();
    assert_eq!(t1, "test2");
}


text:
use crate::abi::Endian;
use crate::spec::{LinkerFlavor, Target, TargetOptions};

pub fn target() -> Target {
    let mut base = super::freebsd_base::opts();
    base.cpu = "ppc64".to_string();
    base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string());
    base.max_atomic_width = Some(64);

    Target {
        llvm_target: "powerpc64-unknown-freebsd".to_string(),
        pointer_width: 64,
        data_layout: "E-m:e-i64:64-n32:64".to_string(),
        arch: "powerpc64".to_string(),
        options: TargetOptions { endian: Endian::Big, mcount: "_mcount".to_string(), ..base },
    }
}


text:
'use strict';

angular.
	module('AlpGatewayApp').
		controller('BleBlindController', function($rootScope, $scope,  $http) {

			$scope.add = function(){
				console.log("add ble blind");
		    $rootScope.addMessage = "Scanning...";
				$http({
				  method: 'GET',
				  url: '/add/ble/blind'
				}).then(function successCallback(response) {
					console.log(response.data.id);
					if (response.data.id == -1)
						$rootScope.addMessage = "No new blind found";
					else
						$rootScope.addMessage = "New blind added. Id - " + response.data.id;
				}, function errorCallback(response){
					console.log("error message : " + response.data);
				});
			};

		});

angular.
	module('AlpGatewayApp').
		controller('ctrlBleBlindHome', function($rootScope, $scope,  $http) {
			$rootScope.activeDev = {id : -1};

		  $scope.delDev = function(devID, event){
		    console.log("del ble blind - " + devID);
        event.stopPropagation();
		    var idJson = {id: devID};
		    console.log(idJson);
		    var request = $http.post("/ble/blind/del", idJson).then(function successCallback(res) {
		      console.log(res.data);
		    }, function errorCallback(res) {
		      console.log( "failure message: " + res.data);
		    });
		    $scope.refreshDevices();
		  };

		  $scope.showDev = function(devID){
		    console.log("show ble blind - " + devID);
		    location.href="#/showBleBlind";
		    $rootScope.activeDev.id = devID;
		    $rootScope.waitStatus = true;
		    $rootScope.timeoutID = setTimeout($scope.getDevStatus,2000);
		  };

		  $scope.getDevStatus = function(){
		    if($rootScope.activeDev.id != -1)
		    {
		      var idJson = {id: $rootScope.activeDev.id};
		      var request = $http.post("/ble/blind/status", idJson).then(function successCallback(res) {
		        if ($rootScope.waitStatus){
		          $rootScope.waitStatus = false;
		          $rootScope.loading = false;
		        }

		        if (res.data.status == -1){
		          $rootScope.activeDev.status = false;
		          $rootScope.activeDev.noConnection = true;
		        }
		        else{
		          $rootScope.activeDev.noConnection = false;
		          $rootScope.activeDev.status = res.data.status;
		        }

		        console.log($rootScope.activeDev.status);
		      }, function errorCallback(res) {
		        console.log( "failure message: " + res.data);
		      });
		      $rootScope.timeoutID = setTimeout($scope.getDevStatus,2000);
		    }
		  };

		});

angular.
	module('AlpGatewayApp').
		controller('ctrlBleBlindShow', function($rootScope, $scope,  $http) {

			$scope.blindLeft= function(){
			  //clearTimeout($rootScope.timeoutID);
			  //$rootScope.timeoutID = setTimeout($scope.getDevStatus,3000);
		    var idJson = {id: $rootScope.activeDev.id};
			  console.log(idJson);
			  var request = $http.post("/ble/blind/turnLeft", idJson).then(function successCallback(res) {
			    console.log(res.data);
			  }, function errorCallback(res) {
			    console.log( "failure message: " + res.data);
			  });
			};

			$scope.blindRight= function(){
			  //clearTimeout($rootScope.timeoutID);
			  //$rootScope.timeoutID = setTimeout($scope.getDevStatus,3000);
		    var idJson = {id: $rootScope.activeDev.id};
			  var request = $http.post("/ble/blind/turnRight", idJson).then(function successCallback(res) {
			    console.log(res.data);
			  }, function errorCallback(res) {
			    console.log( "failure message: " + res.data);
			  });
			};

		});


text:
/**
 * Async helpers.
 */
package com.fangzhou.manatee.async;


text:
package org.casinocoin.params;

import org.casinocoin.core.Block;
import org.casinocoin.core.CoinDefinition;
import org.casinocoin.core.NetworkParameters;

import java.math.BigInteger;

/**
 * Network parameters used by the bitcoinj unit tests (and potentially your own). This lets you solve a block using
 * {@link org.casinocoin.core.Block#solve()} by setting difficulty to the easiest possible.
 */
public class UnitTestParams extends NetworkParameters {
    public UnitTestParams() {
        super();
        id = ID_UNITTESTNET;
        packetMagic = 0x0b110907;
        addressHeader = CoinDefinition.testnetAddressHeader;
        p2shHeader = CoinDefinition.testnetp2shHeader;
        acceptableAddressCodes = new int[] { addressHeader, p2shHeader };
        proofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
        genesisBlock.setTime(System.currentTimeMillis() / 1000);
        genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
        genesisBlock.solve();
        port = CoinDefinition.TestPort;
        interval = 10;
        dumpedPrivateKeyHeader = 128 + CoinDefinition.testnetAddressHeader;
        targetTimespan = 200000000;  // 6 years. Just a very big number.
        spendableCoinbaseDepth = 5;
        subsidyDecreaseBlockCount = 100;
        dnsSeeds = null;
    }

    private static UnitTestParams instance;
    public static synchronized UnitTestParams get() {
        if (instance == null) {
            instance = new UnitTestParams();
        }
        return instance;
    }

    public String getPaymentProtocolId() {
        return null;
    }
}


text:
from msrest.serialization import Model

class OdataFilter(Model):

    _required = []

    _attribute_map = {
        'id': {'key': 'id', 'type': 'int'},
        'name': {'key': 'name', 'type': 'str'},
    }

    def __init__(self, *args, **kwargs):
        """OdataFilter

        :param int id
        :param str name
        """
        self.id = None
        self.name = None

        super(OdataFilter, self).__init__(*args, **kwargs)


text:
/** @jsx React.DOM */
var React = require('react');
var Button = require('react-bootstrap').Button;
var GameStore = require('./GameStore');
var StaticDataStore = require('./StaticDataStore');
var Panel = require('react-bootstrap').Panel;
var Table = require('react-bootstrap').Table;
var ButtonToolbar = require('react-bootstrap').ButtonToolbar;
var Input = require('react-bootstrap').Input;
var AlertService = require('./AlertService');
var GamePanel = require('./GamePanel');

var GamesPanel = React.createClass({
  getInitialState: function () {
    var app = this;

    GameStore.setConsumer('load', function(gameData) {
      app.setState({games: gameData.games});
    });

    GameStore.setConsumer('delete', function(games) {
      app.setState({games: games});
    });

    GameStore.setConsumer('edit', function(games) {
      app.setState({games: games});
    });
    return {games: []};
  },

  componentWillMount: function() {
    GameStore.load();
  },

  render: function() {
    var app = this;
    var gameNodes = this.state.games.map(function (game) {
      return (
        <GamePanel game={game}/>
      );
    }.bind(this));

    return (

        Date
        Caster
        Opponent
        Result
        Details

      {gameNodes}

    );
  }
});

module.exports = GamesPanel;


text:
<?php

namespace Illuminate\Tests\Cache;

use Mockery as m;
use PHPUnit\Framework\TestCase;
use Illuminate\Cache\RedisStore;
use Illuminate\Cache\Repository;
use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;

class RedisCacheIntegrationTest extends TestCase
{
    use InteractsWithRedis;

    protected function setUp(): void
    {
        parent::setUp();
        $this->setUpRedis();
    }

    protected function tearDown(): void
    {
        parent::tearDown();
        $this->tearDownRedis();
        m::close();
    }

    /**
     * @dataProvider redisDriverProvider
     *
     * @param string $driver
     */
    public function testRedisCacheAddTwice($driver)
    {
        $store = new RedisStore($this->redis[$driver]);
        $repository = new Repository($store);
        $this->assertTrue($repository->add('k', 'v', 3600));
        $this->assertFalse($repository->add('k', 'v', 3600));
        $this->assertGreaterThan(3500, $this->redis[$driver]->connection()->ttl('k'));
    }

    /**
     * Breaking change.
     *
     * @dataProvider redisDriverProvider
     *
     * @param string $driver
     */
    public function testRedisCacheAddFalse($driver)
    {
        $store = new RedisStore($this->redis[$driver]);
        $repository = new Repository($store);
        $repository->forever('k', false);
        $this->assertFalse($repository->add('k', 'v', 60));
        $this->assertEquals(-1, $this->redis[$driver]->connection()->ttl('k'));
    }

    /**
     * Breaking change.
     *
     * @dataProvider redisDriverProvider
     *
     * @param string $driver
     */
    public function testRedisCacheAddNull($driver)
    {
        $store = new RedisStore($this->redis[$driver]);
        $repository = new Repository($store);
        $repository->forever('k', null);
        $this->assertFalse($repository->add('k', 'v', 60));
    }
}


text:
namespace MassTransit.DocumentDbIntegration.Tests
{
    using System.Threading.Tasks;
    using Log4NetIntegration.Logging;
    using NUnit.Framework;
    using Saga;

    [SetUpFixture]
    public class ContextSetup
    {
        [OneTimeSetUp]
        public async Task Before_any()
        {
            Log4NetLogger.Use("test.log4net.xml");

            await SagaRepository.Instance.Initialize();
        }
    }
}


text:
package com.zimbra.soap.admin.message;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.zimbra.common.soap.AdminConstants;
import com.zimbra.soap.type.NamedValue;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=AdminConstants.E_GET_ADMIN_SAVED_SEARCHES_RESPONSE)
public class GetAdminSavedSearchesResponse {

    /**
     * @zm-api-field-description Information on saved searches
     */
    @XmlElement(name=AdminConstants.E_SEARCH, required=false)
    private List<NamedValue> searches = Lists.newArrayList();

    public GetAdminSavedSearchesResponse() {
    }

    public void setSearches(Iterable <NamedValue> searches) {
        this.searches.clear();
        if (searches != null) {
            Iterables.addAll(this.searches,searches);
        }
    }

    public GetAdminSavedSearchesResponse addSearch(NamedValue search) {
        this.searches.add(search);
        return this;
    }

    public List<NamedValue> getSearches() {
        return Collections.unmodifiableList(searches);
    }
}


text:
<!DOCTYPE html>
<html ng-app="lb" ng-controller="MainController as m">
<head>
    <title ng-bind="pageTitle"></title>
    <link href="/css/vendor.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
    <link href="/css/app.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>

<main ui-view></main>

<script src="/js/vendor.min.js?2"></script>
<script src="/js/app.min.js?2"></script>
</body>
</html>


text:
'  This file was generated by CSLA Object Generator - CslaGenFork v4.5
'
' Filename:    DocTypeList
' ObjectType:  DocTypeList
' CSLAType:    ReadOnlyCollection

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Csla
Imports Csla.Data
Imports DocStore.Business.Util
Imports Csla.Rules
Imports Csla.Rules.CommonRules

Namespace DocStore.Business

    ''' <summary>
    ''' Collection of document type's basic information (read only list).<br/>
    ''' This is a generated base class of <see cref="DocTypeList"/> business object.
    ''' This class is a root collection.
    ''' </summary>
    ''' <remarks>
    ''' The items of the collection are <see cref="DocTypeInfo"/> objects.
    ''' </remarks>
    <Serializable>
    Public Partial Class DocTypeList
#If WINFORMS Then
        Inherits ReadOnlyBindingListBase(Of DocTypeList, DocTypeInfo)
#Else
        Inherits ReadOnlyListBase(Of DocTypeList, DocTypeInfo)
#End If

        #Region " Collection Business Methods "

        ''' <summary>
        ''' Determines whether a <see cref="DocTypeInfo"/> item is in the collection.
        ''' </summary>
        ''' <param name="docTypeID">The DocTypeID of the item to search for.</param>
        ''' <returns><c>True</c> if the DocTypeInfo is a collection item; otherwise, <c>false</c>.</returns>
        Public Overloads Function Contains(docTypeID As Integer) As Boolean
            For Each item As DocTypeInfo In Me
                If item.DocTypeID = docTypeID Then
                    Return True
                End If
            Next
            Return False
        End Function

        #End Region

        #Region " Find Methods "

        ''' <summary>
        ''' Finds a <see cref="DocTypeInfo"/> item of the <see cref="DocTypeList"/> collection, based on a given DocTypeID.
        ''' </summary>
        ''' <param name="docTypeID">The DocTypeID.</param>
        ''' <returns>A <see cref="DocTypeInfo"/> object.</returns>
        Public Function FindDocTypeInfoByDocTypeID(docTypeID As Integer) As DocTypeInfo
            For i As Integer = 0 To Me.Count - 1
                If Me(i).DocTypeID.Equals(docTypeID) Then
                    Return Me(i)
                End If
            Next i

            Return Nothing
        End Function

        #End Region

        #Region " Private Fields "

        Private Shared _list As DocTypeList

        #End Region

        #Region " Cache Management Methods "

        ''' <summary>
        ''' Clears the in-memory DocTypeList cache so it is reloaded on the next request.
        ''' </summary>
        Public Shared Sub InvalidateCache()
            _list = Nothing
        End Sub

        ''' <summary>
        ''' Used by async loaders to load the cache.
        ''' </summary>
        ''' <param name="lst">The list to cache.</param>
        Friend Shared Sub SetCache(lst As DocTypeList)
            _list = lst
        End Sub

        Friend Shared ReadOnly Property IsCached As Boolean
            Get
                Return _list IsNot Nothing
            End Get
        End Property

        #End Region

        #Region " Factory Methods "

        ''' <summary>
        ''' Factory method. Loads a <see cref="DocTypeList"/> collection.
        ''' </summary>
        ''' <returns>A reference to the fetched <see cref="DocTypeList"/> collection.</returns>
        Public Shared Function GetDocTypeList() As DocTypeList
            If _list Is Nothing Then
                _list = DataPortal.Fetch(Of DocTypeList)()
            End If

            Return _list
        End Function

        ''' <summary>
        ''' Factory method. Loads a <see cref="DocTypeList"/> collection, based on given parameters.
        ''' </summary>
        ''' <param name="docTypeName">The DocTypeName parameter of the DocTypeList to fetch.</param>
        ''' <returns>A reference to the fetched <see cref="DocTypeList"/> collection.</returns>
        Public Shared Function GetDocTypeList(docTypeName As String) As DocTypeList
            Return DataPortal.Fetch(Of DocTypeList)(docTypeName)
        End Function

        ''' <summary>
        ''' Factory method. Asynchronously loads a <see cref="DocTypeList"/> collection.
        ''' </summary>
        ''' <param name="callback">The completion callback method.</param>
        Public Shared Sub GetDocTypeList(ByVal callback As EventHandler(Of DataPortalResult(Of DocTypeList)))
            If _list Is Nothing Then
                DataPortal.BeginFetch(Of DocTypeList)(Sub(o, e)
                        _list = e.Object
                        callback(o, e)
                    End Sub)
            Else
                callback(Nothing, New DataPortalResult(Of DocTypeList)(_list, Nothing, Nothing))
            End If
        End Sub

        ''' <summary>
        ''' Factory method. Asynchronously loads a <see cref="DocTypeList"/> collection, based on given parameters.
        ''' </summary>
        ''' <param name="docTypeName">The DocTypeName parameter of the DocTypeList to fetch.</param>
        ''' <param name="callback">The completion callback method.</param>
        Public Shared Sub GetDocTypeList(docTypeName As String, ByVal callback As EventHandler(Of DataPortalResult(Of DocTypeList)))
            DataPortal.BeginFetch(Of DocTypeList)(docTypeName, callback)
        End Sub

        #End Region

        #Region " Constructor "

        ''' <summary>
        ''' Initializes a new instance of the <see cref="DocTypeList"/> class.
        ''' </summary>
        ''' <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
        Public Sub New()
            ' Use factory methods and do not use direct creation.

            Dim rlce = RaiseListChangedEvents
            RaiseListChangedEvents = False
            AllowNew = False
            AllowEdit = False
            AllowRemove = False
            RaiseListChangedEvents = rlce
        End Sub

        #End Region

        #Region " Object Authorization "

        ''' <summary>
        ''' Adds the object authorization rules.
        ''' </summary>
        Protected Shared Sub AddObjectAuthorizationRules()
            BusinessRules.AddRule(GetType(DocTypeList), New IsInRole(AuthorizationActions.GetObject, "User"))

            AddObjectAuthorizationRulesExtend()
        End Sub

        ''' <summary>
        ''' Allows the set up of custom object authorization rules.
        ''' </summary>
        Partial Private Shared Sub AddObjectAuthorizationRulesExtend()
        End Sub

        ''' <summary>
        ''' Checks if the current user can retrieve DocTypeList's properties.
        ''' </summary>
        ''' <returns><c>True</c> if the user can read the object; otherwise, <c>false</c>.</returns>
        Public Overloads Shared Function CanGetObject() As Boolean
            Return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, GetType(DocTypeList))
        End Function

        #End Region

        #Region " Data Access "

        ''' <summary>
        ''' Loads a <see cref="DocTypeList"/> collection from the database or from the cache.
        ''' </summary>
        Protected Overloads Sub DataPortal_Fetch()
            If IsCached Then
                LoadCachedList()
                Exit Sub
            End If

            Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.DocStoreConnection, False)
                Using cmd = New SqlCommand("GetDocTypeList", ctx.Connection)
                    cmd.CommandType = CommandType.StoredProcedure
                    Dim args As New DataPortalHookArgs(cmd)
                    OnFetchPre(args)
                    LoadCollection(cmd)
                    OnFetchPost(args)
                End Using
            End Using
            _list = Me
        End Sub

        Private Sub LoadCachedList()
            IsReadOnly = False
            Dim rlce = RaiseListChangedEvents
            RaiseListChangedEvents = False
            AddRange(_list)
            RaiseListChangedEvents = rlce
            IsReadOnly = True
        End Sub

        ''' <summary>
        ''' Loads a <see cref="DocTypeList"/> collection from the database, based on given criteria.
        ''' </summary>
        ''' <param name="docTypeName">The Doc Type Name.</param>
        Protected Overloads Sub DataPortal_Fetch(docTypeName As String)
            Using ctx = ConnectionManager(Of SqlConnection).GetManager(Database.DocStoreConnection, False)
                Using cmd = New SqlCommand("GetDocTypeList", ctx.Connection)
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@DocTypeName", docTypeName).DbType = DbType.String
                    Dim args As New DataPortalHookArgs(cmd, docTypeName)
                    OnFetchPre(args)
                    LoadCollection(cmd)
                    OnFetchPost(args)
                End Using
            End Using
        End Sub

        Private Sub LoadCollection(cmd As SqlCommand)
            Using dr As New SafeDataReader(cmd.ExecuteReader())
                Fetch(dr)
            End Using
        End Sub

        ''' <summary>
        ''' Loads all <see cref="DocTypeList"/> collection items from the given SafeDataReader.
        ''' </summary>
        ''' <param name="dr">The SafeDataReader to use.</param>
        Private Sub Fetch(dr As SafeDataReader)
            IsReadOnly = False
            Dim rlce = RaiseListChangedEvents
            RaiseListChangedEvents = False
            While dr.Read()
                Add(DocTypeInfo.GetDocTypeInfo(dr))
            End While
            RaiseListChangedEvents = rlce
            IsReadOnly = True
        End Sub

        #End Region

        #Region " DataPortal Hooks "

        ''' <summary>
        ''' Occurs after setting query parameters and before the fetch operation.
        ''' </summary>
        Partial Private Sub OnFetchPre(args As DataPortalHookArgs)
        End Sub

        ''' <summary>
        ''' Occurs after the fetch operation (object or collection is fully loaded and set up).
        ''' </summary>
        Partial Private Sub OnFetchPost(args As DataPortalHookArgs)
        End Sub

        #End Region

    End Class
End Namespace


text:
ul, li {
  list-style-type: none;
  margin: auto;
  padding: 0;
}
.carousel {
  position: relative;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.circle {
  border-radius: 50%;
  background-color: blue;
}

.circle.selected {
  background-color: orange;
}

.carousel .slidesArea {
  overflow: hidden;
}
.carousel .slidesArea > * {
  float: left;
}

.carousel .slidesArea .slidesViewPort {
  position: relative;
  overflow: hidden;
}

.carousel .slidesArea .slidesViewPort ul, .carousel .slidesArea .viewPort ul li {
  display: block;
  padding: 0;
  margin: 0;
}

.carousel .slidesArea .slidesViewPort ul {
  position: relative;
  transition-duration: 0.5s;
  transition-timing-function: ease-in;
}

.carousel .slidesArea .slidesViewPort ul li {
  position: absolute;
}

.carousel .slidesArea .slidesViewPort ul li img {
  width: 100%;
}

.slideButtons li {
  float: left;
  cursor: pointer;
}


text:
package sample;

import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

    private static final double ANIM_TIME = 4;

    public void init(Stage stage) {
        Pane pane = new Pane();
        Scene scene = new Scene(pane, 500, 300);
        stage.setScene(scene);

        ImageView imgRocket = new ImageView("rocket.png");
        imgRocket.setX(0);
        imgRocket.setY(200);
        imgRocket.setRotate(-45);

        RotateTransition a1 = new RotateTransition(Duration.seconds(ANIM_TIME), imgRocket);
        a1.setByAngle(180);

        TranslateTransition a2 = new TranslateTransition(Duration.seconds(ANIM_TIME), imgRocket);
        a2.setToX(400);

        TranslateTransition a3 = new TranslateTransition(Duration.seconds(ANIM_TIME/2), imgRocket);
        a3.setByY(-200);
        a3.setInterpolator(Interpolator.EASE_OUT);

        TranslateTransition a4 = new TranslateTransition(Duration.seconds(ANIM_TIME/2), imgRocket);
        a4.setByY(200);
        a4.setInterpolator(Interpolator.EASE_IN);

        SequentialTransition s1 = new SequentialTransition(a3, a4);

        Circle rect = new Circle(20, 20, 30);
        rect.setCenterX(200);
        rect.setCenterY(200);
        rect.setFill(Color.GREEN);

        FillTransition a5 = new FillTransition(Duration.seconds(ANIM_TIME), rect);
        a5.setToValue(Color.RED);
        a5.play();

        ParallelTransition parallelTransition = new ParallelTransition(a1, a2, s1, a5);
        parallelTransition.setCycleCount(Animation.INDEFINITE);
        parallelTransition.setDelay(Duration.millis(1000));
        parallelTransition.setAutoReverse(true);
        parallelTransition.play();

        pane.getChildren().add(imgRocket);
        pane.getChildren().add(rect);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.setTitle("AnimationDemo1");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
Шифрование информации

                        Введите 10 - битовый ключ
                        <input type="text"
                               class="form-control"
                               placeholder="Введите ключ..."
                               ng-maxlength="10"
                               maxlength="10"
                               ng-model="vm.key">

                        Текстовое сообщение
                        <textarea class="form-control"
                                  rows="5"
                                  placeholder="Текстовое сообщение..."
                                  ng-model="vm.messageToEncrypt"></textarea>

Зашифрованное сообщение

                            {{ vm.encryptedMessage }}

                        Зашифровать сообщение

Расшифрование информации

                        Ключ
                        <input type="text"
                               class="form-control"
                               placeholder="Введите ключ..."
                               ng-model="vm.keyToDecrypt">

                        Зашифрованное сообщение
                        <textarea class="form-control"
                                  rows="5"
                                  placeholder="Зашифрованное сообщение..."
                                  ng-model="vm.messageToDecrypt"></textarea>

Расшифрованное сообщение

                            {{ vm.decryptedMessage }}

                        Расшифровать сообщение


text:
package com.chaocodes.restapi;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import com.chaocodes.restapi.model.User;
import com.chaocodes.restapi.repository.UserRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class UserControllerTest extends ControllerTest
{
	private MockMvc mockMvc;

	private String baseUrl = "/user";

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private WebApplicationContext webApplicationContext;

	private User testUser;

	@Before
	public void setup() throws Exception {
		mockMvc = webAppContextSetup(webApplicationContext).build();

		userRepository.deleteAll();
		testUser = userRepository.save(new User("test@test.com", "test"));
	}

	@Test
	public void createOneUser() throws Exception {
		String email = "testpost@test.com";
		String username = "testpost";
		User createUser = new User(email, username);
		mockMvc.perform(post(baseUrl)
			.content(json(createUser))
			.contentType(contentType))
			.andExpect(status().isCreated());
		User checkUser = userRepository.findByUsername(username);
		Assert.assertNotNull(checkUser);
		Assert.assertEquals(email, checkUser.getEmail());
	}

	@Test
	public void readAllUsers() throws Exception {
		mockMvc.perform(get(baseUrl))
			.andExpect(status().isOk())
			.andExpect(content().contentType(contentType))
			.andExpect(jsonPath("$", hasSize(1)))
			.andExpect(jsonPath("$[0].id", is(testUser.getId().intValue())))
			.andExpect(jsonPath("$[0].email", is(testUser.getEmail())))
			.andExpect(jsonPath("$[0].username", is(testUser.getUsername())))
			.andExpect(jsonPath("$[0].owner", is(testUser.isOwner())));
	}

	@Test
	public void readOneUser() throws Exception {
		mockMvc.perform(get(baseUrl + "/" + testUser.getId()))
			.andExpect(status().isOk())
			.andExpect(content().contentType(contentType))
			.andExpect(jsonPath("$.id", is(testUser.getId().intValue())))
			.andExpect(jsonPath("$.email", is(testUser.getEmail())))
			.andExpect(jsonPath("$.username", is(testUser.getUsername())))
			.andExpect(jsonPath("$.owner", is(testUser.isOwner())));
	}

	@Test
	public void readOneUserNotFound() throws Exception {
		mockMvc.perform(get(baseUrl + "/5"))
			.andExpect(status().isNotFound());
	}

	@Test
	public void updateOneUser() throws Exception {
		User updateUser = userRepository.save(new User("testupdate@test.com", "testupdate"));
		User updatedUser = new User("testupdated@test.com", "testupdated");
		mockMvc.perform(put(baseUrl + "/" + updateUser.getId())
			.content(json(updatedUser))
			.contentType(contentType))
			.andExpect(status().isOk());
		User checkUser = userRepository.findOne(updateUser.getId());
		Assert.assertNotNull(checkUser);
		Assert.assertEquals(updatedUser.getEmail(), checkUser.getEmail());
		Assert.assertEquals(updatedUser.getUsername(), checkUser.getUsername());
	}

	@Test
	public void deleteOneUser() throws Exception {
		User deleteUser = userRepository.save(new User("testdelete@test.com", "testdelete"));
		mockMvc.perform(delete(baseUrl + "/" + deleteUser.getId()))
			.andExpect(status().isNoContent());
		User checkUser = userRepository.findOne(deleteUser.getId());
		Assert.assertNull(checkUser);
	}
}


text:
#ifndef XSIMD_SVE_REGISTER_HPP
#define XSIMD_SVE_REGISTER_HPP

#include "xsimd_generic_arch.hpp"
#include "xsimd_register.hpp"

#if XSIMD_WITH_SVE
#include <arm_sve.h>
#endif

namespace xsimd
{
    namespace detail
    {
        /**
         * @ingroup arch
         *
         * SVE instructions (fixed vector size) for arm64
         */
        template <size_t Width>
        struct sve : xsimd::generic
        {
            static constexpr bool supported() noexcept { return Width == XSIMD_SVE_BITS; }
            static constexpr bool available() noexcept { return true; }
            static constexpr bool requires_alignment() noexcept { return true; }
            static constexpr std::size_t alignment() noexcept { return 16; }
            static constexpr unsigned version() noexcept { return generic::version(9, 0, 0); }
            static constexpr char const* name() noexcept { return "arm64+sve"; }
        };
    }

#if XSIMD_WITH_SVE

    using sve = detail::sve<__ARM_FEATURE_SVE_BITS>;

    namespace types
    {
        namespace detail
        {
// define fixed size alias per SVE sizeless type
#define SVE_TO_FIXED_SIZE(ty) ty __attribute__((arm_sve_vector_bits(__ARM_FEATURE_SVE_BITS)))
            using sve_int8_t = SVE_TO_FIXED_SIZE(svint8_t);
            using sve_uint8_t = SVE_TO_FIXED_SIZE(svuint8_t);
            using sve_int16_t = SVE_TO_FIXED_SIZE(svint16_t);
            using sve_uint16_t = SVE_TO_FIXED_SIZE(svuint16_t);
            using sve_int32_t = SVE_TO_FIXED_SIZE(svint32_t);
            using sve_uint32_t = SVE_TO_FIXED_SIZE(svuint32_t);
            using sve_int64_t = SVE_TO_FIXED_SIZE(svint64_t);
            using sve_uint64_t = SVE_TO_FIXED_SIZE(svuint64_t);
            using sve_float32_t = SVE_TO_FIXED_SIZE(svfloat32_t);
            using sve_float64_t = SVE_TO_FIXED_SIZE(svfloat64_t);
            using sve_bool_t = SVE_TO_FIXED_SIZE(svbool_t);
#undef SVE_TO_FIXED_SIZE

            template <size_t S>
            struct sve_vector_type_impl;

            template <>
            struct sve_vector_type_impl<8>
            {
                using signed_type = sve_int8_t;
                using unsigned_type = sve_uint8_t;
                using floating_point_type = void;
            };

            template <>
            struct sve_vector_type_impl<16>
            {
                using signed_type = sve_int16_t;
                using unsigned_type = sve_uint16_t;
                using floating_point_type = void;
            };

            template <>
            struct sve_vector_type_impl<32>
            {
                using signed_type = sve_int32_t;
                using unsigned_type = sve_uint32_t;
                using floating_point_type = sve_float32_t;
            };

            template <>
            struct sve_vector_type_impl<64>
            {
                using signed_type = sve_int64_t;
                using unsigned_type = sve_uint64_t;
                using floating_point_type = sve_float64_t;
            };

            template <class T>
            using signed_int_sve_vector_type = typename sve_vector_type_impl<8 * sizeof(T)>::signed_type;

            template <class T>
            using unsigned_int_sve_vector_type = typename sve_vector_type_impl<8 * sizeof(T)>::unsigned_type;

            template <class T>
            using floating_point_sve_vector_type = typename sve_vector_type_impl<8 * sizeof(T)>::floating_point_type;

            template <class T>
            using signed_int_or_floating_point_sve_vector_type = typename std::conditional<std::is_floating_point<T>::value,
                                                                                floating_point_sve_vector_type<T>,
                                                                                signed_int_sve_vector_type<T>>::type;

            template <class T>
            using sve_vector_type = typename std::conditional<std::is_signed<T>::value,
                                                              signed_int_or_floating_point_sve_vector_type<T>,
                                                              unsigned_int_sve_vector_type<T>>::type;
        } // namespace detail

        XSIMD_DECLARE_SIMD_REGISTER(signed char, sve, detail::sve_vector_type<signed char>);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned char, sve, detail::sve_vector_type<unsigned char>);
        XSIMD_DECLARE_SIMD_REGISTER(char, sve, detail::sve_vector_type<char>);
        XSIMD_DECLARE_SIMD_REGISTER(short, sve, detail::sve_vector_type<short>);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned short, sve, detail::sve_vector_type<unsigned short>);
        XSIMD_DECLARE_SIMD_REGISTER(int, sve, detail::sve_vector_type<int>);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned int, sve, detail::sve_vector_type<unsigned int>);
        XSIMD_DECLARE_SIMD_REGISTER(long int, sve, detail::sve_vector_type<long int>);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned long int, sve, detail::sve_vector_type<unsigned long int>);
        XSIMD_DECLARE_SIMD_REGISTER(long long int, sve, detail::sve_vector_type<long long int>);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned long long int, sve, detail::sve_vector_type<unsigned long long int>);
        XSIMD_DECLARE_SIMD_REGISTER(float, sve, detail::sve_vector_type<float>);
        XSIMD_DECLARE_SIMD_REGISTER(double, sve, detail::sve_vector_type<double>);

        namespace detail
        {
            struct sve_bool_simd_register
            {
                using register_type = sve_bool_t;
                register_type data;
                operator register_type() const noexcept { return data; }
            };
        } // namespace detail

        template <class T>
        struct get_bool_simd_register<T, sve>
        {
            using type = detail::sve_bool_simd_register;
        };
    } // namespace types
#endif
} // namespace xsimd

#endif


text:
import { Component, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import { AppSandbox } from '../../app.sandbox';

@Component({
  selector: 'app-root',
  encapsulation: ViewEncapsulation.None,
  template: `
    <app-navbar (logout)="onLogout()" [account]="account$|async" *ngIf="authenticated$|async"></app-navbar>
    <router-outlet></router-outlet>
    <app-spinner [spin]="isBusy$|async"></app-spinner>
  `,
  styleUrls: ['./app.component.less']
})
export class AppComponent {
  authenticated$ = this.sb.authenticated$;
  isBusy$ = this.sb.isBusy$;
  account$ = this.sb.account$;

  constructor(private router: Router, private sb: AppSandbox) {
    this.sb.checkInitialAuthentication();
    this.authenticated$
      .filter(item => item)
      .subscribe(() => {
        this.sb.fetchAll();
      });
  }

  onLogout(): void {
    this.sb.logout();
    this.router.navigate(['/authentication']);
  }
}


text:
About:
This project is written in Swift 3 and is meant to supplement the UISlider functionality by adding two knobs, thus allowing the use of a range.

How To Use

1. Add the UIRangeSlider.swift file to your project
2. Add a UIView in your Storyboard using drag and drop
3. Change the class of the UIView to UIRangeSlider in left panel -> Identity Inspector
4. Adjust the settings you want in the left panel -> Attributes Inspector
5. Used Drag and drop to set the delegate of the newly created UIRangeSlider to your files owner

![Demo Project](https://drive.google.com/file/d/0B4f7KioAL2tPZll2TFY0Q3poUDQ/view?usp=sharing)


text:
/* This class get a token of cognitive service api.
 * http://docs.microsofttranslator.com/oauth-token.html
 * Get access token sample code from Microsoft.
 * https://github.com/MicrosoftTranslator/GetAzureToken/blob/master/AzureAuthToken.cs
 * Special thanks to @beachside
 * Cognitive Services でのAPIの 認証 処理 ( Microsoft Cognitive Services ) - BEACHSIDE BLOG
 * http://beachside.hatenablog.com/entry/2017/01/27/123000
 */
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NetStandardLibrary
{
    public class AuthenticationToken : IDisposable
    {
        private const string TokenUri = @"https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
        private static readonly HttpClient Client;

        static AuthenticationToken()
        {
            Client = new HttpClient();
        }

        public static async Task<string> GetBearerTokenAsync(string apiKey)
        {
            var token = await GetTokenAsync(apiKey);
            //"Bearer "を付与してリターンしてます。
            return $"Bearer {token}";
        }

        private static async Task<string> GetTokenAsync(string apiKey)
        {
            Client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
            var resuponse = await Client.PostAsync(TokenUri, new StringContent(string.Empty));
            return await resuponse.Content.ReadAsStringAsync();
        }

        public void Dispose()
        {
            //TODO Dispose support !
        }
    }
}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
<<<<<<< HEAD
    [EHPlainAlert updateAlertPosition:EHPlainAlertPositionTop];
=======
    [EHPlainAlert updateAlertPosition:ViewAlertPositionBottom];
    [EHPlainAlert updateShouldShowCloseIcon:NO];
>>>>>>> josshad/master
//    [EHPlainAlert updateTitleFont:[UIFont fontWithName:@"TrebuchetMS" size:18]];
//    [EHPlainAlert updateSubTitleFont:[UIFont fontWithName:@"TrebuchetMS" size:10]];
//    [EHPlainAlert updateNumberOfAlerts:4];
//    [EHPlainAlert updateAlertColor:[UIColor colorWithWhite:0 alpha:0.5] forType:ViewAlertPanic];
//    [EHPlainAlert updateHidingDelay:2.5f];
//    [EHPlainAlert updateAlertIcon:nil forType:ViewAlertInfo];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}

- (IBAction)successAlert:(id)sender
{
    [EHPlainAlert showAlertWithTitle:@"Success" message:@"Something works!" type:EHPlainAlertSuccess];
}

- (IBAction)failureAlert:(id)sender
{
    NSError * error = [[NSError alloc] initWithDomain:@"My domain"
                                                 code:1337
                                             userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Operation was unsuccessful.", nil),
                                                        NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"The operation timed out.", nil),
                                                        NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Have you tried turning it off and on again?", nil)}];
    [EHPlainAlert showError:error];
}

- (IBAction)infoAlert:(id)sender
{
    EHPlainAlert * ehAlert = [[EHPlainAlert alloc] initWithTitle:@"Info" message:@"This is info message" type:EHPlainAlertInfo];
    ehAlert.titleFont = [UIFont fontWithName:@"TrebuchetMS" size:15];
    ehAlert.subTitleFont = [UIFont fontWithName:@"TrebuchetMS-Italic" size:12];
    ehAlert.shouldShowCloseIcon = YES;
    [ehAlert show];

}

- (IBAction)panicAlert:(id)sender
{
    [EHPlainAlert showAlertWithTitle:@"Panic!" message:@"Something brokе!" type:EHPlainAlertPanic];
}

- (IBAction)infoWithSafari:(id)sender
{
    EHPlainAlert * ehAlert = [[EHPlainAlert alloc] initWithTitle:@"Hmm..." message:@"Tap for information" type:EHPlainAlertInfo];
    ehAlert.action = ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://github.com/josshad/EHPlainAlert"]];
    };
    ehAlert.messageColor = [UIColor blueColor];
    ehAlert.iconImage = nil;
    [ehAlert show];
}

- (IBAction)hideAll:(id)sender
{
    [EHPlainAlert hideAll:YES];
}
@end


text:
<!DOCTYPE html>

        <title>Conversational Technologies Natural Language Service</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <link href="css/ct.css" rel="stylesheet" type="text/css">

Conversational Technologies

Speech Recognition Demo

            with W3C Multimodal Standards

Speech Recognition

                    This demo uses the Web Speech API and creates EMMA documents from the results. You will need to use the Chrome browser.

                    Language
                    <select id="selectLanguage">
                        <option value="en-US">English</option>
                        <option value="cmn-Hans">Chinese</option>
                        <option value="fr-FR">French</option>
                        <option value="de-DE">German</option>
                        <option value="it-IT">Italian</option>
                        <option value="ja-JP">Japanese</option>
                         <option value="pt-PT">Portuguese</option>
                        <option value="es-MX">Spanish</option>
                    </select>

                        Number of speech recognition results to return
                    <input type="text" size="4" value="1" id="maxNbest"/>

                    <button type="button" class="ctButton" id="startReco" name="startReco" onclick="turnOnRecognition()">Start Recognition</button>
                    <button type="button" class="ctButton" id="stopReco" name="stopReco" onclick="turnOffRecognition()">Stop Recognition</button>

                <form name="analyzePost">
                        Speech recognition results:

                        <textarea name="messageTextPost" rows="10" wrap="soft" class="ctTextDisplay" id="messageTextPost"></textarea>

                        <button type="button" class="ctButton" id="showXML" name="showXML" onclick="toggleShowXMLResult();">Show MMI Event result</button>
                        <button type="button" class="ctButton" id="clearText" name="clearText" onclick="clearInput();">Clear Input</button>

                    </form>

                    <form name="eventLog">
                        Event Log
                        <textarea rows="10" wrap="soft" class="ctTextDisplay" id="events"></textarea>
                        <button type="button" class="ctButton" name="post" onclick="clearEventLog();">Clear Events</button>
                    </form>

Result

                    <textarea class="ctTextDisplay" id="output" rows="10"></textarea>


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

	<name>Spring Boot Web Secure Sample</name>
	<description>Treinamento 1 </description>
	<url>http://gamas.com.br/</url>

	<groupId>br.com.gamas.treinamento</groupId>
	<artifactId>app-treinamento-1</artifactId>
	<version>0.0.2</version>
	<!-- <packaging>jar</packaging> -->

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.6.RELEASE</version>
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
class AddMissingAuthTableIndexes < ActiveRecord::Migration
  def up
    add_index "investigation_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_inv_user_id_asset_id_can_view"
    add_index "presentation_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_presentation_user_id_asset_id_can_view"
    add_index "publication_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_pub_user_id_asset_id_can_view"
    add_index "sample_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_sample_user_id_asset_id_can_view"
    add_index "specimen_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_spec_user_id_asset_id_can_view"
    add_index "strain_auth_lookup", ["user_id", "asset_id", "can_view"],:name=>"index_strain_user_id_asset_id_can_view"
  end

  def down
    remove_index "investigation_auth_lookup", :name=>"index_inv_user_id_asset_id_can_view"
    remove_index "presentation_auth_lookup", :name=>"index_presentation_user_id_asset_id_can_view"
    remove_index "publication_auth_lookup", :name=>"index_pub_user_id_asset_id_can_view"
    remove_index "sample_auth_lookup", :name=>"index_sample_user_id_asset_id_can_view"
    remove_index "specimen_auth_lookup", :name=>"index_spec_user_id_asset_id_can_view"
    remove_index "strain_auth_lookup", :name=>"index_strain_user_id_asset_id_can_view"
  end
end


text:
<?php
    // This php file receive POST request from client and add new score to the score table.
    if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
        if (isset($_POST['Name']) AND isset($_POST["description"]) AND isset($_POST["achieve"])) {
            $user = $_POST["Name"];
            $achieve = $_POST["achieve"];
            $description = $_POST["description"];

            $servername = "localhost";
            $loginName = "tyler637_dolos";
            $loginPass = "Dolos123";
            $db = "tyler637_dolos";

            // Create connection
            $conn = new mysqli($servername, $loginName, $loginPass, $db);

            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }

            //$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
            $sql = "INSERT INTO Achievement VALUES (NULL,'".$achieve."', '".$description."', '".$user."', CURRENT_TIMESTAMP)";
            $result = $conn->query($sql);

            $conn->close();
        }
    } else
        echo "Website doesn't support get request";
?>


text:
typedef void(^VideoBlock)(NSURL *url, NSError *error);

@interface MAGVideoCreator : NSObject

@property (strong, nonatomic) VideoBlock didVideoCreationFinishedBlock;

+ (NSString *)videosDestinationPath;
+ (CVPixelBufferRef)pixelBufferFromImage:(UIImage *)sourceImage contextScaleWhereThemCreated:(CGFloat)contextScale;

- (void)createVideoWithImageSize:(CGSize)imageSize contextScaleWhereThemCreated:(CGFloat)contextScale fpsWithWhichScreenshotsTaken:(ScreenshotTakingFPS)takingFPS;
- (void)addImage:(UIImage *)image;
- (void)finishVideoCreation;

@end


text:
import nltk
import random

WORD_TERMINATORS = ['.', '!', '?']
SPLIT_SYMBOLS = [',', ';']
VALID_SYMBOLS = WORD_TERMINATORS + SPLIT_SYMBOLS

class PhraseGenerator(object):
    '''A simple Phrase Generator.
    Starting with a simple input Text corpa,
    creates a Conditional Frequency Distribution (CDF), and
    then allows you to call this module with a word and optional
    number of words you'd like in the sentence.

    This lets you produce likely phrases given a source word and the author's
    style of writing.
    >>> gen = PhraseGenerator(nltk.corpus.brown)
    >>> print gen('living')

    You can also provide a keyword
    >>> gen = PhraseGenerator(nltk.corpus.brown, categories='news')
    >>> print gen('news')

    Or a specific file
    >>> gen = PhraseGenerator(nltk.corpus.inaugural, '2009-Obama.txt')
    >>> print gen('i')
    >>> print gen('you')

    Note that some randomization is involved, so you may get different results
    if you run the same request twice

    You can also pass in your own text blob directly, creating your own
    style.
    '''

    def __init__(self, corpa, *args, **kwargs):
        '''Initialize the PhraseGenerator with a starting corpus. This can
        be either a text blob, or a Class that responds to functions
        "words" and "sents", with optional args and kwargs as passed in to this initializer
        '''
        # nltk.data.path = ['nltk_data']
        # nltk.data.path.append('nltk_data')

        if isinstance(corpa, basestring):
            words = nltk.word_tokenize(corpa)
            sents = nltk.sent_tokenize(corpa)
        else:
            words = corpa.words(*args, **kwargs)
            sents = corpa.sents(*args, **kwargs)
        bigrams = nltk.bigrams([w.lower() for w in words])
        self.cdf = nltk.ConditionalFreqDist(bigrams)
        self.case_cdf = nltk.ConditionalFreqDist([(w.lower(), w) for w in words])
        self.avg_sent_len = int(len(words) / len(sents))

    def __call__(self, word):
        '''Produces a likely phrase based on the initial "seed word" provided
        :param word: Seed word to start the phrase with
        :type word: str

        :return: A likely string that would come from this corpa, based on the seed word
        :rtype: str
        '''
        word = word.lower()
        if ' ' in word:
            ret = nltk.word_tokenize(word)
            word = ret[-1]
        else:
            ret = [word]
        while word not in WORD_TERMINATORS:
            if ret[-1] in SPLIT_SYMBOLS:
                prev_word = ret[-1]
            else:
                prev_word = ret[-1]
            for new_word in self.cdf[word]:
                # Don't duplicate words
                if new_word == word:
                    continue
                # Don't accept any symbols
                if not (new_word.isalpha() or new_word.isdigit()) and not new_word in VALID_SYMBOLS:
                    continue
                # Don't allow the sentence to be less then half
                # of the average sentence length
                if new_word in WORD_TERMINATORS and len(ret) < self.avg_sent_len / 2:
                    continue
                if not new_word in ret[-len(ret) / 2:]:
                    prev_phrase = [prev_word, new_word]
                    if not ' '.join(prev_phrase) in ' '.join(ret):
                        # If this word is less then 4 characters
                        # and so was the previous one, on average we skip it,
                        # with only a small chance to keep it
                        if not (len(new_word) < 4 and (len(prev_word) < 4) and not random.randint(0, 6)):
                            word = new_word
                            # Randomly we'll try to skip this word, but we set our previous match to this
                            # just in case we don't find a new one
                            if not random.randint(0, 2):
                                break
            if word == ret[-1]:
                ret.append('...')
                break
            ret.append(word)

        for x, w in enumerate(ret[:]):
            d = self.case_cdf[w]
            if d:
                ret[x] = d.max()
        ret = ' '.join(ret)

        ret = ret[0].upper() + ret[1:]

        for symbol in VALID_SYMBOLS:
            ret = ret.replace(' %s' % symbol, symbol)
        return ret


text:
package fr.opensagres.xdocreport.samples.docxandfreemarker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;

public class DocxNativeLineBreakAndTabWithFreemarker
{

    public static void main( String[] args )
    {
        try
        {
            // 1) Load Docx file by filling Freemarker template engine and cache
            // it to the registry
            InputStream in =
                DocxNativeLineBreakAndTabWithFreemarker.class.getResourceAsStream( "DocxNativeLineBreakAndTabWithFreemarker.docx" );
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport( in, TemplateEngineKind.Freemarker );

            // 2) Create context Java model
            IContext context = report.createContext();

            context.put( "comments", "aaa\tbbb\nccc\n\nddd\n\teeee\n\t\tfff\n\nggg\t\thhh" );

            // 3) Generate report by merging Java model with the Docx
            OutputStream out = new FileOutputStream( new File( "DocxNativeLineBreakAndTabWithFreemarker_Out.docx" ) );
            report.process( context, out );

        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
        catch ( XDocReportException e )
        {
            e.printStackTrace();
        }
    }
}


text:
@import "http://fonts.googleapis.com/css?family=Droid+Sans";

/*# sourceMappingURL=input.css.map */


text:
.class public Lcom/htc/painting/pal/LaunchedWinInfo;
.super Ljava/lang/Object;
.source "LaunchedWinInfo.java"

# instance fields
.field public final mPackageName:Ljava/lang/String;

.field public final mPenWorkingMode:I

.field public final mTitle:Ljava/lang/String;

.field public final mWindowType:I

# direct methods
.method public constructor <init>(Ljava/lang/String;Ljava/lang/String;II)V
    .locals 0
    .parameter "pkgName"
    .parameter "title"
    .parameter "penMode"
    .parameter "type"

    .prologue
    .line 27
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 28
    if-nez p1, :cond_0

    const-string p1, ""

    .end local p1
    :cond_0
    iput-object p1, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mPackageName:Ljava/lang/String;

    .line 29
    if-nez p2, :cond_1

    const-string p2, ""

    .end local p2
    :cond_1
    iput-object p2, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mTitle:Ljava/lang/String;

    .line 30
    iput p3, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mPenWorkingMode:I

    .line 31
    iput p4, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mWindowType:I

    .line 32
    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 3

    .prologue
    .line 40
    new-instance v1, Ljava/lang/StringBuilder;

    iget-object v2, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mPackageName:Ljava/lang/String;

    invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    const/16 v2, 0x2d

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mTitle:Ljava/lang/String;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const/16 v2, 0x3a

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v1

    iget v2, p0, Lcom/htc/painting/pal/LaunchedWinInfo;->mPenWorkingMode:I

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    .line 42
    .local v0, builder:Ljava/lang/StringBuilder;
    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method


text:
@interface TalkfunPhotoPickerViewController : UIViewController

@property (nonatomic,copy) void (^loadCallback)(BOOL loading);
@property (nonatomic,strong) TalkfunCourseModel * model;

- (void)showAlert;

@end


text:
/**
 * Products templates relationship
 */
import { Identifiable, ResourceList } from './core'

export interface PcmTemplateRelationship extends Identifiable {
  meta: {
    created_at: string
    tags?: string[]
  }
  type: string
}

export type ProductTemplateRelationshipResource = string | { id: string; meta: { tags: string[] } }

export interface PcmTemplateRelationshipEndpoint {
  endpoint: 'relationships/templates'

  /**
   * Get all product template relationships
   * Description:
   * @param productId
   * @constructor
   */
  All(productId: string): Promise<ResourceList<PcmTemplateRelationship>>

  /**
   * Create a product template relationship
   * Description:
   * @param productId
   * @param resources
   * @constructor
   */
  Create(
    productId: string,
    resources?: string | ProductTemplateRelationshipResource[]
  ): Promise<void>

  /**
   * Delete a product template relationship
   * Description:
   * @param productId
   * @param resources
   * @constructor
   */
  Delete(
    productId: string,
    resources?: string | string[]
  ): Promise<void>
}


text:
package gedis

import (
	"bytes"
	"fmt"
	"strconv"
)

// Interface for writing Redis commands
type Writer interface {
	Write(p []byte) (n int, err error)
}

func Write(w Writer, args ...interface{}) (n int, err error) {
	if len(args) == 0 {
		return -1, fmt.Errorf("Must write at least one argument")
	}
	return w.Write(WriteMultiBulk(args...))
}

// Writes a string as a sequence of bytes to be send to a Redis
// instance, using the Redis Bulk format.
func WriteBulk(bulk string) []byte {
	bulk_len := strconv.Itoa(len(bulk))

	// '$' + len(string(len(bulk))) + "\r\n" + len(bulk) + "\r\n"
	n := 1 + len(bulk_len) + 2 + len(bulk) + 2

	bytes := make([]byte, n)

	bytes[0] = '$'

	j := 1

	for _, c := range bulk_len {
		bytes[j] = byte(c)
		j++
	}

	bytes[j] = '\r'
	bytes[j+1] = '\n'
	j += 2

	for _, c := range bulk {
		bytes[j] = byte(c)
		j++
	}

	bytes[j] = '\r'
	bytes[j+1] = '\n'

	return bytes
}

// Writes a number in the Redis protocol format
func WriteInt(n int64) []byte {
	return []byte(":" + strconv.FormatInt(n, 10) + "\r\n")
}

// Writes an error in the Redis protocol format
func WriteError(err error) []byte {
	return []byte("-ERR " + err.Error() + "\r\n")
}

// Writes a status in the Redis protocol format
func WriteStatus(status string) []byte {
	bs := make([]byte, len(status)+3)
	bs[0] = '+'
	l := 1
	for _, r := range status {
		bs[l] = byte(r)
		l++
	}
	bs[l] = '\r'
	bs[l+1] = '\n'
	return bs
}

// BUG(inkel): writeMultiBulk can't write multi-bulks inside multi-bulks

// Writes a sequence of strings as a sequence of bytes to be send to a
// Redis instance, using the Redis Multi-Bulk format.
func WriteMultiBulk(args ...interface{}) []byte {
	var buffer bytes.Buffer

	buffer.WriteByte('*')
	buffer.WriteString(strconv.Itoa(len(args)))
	buffer.WriteString("\r\n")

	var bs []byte

	for _, arg := range args {
		bs = []byte{}

		switch arg := arg.(type) {
		case string:
			bs = WriteBulk(arg)
		case int:
			bs = WriteInt(int64(arg))
		case int64:
			bs = WriteInt(arg)
		case error:
			bs = WriteError(arg)
		case nil:
			bs = []byte("$-1\r\n")
		default:
			panic(fmt.Errorf("Unrecognized type: %#v", arg))
		}

		buffer.Write(bs)
	}

	return buffer.Bytes()
}


text:
var assert = require('chai').assert,
    Reflux = require('../lib'),
    Action = Reflux.createAction,
    Store = Reflux.createStore,
    fn = function(){},
    sinon = require('sinon');

describe('Stopping',function(){
    describe('listening to a publisher that\'s only part of a join',function(){
        var store = Store(),
            action1 = Action(),
            action2 = Action();
        store.joinTrailing(action1,action2,function(){});
        it('should fail',function(){
            assert.equal(store.stopListeningTo(action1),false);
            assert.equal(store.subscriptions.length,1);
        });
    });
    describe('a join',function(){
        var store = Store(),
            action1 = Action({sync:true}),
            action2 = Action({sync:true}),
            action3 = Action({sync:true}),
            indivcallback = sinon.spy(),
            joincallback = sinon.spy(),
            subobj;
        store.listenTo(action2,indivcallback);
        subobj = store.joinLeading(action1,action2,action3,joincallback);
        subobj.stop();
        action1("A");
        action2("B");
        action3("C");
        it('should leave the individual listening intact',function(){
            assert.equal(store.subscriptions.length,1);
            assert.equal(store.subscriptions[0].listenable,action2);
            action2("foo","bar");
            assert.deepEqual(["foo","bar"],indivcallback.lastCall.args);
        });
        it('should not fire join callback anymore',function(done){
            setTimeout(function(){
                assert.equal(joincallback.callCount,0);
                done();
            },10);
        });
    });
    describe('a single listen', function(){
        describe('by calling stop directly',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(Action(),fn);
                store.listenTo(action3,fn);
                it('should remove that listener from the list but keep the others',function(){
                    store.subscriptions[1].stop();
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
            });
            describe('when the listener has already been removed from the list somehow',function(){
                var store = Store();
                store.listenTo(Action(),fn);
                store.listenTo(Action(),fn);
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.subscriptions.pop().stop();
                    });
                });
            });
        });
        describe('by using stopListenTo',function(){
            describe('when all is well',function(){
                var store = Store(),
                    action1 = Action(),
                    action2 = Action(),
                    action3 = Action();
                store.listenTo(action1,fn);
                store.listenTo(action2,fn);
                store.listenTo(action3,fn);
                var result = store.stopListeningTo(action2);
                it('should remove that listener from the list but keep the others',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action3,store.subscriptions[1].listenable);
                });
                it('should return true',function(){
                    assert.equal(true,result);
                });
            });
            describe('when the stop method won\'t remove it from the array',function(){
                var store = Store(),
                    action = Action();
                store.listenTo(action,fn);
                store.subscriptions[0].stop = fn;
                it('should throw an error',function(){
                    assert.throws(function(){
                        store.stopListeningTo(action);
                    });
                });
            });
            describe('when we weren\'t actually listening to the given listenable',function(){
                var action1 = Action(),
                    action2 = Action(),
                    store = Store(),
                    result;
                store.listenTo(action1);
                store.listenTo(action2);
                result = Store().stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(false,result);
                });
                it('should leave the other listens intact',function(){
                    assert.equal(2,store.subscriptions.length);
                    assert.equal(action1,store.subscriptions[0].listenable);
                    assert.equal(action2,store.subscriptions[1].listenable);
                });
            });
            describe('when we don\'t have a subscriptions list',function(){
                var store = Store(), result;
                delete store.subscriptions;
                result = store.stopListeningTo(Action());
                it('should return false',function(){
                    assert.equal(result,false);
                });
            });
        });
    });
    describe('all listens',function(){
        describe('when all is well',function(){
            var store = Store();
            store.listenTo(Action(),fn);
            store.listenTo(Action(),fn);
            it('should clear the subscriptions list',function(){
                store.stopListeningToAll();
                assert.deepEqual([],store.subscriptions);
            });
        });
        describe('when a stop fails to remove the subscription object from the list',function(){
            var store = Store();
            store.listenTo(Action());
            store.subscriptions[0].stop = fn;
            it('should throw an error',function(){
                assert.throws(function(){
                    store.stopListeningToAll();
                });
            });
        });
        describe('when we don\'t have a subscriptions list',function(){
            var store = Store();
            delete store.subscriptions;
            it('should be a noop',function(){
                store.stopListeningToAll();
            });
        });
    });
});


text:
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

import baseLogger from './logger.js';

function capitalize(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

var LanguageUtil = function () {
  function LanguageUtil(options) {
    _classCallCheck(this, LanguageUtil);

    this.options = options;

    this.whitelist = this.options.whitelist || false;
    this.logger = baseLogger.create('languageUtils');
  }

  LanguageUtil.prototype.getScriptPartFromCode = function getScriptPartFromCode(code) {
    if (!code || code.indexOf('-') < 0) return null;

    var p = code.split('-');
    if (p.length === 2) return null;
    p.pop();
    return this.formatLanguageCode(p.join('-'));
  };

  LanguageUtil.prototype.getLanguagePartFromCode = function getLanguagePartFromCode(code) {
    if (!code || code.indexOf('-') < 0) return code;

    var p = code.split('-');
    return this.formatLanguageCode(p[0]);
  };

  LanguageUtil.prototype.formatLanguageCode = function formatLanguageCode(code) {
    // http://www.iana.org/assignments/language-tags/language-tags.xhtml
    if (typeof code === 'string' && code.indexOf('-') > -1) {
      var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
      var p = code.split('-');

      if (this.options.lowerCaseLng) {
        p = p.map(function (part) {
          return part.toLowerCase();
        });
      } else if (p.length === 2) {
        p[0] = p[0].toLowerCase();
        p[1] = p[1].toUpperCase();

        if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
      } else if (p.length === 3) {
        p[0] = p[0].toLowerCase();

        // if lenght 2 guess it's a country
        if (p[1].length === 2) p[1] = p[1].toUpperCase();
        if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();

        if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
        if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
      }

      return p.join('-');
    }

    return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
  };

  LanguageUtil.prototype.isWhitelisted = function isWhitelisted(code) {
    if (this.options.load === 'languageOnly' || this.options.nonExplicitWhitelist) {
      code = this.getLanguagePartFromCode(code);
    }
    return !this.whitelist || !this.whitelist.length || this.whitelist.indexOf(code) > -1;
  };

  LanguageUtil.prototype.getFallbackCodes = function getFallbackCodes(fallbacks, code) {
    if (!fallbacks) return [];
    if (typeof fallbacks === 'string') fallbacks = [fallbacks];
    if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;

    if (!code) return fallbacks.default || [];

    // asume we have an object defining fallbacks
    var found = fallbacks[code];
    if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
    if (!found) found = fallbacks[this.formatLanguageCode(code)];
    if (!found) found = fallbacks.default;

    return found || [];
  };

  LanguageUtil.prototype.toResolveHierarchy = function toResolveHierarchy(code, fallbackCode) {
    var _this = this;

    var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);

    var codes = [];
    var addCode = function addCode(c) {
      if (!c) return;
      if (_this.isWhitelisted(c)) {
        codes.push(c);
      } else {
        _this.logger.warn('rejecting non-whitelisted language code: ' + c);
      }
    };

    if (typeof code === 'string' && code.indexOf('-') > -1) {
      if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
      if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
      if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
    } else if (typeof code === 'string') {
      addCode(this.formatLanguageCode(code));
    }

    fallbackCodes.forEach(function (fc) {
      if (codes.indexOf(fc) < 0) addCode(_this.formatLanguageCode(fc));
    });

    return codes;
  };

  return LanguageUtil;
}();

export default LanguageUtil;


text:
<?php

namespace Spiffy\Framework\Action;

use Spiffy\Framework\View\ViewManager;
use Spiffy\View\ViewModel;

class DispatchExceptionAction extends AbstractAction
{
    /** @var \Spiffy\Framework\View\ViewManager  */
    private $vm;

    /**
     * @param \Spiffy\Framework\View\ViewManager $vm
     */
    public function __construct(ViewManager $vm)
    {
        $this->vm = $vm;
    }

    /**
     * @param \Exception $exception
     * @return \Spiffy\View\ViewModel
     */
    public function __invoke(\Exception $exception)
    {
        $previous = [];

        $e = $exception;
        while ($e->getPrevious()) {
            $e = $e->getPrevious();
            $previous[] = $e;
        }

        $model = new ViewModel();
        $model->setTemplate($this->vm->getErrorTemplate());
        $model->setVariables([
            'type' => 'exception',
            'exception_class' => get_class($exception),
            'exception' => $exception,
            'previous_exceptions' => $previous
        ]);

        return $model;
    }
}


text:
<!--
Create tabs with an icon and label, using the tabs-positive style.
Each tab's child <ion-nav-view> directive will have its own
navigation history that also transitions its views in and out.
-->
<ion-tabs class="tabs-icon-top tabs-color-active-positive">
  <!-- Dashboard Tab -->
  <ion-tab title="Status" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/dash">
    <ion-nav-view name="tab-dash"></ion-nav-view>
  </ion-tab>
  <!-- Video Tab -->
  <ion-tab title="Video" icon-off="ion-ios-videocam-outline" icon-on="ion-ios-videocam" disabled="!state.registered" href="#/tab/video">
    <ion-nav-view name="tab-video"></ion-nav-view>
  </ion-tab>
  <!-- Users Tab  -->
  <ion-tab title="Users" icon-off="ion-ios-people-outline" icon-on="ion-ios-people" href="#/tab/users">
    <ion-nav-view name="tab-users"></ion-nav-view>
  </ion-tab>
  <!-- Settings Tab -->
  <ion-tab title="Settings" icon-off="ion-ios-gear-outline" icon-on="ion-ios-gear" href="#/tab/settings" disabled="state.insession">
    <ion-nav-view name="tab-settings"></ion-nav-view>
  </ion-tab>
</ion-tabs>


text:
        <umb-box data-element="node-info-urls">
            <umb-box-header title-key="general_links"></umb-box-header>
            <umb-box-content class="block-form">

                <umb-empty-state
                    ng-if="!nodeUrl"
                    size="small">
                    <localize key="content_noMediaLink"></localize>
                </umb-empty-state>

                            {{nodeUrl}}

            </umb-box-content>
        </umb-box>

        <umb-box data-element="node-info-general">
            <umb-box-header title-key="general_general"></umb-box-header>
            <umb-box-content class="block-form">

                <umb-control-group ng-if="node.id !== 0" data-element="node-info-create-date" label="@content_createDate">
                    {{node.createDateFormatted}} by {{ node.owner.name }}
                </umb-control-group>

                <umb-control-group ng-if="node.id !== 0" data-element="node-info-update-date" label="@content_updateDate">
                    {{node.updateDateFormatted}}
                </umb-control-group>

                <umb-control-group data-element="node-info-media-type" label="@content_mediatype">
                    <umb-node-preview
                        style="max-width: 100%; margin-bottom: 0px;"
                        icon="node.icon"
                        name="node.contentTypeName"
                        allow-open="allowOpen"
                        on-open="openMediaType(mediaType)">
                    </umb-node-preview>
                </umb-control-group>

                <umb-control-group ng-if="node.id !== 0" data-element="node-info-id" label="Id">

{{ node.id }}

                    {{ node.key }}
                </umb-control-group>

            </umb-box-content>
        </umb-box>


text:
'use strict';

var bunyan       = require('bunyan');
var prettyStream = require('bunyan-prettystream');

var prettyStdOut = new prettyStream();
prettyStdOut.pipe(process.stdout);

var createLogger = function(name, log_level, log_file_name){

   return bunyan.createLogger({
      name   : name,
      src    : true,
      streams: [
         {
            level : log_level,
            path  : log_file_name
         },
         {
            level  : log_level,
            type   : 'raw',
            stream : prettyStdOut
         }
      ]
   });
};

module.exports.createLogger = createLogger;


text:
'use strict'
/**
 * The Stream Logger class which sends the message to be logged to the server
 * @class
 */
class StreamLogger {
  /**
   * Default constructor that initializes the socket communicator
   * @function
   * @param {JSON} SocketCommunicator The SocketCommunicator object which will send data
   */
  constructor(SocketCommunicator) {
    this.socketCommunicator = SocketCommunicator;
  }
  /**
   * The logging function which emits the message to be logged to the communication engine
   * @function
   * @param {String} data The message to be logged on the server
   */
  log(data) {
    this.socketCommunicator.emitEvent('message', data);
  }
}
module.exports = StreamLogger;


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe Metamuse::Services::Echonest do
  describe "finding an artist" do
    before do
      @query = "coldplay"
      @response = {'response' => {'artists' => {}}}
    end

    it "returns nil when no artist was found" do
      @response['response'] = {'artists' => nil}
      stub(Metamuse::Services::Echonest).get { @response}
      Metamuse::Services::Echonest.artist(@query).should be_nil
    end

    it "returns the first of a collection of artists" do
      @response['response']['artists'].merge! "artist"=>[{"name"=>"Battles", "id"=>"1"}, {"name"=>"The Battles", "id"=>"2"}]
      stub(Metamuse::Services::Echonest).get { @response}
      Metamuse::Services::Echonest.artist(@query).should be_instance_of(Metamuse::Artist)
    end

    it "returns the one matching artist" do
      @response['response']['artists'].merge! "artist"=>{"name"=>"Coldplay", "id"=>"1"}
      stub(Metamuse::Services::Echonest).get { @response}
      Metamuse::Services::Echonest.artist(@query).should be_instance_of(Metamuse::Artist)
    end
  end
end


text:
#include "Tudat/InputOutput/textParser.h"

namespace tudat
{
namespace input_output
{

// Using declaration.
using namespace parsed_data_vector_utilities;

// Parse string.
ParsedDataVectorPtr TextParser::parse( std::string& string )
{
    // Create stringstream object.
    std::stringstream stringStream( string );

    // Return parsed data from stringstream.
    return parse( stringStream );
}

// Parse stream.
ParsedDataVectorPtr TextParser::parse( std::istream& stream )
{
    // Clear parsedData variable.
    parsedData->clear( );

    if ( parseAsStream )
    {
        // Stream based parsing.
        parseStream( stream );
    }
    else
    {
        // Line based parsing
        while ( !stream.fail( ) && !stream.eof( ) )
        {
            std::string line;
            std::getline( stream, line );
            parseLine( line );
        }
    }

    // Return parsed data.
    return parsedData;
}

} // namespace input_output
} // namespace tudat