text:
namespace System.IdentityModel
{
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;
    using System.ServiceModel.Diagnostics;

    sealed class Psha1DerivedKeyGenerator
    {
        byte[] key;

        public Psha1DerivedKeyGenerator(byte[] key)
        {
            if (key == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
            }
            this.key = key;
        }

        public byte[] GenerateDerivedKey(byte[] label, byte[] nonce, int derivedKeySize, int position)
        {
            if (label == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("label");
            }
            if (nonce == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("nonce");
            }
            ManagedPsha1 dkcp = new ManagedPsha1(key, label, nonce);
            return dkcp.GetDerivedKey(derivedKeySize, position);
        }

        // private class to do the real work
        // Note: Though named ManagedPsha1, this works for both fips and non-fips compliance
        sealed class ManagedPsha1
        {
            byte[] aValue;
            byte[] buffer;
            byte[] chunk;
            KeyedHashAlgorithm hmac;
            int index;
            int position;
            byte[] secret;
            byte[] seed;

            // assume arguments are already validated
            public ManagedPsha1(byte[] secret, byte[] label, byte[] seed)
            {
                this.secret = secret;
                this.seed = DiagnosticUtility.Utility.AllocateByteArray(checked(label.Length + seed.Length));
                label.CopyTo(this.seed, 0);
                seed.CopyTo(this.seed, label.Length);

                this.aValue = this.seed;
                this.chunk = new byte[0];
                this.index = 0;
                this.position = 0;
                this.hmac = CryptoHelper.NewHmacSha1KeyedHashAlgorithm(secret);

                this.buffer = DiagnosticUtility.Utility.AllocateByteArray(checked(this.hmac.HashSize / 8 + this.seed.Length));
            }

            public byte[] GetDerivedKey(int derivedKeySize, int position)
            {
                if (derivedKeySize < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("derivedKeySize", SR.GetString(SR.ValueMustBeNonNegative)));
                }
                if (this.position > position)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("position", SR.GetString(SR.ValueMustBeInRange, 0, this.position)));
                }

                // Seek to the desired position in the pseudo-random stream.
                while (this.position < position)
                {
                    GetByte();
                }
                int sizeInBytes = derivedKeySize / 8;
                byte[] derivedKey = new byte[sizeInBytes];
                for (int i = 0; i < sizeInBytes; i++)
                {
                    derivedKey[i] = GetByte();
                }
                return derivedKey;
            }

            byte GetByte()
            {
                if (index >= chunk.Length)
                {
                    // Calculate A(i) = HMAC_SHA1(secret, A(i-1)).
                    hmac.Initialize();
                    this.aValue = hmac.ComputeHash(this.aValue);
                    // Calculate P_SHA1(secret, seed)[j] = HMAC_SHA1(secret, A(j+1) || seed).
                    this.aValue.CopyTo(buffer, 0);
                    this.seed.CopyTo(buffer, this.aValue.Length);
                    hmac.Initialize();
                    this.chunk = hmac.ComputeHash(buffer);
                    index = 0;
                }
                position++;
                return chunk[index++];
            }
        }
    }
}


text:
package org.hitachivantara.spring.kafka.producer;

import org.apache.kafka.common.serialization.Serializer;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.ProducerFactory;

public class KafkaProducerFactory  {
  private static final String DEFAULT_KAFKA_PRODUCER_FACTORY_BEAN_NAME = "defaultKafkaProducerFactory";
  private BlueprintContainer container;

  public KafkaProducerFactory( BlueprintContainer container ) {
    this.container = container;
  }

  public ProducerFactory createProducerFactory( Serializer keySerializer, Serializer valueSerializer ) {
    DefaultKafkaProducerFactory producerFactory = (DefaultKafkaProducerFactory) this.container.getComponentInstance( DEFAULT_KAFKA_PRODUCER_FACTORY_BEAN_NAME );
    producerFactory.setKeySerializer( keySerializer );
    producerFactory.setValueSerializer( valueSerializer );
    return producerFactory;
  }

}

redpajama_set_name: RedPajamaGithub


text:
package CIAPI.Java.core.dto;

/**
 * !This is an auto generated model object!
 *
 * system status
 */
public class SystemStatusDTO {

	/**
	 * No argument constructor
	 */
	public SystemStatusDTO() {
	}

	private String StatusMessage;

	/**
	 * a status message
	 */
	public String getStatusMessage() {
		return StatusMessage;
	}

	public void setStatusMessage(String StatusMessage) {
		this.StatusMessage = StatusMessage;
	}
}


text:
const path = require('path');
const _ = require('lodash');
const gm = require('gm');

module.exports = function(Model) {
  Model.__images.onUpload = function(options, operations) {
    return _.map(Model.__images.sizeKeys, function(key) {
      var size = Model.__images.sizes[key];

      var transformer = gm(options.file, options.filename);

      if (size.crop) {
        transformer = transformer.thumbnail(size.width, size.height + '^');
        transformer = transformer.gravity('center');
      } else {
        transformer = transformer.resize(size.width, size.height);
      }

      transformer = transformer.noProfile();

      var parsed = path.parse(options.location);
      parsed.base += '/' + key;
      var location = path.format(parsed);

      operations.push(
        _.extend({}, options, {
          file: transformer.stream(),
          location: location,
          isSize: true
        })
      );
    });
  };
};


text:
/*
 * This content is released under the MIT License as specified in https://raw.githubusercontent.com/gabime/spdlog/master/LICENSE
 */
#include "includes.h"

#include <iostream>

class failing_sink : public spdlog::sinks::base_sink<std::mutex>
{
public:
    failing_sink() = default;
    ~failing_sink() final = default;

protected:
    void sink_it_(const spdlog::details::log_msg &) final
    {
        throw std::runtime_error("some error happened during log");
    }

    void flush_() final
    {
        throw std::runtime_error("some error happened during flush");
    }
};

TEST_CASE("default_error_handler", "[errors]]")
{
    prepare_logdir();
    std::string filename = "logs/simple_log.txt";

    auto logger = spdlog::create<spdlog::sinks::basic_file_sink_mt>("test-error", filename, true);
    logger->set_pattern("%v");
    logger->info("Test message {} {}", 1);
    logger->info("Test message {}", 2);
    logger->flush();

    REQUIRE(file_contents(filename) == std::string("Test message 2\n"));
    REQUIRE(count_lines(filename) == 1);
}

struct custom_ex
{
};
TEST_CASE("custom_error_handler", "[errors]]")
{
    prepare_logdir();
    std::string filename = "logs/simple_log.txt";
    auto logger = spdlog::create<spdlog::sinks::basic_file_sink_mt>("logger", filename, true);
    logger->flush_on(spdlog::level::info);
    logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
    logger->info("Good message #1");

    REQUIRE_THROWS_AS(logger->info("Bad format msg {} {}", "xxx"), custom_ex);
    logger->info("Good message #2");
    REQUIRE(count_lines(filename) == 2);
}

TEST_CASE("default_error_handler2", "[errors]]")
{
    spdlog::drop_all();
    auto logger = spdlog::create<failing_sink>("failed_logger");
    logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
    REQUIRE_THROWS_AS(logger->info("Some message"), custom_ex);
}

TEST_CASE("flush_error_handler", "[errors]]")
{
    spdlog::drop_all();
    auto logger = spdlog::create<failing_sink>("failed_logger");
    logger->set_error_handler([=](const std::string &) { throw custom_ex(); });
    REQUIRE_THROWS_AS(logger->flush(), custom_ex);
}

TEST_CASE("async_error_handler", "[errors]]")
{
    prepare_logdir();
    std::string err_msg("log failed with some msg");

    std::string filename = "logs/simple_async_log.txt";
    {
        spdlog::init_thread_pool(128, 1);
        auto logger = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("logger", filename, true);
        logger->set_error_handler([=](const std::string &) {
            std::ofstream ofs("logs/custom_err.txt");
            if (!ofs)
                throw std::runtime_error("Failed open logs/custom_err.txt");
            ofs << err_msg;
        });
        logger->info("Good message #1");
        logger->info("Bad format msg {} {}", "xxx");
        logger->info("Good message #2");
        spdlog::drop("logger"); // force logger to drain the queue and shutdown
    }
    spdlog::init_thread_pool(128, 1);
    REQUIRE(count_lines(filename) == 2);
    REQUIRE(file_contents("logs/custom_err.txt") == err_msg);
}

// Make sure async error handler is executed
TEST_CASE("async_error_handler2", "[errors]]")
{
    prepare_logdir();
    std::string err_msg("This is async handler error message");
    {
        spdlog::init_thread_pool(128, 1);
        auto logger = spdlog::create_async<failing_sink>("failed_logger");
        logger->set_error_handler([=](const std::string &) {
            std::ofstream ofs("logs/custom_err2.txt");
            if (!ofs)
                throw std::runtime_error("Failed open logs/custom_err2.txt");
            ofs << err_msg;
        });
        logger->info("Hello failure");
        spdlog::drop("failed_logger"); // force logger to drain the queue and shutdown
    }

    spdlog::init_thread_pool(128, 1);
    REQUIRE(file_contents("logs/custom_err2.txt") == err_msg);
}


text:
package com.jivesoftware.os.amza.client.http;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jivesoftware.os.amza.api.ring.RingMember;
import com.jivesoftware.os.amza.api.ring.RingMemberAndHost;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author jonathan.colt
 */
public class Ring {

    private static final Random RANDOM = new Random(); // Random number generator
    private final int leaderIndex;
    final RingMemberAndHost[] members;

    public Ring(int leaderIndex, RingMemberAndHost[] members) {
        this.leaderIndex = leaderIndex;
        this.members = members;
    }

    public RingMemberAndHost leader() {
        return (leaderIndex == -1) ? null : members[leaderIndex];
    }

    public RingMemberAndHost[] actualRing() {
        return members;
    }

    public RingMemberAndHost[] orderedRing(List<RingMember> membersInOrder) {
        List<RingMemberAndHost> ordered = Lists.newArrayListWithCapacity(members.length);
        if (membersInOrder == null) {
            if (leaderIndex >= 0) {
                ordered.add(members[leaderIndex]);
            }
            for (int i = 0; i < members.length; i++) {
                if (i != leaderIndex) {
                    ordered.add(members[i]);
                }
            }
        } else {
            Map<RingMember, RingMemberAndHost> memberHosts = Maps.newHashMapWithExpectedSize(members.length);
            for (RingMemberAndHost member : members) {
                memberHosts.put(member.ringMember, member);
            }
            for (RingMember ringMember : membersInOrder) {
                RingMemberAndHost ringMemberAndHost = memberHosts.remove(ringMember);
                if (ringMemberAndHost != null) {
                    ordered.add(ringMemberAndHost);
                }
            }
            for (RingMemberAndHost ringMemberAndHost : memberHosts.values()) {
                ordered.add(ringMemberAndHost);
            }
        }
        return ordered.toArray(new RingMemberAndHost[0]);
    }

    public RingMemberAndHost[] leaderlessRing() {
        if (leaderIndex == -1) {
            return Arrays.copyOf(members, members.length);
        } else {
            RingMemberAndHost[] memberAndHosts = new RingMemberAndHost[members.length - 1];
            System.arraycopy(members, 0, memberAndHosts, 0, leaderIndex);
            System.arraycopy(members, leaderIndex + 1, memberAndHosts, leaderIndex, members.length - 1 - leaderIndex);
            return memberAndHosts;
        }
    }

    public RingMemberAndHost[] randomizeRing() {
        RingMemberAndHost[] array = Arrays.copyOf(members, members.length);
        for (int i = 0; i < array.length; i++) {
            int randomPosition = RANDOM.nextInt(array.length);
            RingMemberAndHost temp = array[i];
            array[i] = array[randomPosition];
            array[randomPosition] = temp;
        }
        return array;
    }

}


text:
from flask_restful import Resource
from flask import request, g
from v.tools.exception import ExceptionRest
from v.tools.v import processing_rest_exception, processing_rest_success, type_of_insert_rest, type_of_update_rest
from v.tools.validate import validate_rest
from v.project.model.projectTaskIssueMdl import ProjectIssueMdl

class ProjectIssueListRst(Resource, ProjectIssueMdl):
    def get(self):
        try:
            _where = " WHERE deleted_at is null "
            _by = request.args.get("by", False)
            if _by:
                if _by == 'project_task_participed_id':
                    _project_task_id = request.args.get('project_task_participed_id', False)
                    _where = _where + " and project_task_participed_id=%s " % (_project_task_id,)
                else:
                    _where = _where + " and create_id =%s " % (g.user.id,)
            else:
                _where = _where + " and create_id =%s " % (g.user.id,)

            _completed = request.args.get("completed")
            if _completed == 'True' or _completed == 'true':
                _where = _where + " and completed_at is not null "
            elif _completed == 'False' or _completed == 'false':
                _where = _where + " and completed_at is null "

            _qrg = self._query_get % _where
            g.db_conn.execute(_qrg)
            if g.db_conn.count() > 0:
                _collection = g.db_conn.one()[0]
                if _collection:
                    _data = {self._table: _collection}
                    _get = processing_rest_success(data=_data)
                else:
                    raise ExceptionRest(status_code=404, message="No se han encontrado resultados")
            else:
                raise ExceptionRest(status_code=404, message="No se han encontrado resultados")
        except (Exception, ExceptionRest), e:
            _get = processing_rest_exception(e)
        return _get

    def post(self):
        _request = request.json
        try:
            if 'priority' not in _request:
                _request['priority'] = 'minor'
            if 'kind' not in _request:
                _request['kind'] = 'bug'
            if 'assigned_user_id' not in _request:
                _request['assigned_user_id'] = g.user.id

            _errors = validate_rest(fields=self._fields, request=_request)
            if not _errors:
                _col, _val = type_of_insert_rest(self._fields, _request)
                _qrp = """
                    INSERT INTO %s (create_id , %s ) VALUES (%s, %s)
                    RETURNING (select row_to_json(collection) FROM (VALUES(id)) collection(id));
                """ % (self._table, _col, g.user.id, _val)
                g.db_conn.execute(_qrp)
                if g.db_conn.count() > 0:
                    _data = {self._table: g.db_conn.one()}
                    _post = processing_rest_success(data=_data, message='Fue creado correctamente',
                                                    status_code=201)
                else:
                    raise ExceptionRest(status_code=500, message='No se ha podido registrar')
            else:
                raise ExceptionRest(status_code=400, errors=_errors)
        except (Exception, ExceptionRest), e:
            _post = processing_rest_exception(e)
        return _post

class ProjectIssueRst(Resource, ProjectIssueMdl):
    def get(self, id):
        try:
            _qrg = self._query_get + " WHERE deleted_at is null and id=%s" % (id,)
            g.db_conn.execute(_qrg)
            if g.db_conn.count() > 0:
                _collection = g.db_conn.one()[0]
                if _collection:
                    _data = {self._table: _collection}
                    _get = processing_rest_success(data=_data)
                else:
                    raise ExceptionRest(status_code=404, message="No se han encontrado resultados")
            else:
                raise ExceptionRest(status_code=404, message="No se han encontrado resultados")
        except (Exception, ExceptionRest), e:
            _get = processing_rest_exception(e)
        return _get

    def put(self, id):
        _request = request.json
        try:
            _errors = validate_rest(fields=self._fields, request=_request, method="put")
            if not _errors:
                _val = type_of_update_rest(self._fields, _request)
                _qrp = "UPDATE %s SET %s WHERE id=%s;" % (self._table, _val, id,)
                g.db_conn.execute(_qrp)
                if g.db_conn.count() > 0:
                    _put = processing_rest_success(status_code=201, message="El registro fue actualizado correctamente")
                else:
                    raise ExceptionRest(status_code=404,
                                        message="No se ha podido encontrar el registro, para actualizar.")
            else:
                raise ExceptionRest(status_code=400, errors=_errors)
        except (Exception, ExceptionRest), e:
            _put = processing_rest_exception(e)
        return _put

    def delete(self, id):
        try:
            _qrd = "UPDATE %s SET deleted_at=current_timestamp WHERE id=%s;" % (self._table, id,)
            g.db_conn.execute(_qrd)
            if g.db_conn.count() > 0:
                _delete = processing_rest_success(status_code=201, message="El registro fue eliminado correctamente")
            else:
                raise ExceptionRest(status_code=404,
                                    message="No se ha podido encontrar el registro, para eliminar.")
        except (Exception, ExceptionRest), e:
            _delete = processing_rest_exception(e)
        return _delete


text:
<?php

/**
 * Remove all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max).
 *
 * @param string  $name  Key name
 * @param numeric $min   Min value
 * @param numeric $max   Max value
 * @return integer
 *
 * @author Ivan Shumkov
 * @package Rediska
 * @version @package_version@
 * @link http://rediska.geometria-lab.net
 * @license http://www.opensource.org/licenses/bsd-license.php
 */
class Rediska_Command_DeleteFromSortedSetByRankTest extends Rediska_TestCase
{
    public function testDeleteFromNotExistsSetReturnFalse()
    {
        $reply = $this->rediska->deleteFromSortedSetByRank('test', 0, 1);
        $this->assertEquals(0, $reply);
    }

    public function testDelete()
    {
        $this->rediska->addToSortedSet('test', 'aaa', 1);
        $this->rediska->addToSortedSet('test', 'bbb', 2);
        $this->rediska->addToSortedSet('test', 'ccc', 3);
        $this->rediska->addToSortedSet('test', 'ddd', 4);

        $reply = $this->rediska->deleteFromSortedSetByRank('test', 1, 2);
        $this->assertEquals(2, $reply);

        $values = $this->rediska->getSortedSet('test');
        $this->assertContains('aaa', $values);
        $this->assertNotContains('bbb', $values);
        $this->assertNotContains('ccc', $values);
        $this->assertContains('ddd', $values);
    }
}


text:
import Benchmark = require('benchmark');
import * as store from './store';

const Suite = Benchmark.Suite;

const construct = (Instance, a?, b?, c?) => {
  if (c) {
    return new Instance(a, b, c);
  }
  if (b) {
    return new Instance(a, b);
  }
  if (a) {
    return new Instance(a);
  }
  return new Instance();
};

export const WrappedBenchmark = (
  name: string,
  fn: string | Function,
  options?: Benchmark.Options
): Benchmark => {
  const benchmark = construct(Benchmark, name, fn, options);
  return store.addBenchmark(benchmark, false);
};

const WrappedSuite = (
  name?: string,
  options?: Benchmark.Options
): Benchmark.Suite => {
  const suite = construct(Suite, name, options);
  suite.add = addBenchmark;
  store.addSuite(suite);
  return suite;
};

function addBenchmark(
  name: string,
  fn: string | Function,
  options?: Benchmark.Options
): Benchmark.Suite {
  const suite = Suite.prototype.add.call(this, name, fn, options);
  const benchmark = suite[suite.length - 1];
  store.addBenchmark(benchmark, true);
  return suite;
}

WrappedBenchmark.Suite = WrappedSuite;


text:
using log4net;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.Jwt;
using StatsApi.Controllers;
using StatsApi.Services;
using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;

namespace StatsApi
{
    public class ControllerFactory : IHttpControllerActivator
    {
        //singleton instances
        ILog logger = LogManager.GetLogger("StatsApi.Controllers");
        DataServices ds = new DataServices();

        JwtFormat format = new JwtFormat(
            new[] { Secrets.PublicClientId },
            new IIssuerSecurityTokenProvider[] {
                new SymmetricKeyIssuerSecurityTokenProvider(Secrets.Issuer, Secrets.PublicKey)
            }
        );

        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            if (controllerType == typeof(AccountController))
            {
                var userManager = request.GetOwinContext().GetUserManager<ApplicationUserManager>();
                request.RegisterForDispose(userManager);
                return new AccountController(userManager, format);
            }
            else if (controllerType == typeof(DataSynchController))
            {
                return new DataSynchController(ds);
            }
            else
            {
                logger.ErrorFormat("No matching controller exists for {0}", controllerType);
            }
            // no matching controller
            return null;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Constant Field Values (ZooKeeper 3.3.6 API)
</TITLE>

<META NAME="date" CONTENT="2012-07-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Constant Field Values

Contents

org.apache.*

org.apache.*

org.apache.zookeeper.KeeperException.CodeDeprecated

public static final int
APIError
-100

public static final int
AuthFailed
-115

public static final int
BadArguments
-8

public static final int
BadVersion
-103

public static final int
ConnectionLoss
-4

public static final int
DataInconsistency
-3

public static final int
InvalidACL
-114

public static final int
InvalidCallback
-113

public static final int
MarshallingError
-5

public static final int
NoAuth
-102

public static final int
NoChildrenForEphemerals
-108

public static final int
NodeExists
-110

public static final int
NoNode
-101

public static final int
NotEmpty
-111

public static final int
Ok
0

public static final int
OperationTimeout
-7

public static final int
RuntimeInconsistency
-2

public static final int
SessionExpired
-112

public static final int
SystemError
-1

public static final int
Unimplemented
-6

org.apache.zookeeper.ZooDefs.OpCode

public static final int
auth
100

public static final int
closeSession
-11

public static final int
create
1

public static final int
createSession
-10

public static final int
delete
2

public static final int
error
-1

public static final int
exists
3

public static final int
getACL
6

public static final int
getChildren
8

public static final int
getChildren2
12

public static final int
getData
4

public static final int
notification
0

public static final int
ping
11

public static final int
setACL
7

public static final int
setData
5

public static final int
setWatches
101

public static final int
sync
9

org.apache.zookeeper.ZooDefs.Perms

public static final int
ADMIN
16

public static final int
ALL
31

public static final int
CREATE
4

public static final int
DELETE
8

public static final int
READ
1

public static final int
WRITE
2

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2012 The Apache Software Foundation


text:
package br.unicamp.ic.sed.mobilemedia.album_exceptionhandler.impl;

import br.unicamp.ic.sed.mobilemedia.album.spec.req.IExceptionHandler;

class IAdapterAlbumEH implements IExceptionHandler {

	public void handle(Exception exception) {
		IManager manager = ComponentFactory.createInstance();
		br.unicamp.ic.sed.mobilemedia.exceptionhandler.spec.prov.IExceptionHandler handler = (br.unicamp.ic.sed.mobilemedia.exceptionhandler.spec.prov.IExceptionHandler)manager.getRequiredInterface("IExceptionHandler");
		handler.handle(exception);

	}

}


text:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;

using System.Diagnostics;
using System.Threading;

namespace SAMP_Ex
{
    class Server
    {
        #region Property
        private ConcurrentDictionary<string, string> _rules;
        private ConcurrentDictionary<string, int> _players;

        private int _port;

        private DateTime _timestamp;
		private IPEndPoint _endPoint;
        private Socket _querySocket;

		private ManualResetEvent _receptionComplete;

        private byte[] _buffer;
        #endregion

        #region Accessors
        [Browsable(false)]
        public IPAddress Ip { get; private set; }
        [Browsable(false)]
        public string Port { get; private set; }

        public string Hostname { get; private set; }
        [Browsable(false)]
        public bool HasPassword { get; private set; }
        [Browsable(false)]
        public string Password { get; private set; }
        [Browsable(false)]
        public int MaxPlayers { get; private set; }
        public int Players { get; private set; }
        public string MapName { get; private set; }
        public string Gamemode { get; private set; }
        public string Language { get; private set; }

        public int Ping { get; private set; }

        [Browsable(false)]
        public bool IsValid { get; private set; }

        [Browsable(false)]
        public string Nickname { get; set; }

        #endregion

        public Server(string address, string port, string nickname="")
        {
            _rules = new ConcurrentDictionary<string, string>();
            _players = new ConcurrentDictionary<string, int>();
            _buffer = new byte[3402];

            Nickname = nickname;
            Password = "";

            IsValid = true;

            if (Utils.IsValidPort(port))
            {
                Port = port;
                Int32.TryParse(Port, out _port);
            }
            else
            {
                IsValid = false;
            }

            _querySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			_querySocket.SendTimeout = 1000;
            _querySocket.ReceiveTimeout = 500;
			_querySocket.Blocking = true;

			_receptionComplete = new ManualResetEvent(false);

			try
            {
                Ip = Dns.GetHostAddresses(address)[0];
				_endPoint = new IPEndPoint(Ip, _port);
			}
            catch
            {
				IsValid = false;
				throw new Exception("Invalid IP");
            }

        }

        public Server(string addressAndPort, string nickname="") : this(Utils.ParseIPFromIPPort(addressAndPort), Utils.ParsePortFromIPPort(addressAndPort), nickname)
        {
        }

        public void SetPassword(string password)
        {
            Password = password;
        }

        public string GetVersion()
        {
            return this.GetRule("version");
        }

        private bool SendOpcode(char opcode)
        {

            // from https://wiki.sa-mp.com/wiki/Query_Mechanism/Csharp
            try
            {
				_buffer = new byte[3402];

				using (MemoryStream stream = new MemoryStream())
                {
                    using (BinaryWriter writer = new BinaryWriter(stream))
                    {
                        writer.Write("SAMP".ToCharArray());

                        string[] splitIP = Ip.ToString().Split('.');

                        writer.Write(Convert.ToByte(Convert.ToInt32(splitIP[0])));
                        writer.Write(Convert.ToByte(Convert.ToInt32(splitIP[1])));
                        writer.Write(Convert.ToByte(Convert.ToInt32(splitIP[2])));
                        writer.Write(Convert.ToByte(Convert.ToInt32(splitIP[3])));

                        writer.Write((ushort)_port);

                        writer.Write(opcode);

                        if (opcode == 'p')
                            writer.Write("6666".ToCharArray());

                        _timestamp = DateTime.Now;
                    }

                    if (!(_querySocket.SendTo(stream.ToArray(), _endPoint) > 0))
                        return false;
                    else
                        return true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return false;
            }
        }

		protected void ParseReceivedBytes(byte[] buffer)
		{
			try
			{
				using (MemoryStream receiveStream = new MemoryStream(buffer))
				{
					using (BinaryReader reader = new BinaryReader(receiveStream))
					{
						if (receiveStream.Length <= 10)
						{
							reader.Dispose();
							receiveStream.Dispose();
							return;
						}

						reader.ReadBytes(10);

						switch (reader.ReadChar())
						{
							case 'i':
								{
									HasPassword = Convert.ToBoolean((reader.ReadByte()));

									Players = reader.ReadInt16();
									MaxPlayers = reader.ReadInt16();

									int hostnamelen = reader.ReadInt32();
									Hostname = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(hostnamelen));

									int gamemodelen = reader.ReadInt32();
									Gamemode = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(gamemodelen));

									int mapnamelen = reader.ReadInt32();
									MapName = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(mapnamelen));

									if (reader.BaseStream.Position != reader.BaseStream.Length)
									{
										if (this.GetVersion() == "0.3.7" || this.GetVersion() == "0.3.7-R2" || this.GetVersion() == "0.3.7-R1")
										{
											int language = reader.ReadInt32();
											Language = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(language));
										}
									}
									break;
								}
							case 'r':
								{
									_rules.Clear();

									int rulecount = reader.ReadInt16();
									int rulelen = 0;
									int valuelen = 0;

									for (int i = 0; i < rulecount; i++)
									{
										rulelen = reader.ReadByte();
										string ruleName = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(rulelen));

										valuelen = reader.ReadByte();
										string ruleValue = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(valuelen));

										if (!_rules.ContainsKey(ruleName))
											_rules.AddOrUpdate(ruleName, ruleValue, (key, val) => val);
										else
											_rules[ruleName] = ruleValue;
									}
									break;
								}
							case 'c':
								{
									_players.Clear();

									int playercount = reader.ReadInt16();
									if (playercount == 0)
									{
										break;
									}

									for (int i = 0; i < playercount; i++)
									{
										try
										{
											int namelen = 0;
											int score = 0;
											if (reader.BaseStream.Position != reader.BaseStream.Length)
											{
												namelen = reader.ReadByte();
											}
											else
											{
												break;
											}

											string nickname = System.Text.Encoding.UTF7.GetString(reader.ReadBytes(namelen));

											if (reader.BaseStream.Position + 4 != reader.BaseStream.Length)
											{
												try
												{
													//Debug.WriteLine(reader.BaseStream.Position + " : " + reader.BaseStream.Length);
													//score = reader.ReadInt32();
												}
												catch (EndOfStreamException ex) { Debug.WriteLine(ex.Data); score = 0; }

											}
											else
											{
												break;
											}

											if (!String.IsNullOrEmpty(nickname))
											{
												if (!_players.ContainsKey(nickname))
													_players.AddOrUpdate(nickname, score, (key, val) => val);
												else
													_players[nickname] = score;
											}
										}
										catch (Exception ex)
										{
											Debug.WriteLine(ex.ToString());
										}

									}

									break;
								}
							case 'p': // Ping
								{
									Ping = DateTime.Now.Subtract(_timestamp).Milliseconds;

									break;
								}
							default:
								{
									break;
								}
						}
						reader.Dispose();
						receiveStream.Dispose();
						_buffer = null;
						return;
					}
				}
			}
			catch(Exception ex)
			{
				Debug.WriteLine(ex.ToString());
			}
		}

        private bool Receive()
        {
            try
            {
				_buffer = new byte[3402];
				_querySocket.Receive(_buffer);
				if (_buffer != null)
				{
					try
					{
						ParseReceivedBytes(_buffer);
						return true;
					}
					catch (Exception ex)
					{
						Debug.WriteLine("Except : " + ex.ToString());
						return false;
					}
				}
				else return false;

            }
            catch (Exception ex)
            {
                Debug.WriteLine("Except : " + ex.ToString());
				return false;
            }

        }

        /// <summary>
        /// Update all server informations
        /// </summary>
        /// <returns>True if all updates were success, false if not</returns>
        public bool TotalUpdate()
        {
            if ((UpdateInfos() && UpdatePing() && UpdatePlayerList() && UpdateRules()) == true)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Update basic server informations (Name, number of players, mapname, etc.)
        /// </summary>
        /// <returns>True if update was success, false if not</returns>
        public bool UpdateInfos()
        {
            if(!SendOpcode('i'))
            {
                if (String.IsNullOrWhiteSpace(this.Hostname))
                    this.Hostname = "SAMP 0.3 Server (No response)";

                return false;
            }

			bool res = Receive();
			if (String.IsNullOrWhiteSpace(this.Hostname))
				this.Hostname = "SAMP 0.3 Server (No response)";
			return res;
        }

        /// <summary>
        /// Update rules of the server
        /// </summary>
        /// <returns>True if update was success, false if not</returns>
        public bool UpdateRules()
        {
            if (!SendOpcode('r'))
            {
                return false;
            }
			return Receive();
        }

        /// <summary>
        /// Update player list of the server
        /// </summary>
        /// <returns>True if update was success, false if not</returns>
        public bool UpdatePlayerList()
        {
            if (!SendOpcode('c'))
            {
                return false;
            }

			return Receive();
        }

        /// <summary>
        /// Update ping value
        /// </summary>
        /// <returns>True if update was success, false if not</returns>
        public bool UpdatePing()
        {
            if (!SendOpcode('p'))
            {
                return false;
            }

			return Receive();
        }

        /// <summary>
        /// Get a specific rule value
        /// </summary>
        /// <param name="rule">rule name</param>
        /// <returns>rule value</returns>
        public string GetRule(string rule)
        {
            string tmpvalue = "";
            if(_rules.TryGetValue(rule, out tmpvalue))
            {
                return tmpvalue;
            }
            /*if (_rules.ContainsKey(rule))
                return _rules[rule];*/
            else
                return String.Empty;
        }

        /// <summary>
        /// Get rules list
        /// </summary>
        /// <returns>A dictionary with rules name/value inside</returns>
        public ConcurrentDictionary<string, string> GetRulesList()
        {
            return _rules;
        }

        /// <summary>
        /// Get players list
        /// </summary>
        /// <returns>A dictionary with players name/score inside</returns>
        public ConcurrentDictionary<string, int> GetPlayersList()
        {
            return _players;
        }
    }
}


text:
package main

var routes = Routes{
	Route{
		"UpdateProject",
		"POST",
		"/namespace/update/projects/",
		UpdateProject,
	},
	Route{
		"CreateNamespace",
		"POST",
		"/namespace/create/",
		CreateNamespace,
	},
	Route{
		"DeleteNamespace",
		"POST",
		"/namespace/delete/",
		DeleteNamespace,
	},
	Route{
		"GetNamespace",
		"POST",
		"/namespace/get/",
		GetNamespace,
	},
}


text:
//@compileroption /unsafe

using System;
using JSIL.Meta;

public static class Program {
    const int BufferSize = 8192;
    const int IterationCount = 320;

    public static Vector3d[] Vectors = new Vector3d[BufferSize];

    public static unsafe void Main () {
        for (int i = 0; i < BufferSize; i++)
            Vectors[i] = new Vector3d(i * 0.5, (double)i, i * 1.5);

        Console.WriteLine("Add: {0:00000.00}ms", Time(TestAdd));
        Console.WriteLine("Add Overloaded: {0:00000.00}ms", Time(TestAddOverloaded));
    }

    public static int Time (Func<Vector3d> func) {
        var started = Environment.TickCount;

        Vector3d sum = default(Vector3d);

        for (int i = 0; i < IterationCount; i++) {
            sum = func();
        }

        Console.WriteLine(sum);

        var ended = Environment.TickCount;
        return ended - started;
    }

    public static Vector3d TestAddOverloaded () {
        Vector3d sum = new Vector3d();

        for (int i = 0; i < BufferSize; i++) {
            sum = Vector3d.Add_Overloaded(sum, Vectors[i]);
        }

        return sum;
    }

    public static Vector3d TestAdd () {
        Vector3d sum = new Vector3d();

        for (int i = 0; i < BufferSize; i++) {
            sum = Vector3d.Add(sum, Vectors[i]);
        }

        return sum;
    }
}

public struct Vector3d {
    public readonly double x, y, z;

    public Vector3d (double x = 0, double y = 0, double z = 0) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static Vector3d Add (Vector3d a, Vector3d b) {
        return new Vector3d(a.x + b.x, a.y + b.y, a.z + b.z);
    }

    public static Vector3d Add_Overloaded (Vector3d a, Vector3d b) {
        return new Vector3d(a.x + b.x, a.y + b.y, a.z + b.z);
    }

    public static Vector3d Add_Overloaded (Vector3d a, float b) {
        return new Vector3d(a.x + b, a.y + b, a.z + b);
    }

    public override string ToString () {
        return String.Format("<{0:00000000.00}, {1:00000000.00}, {2:00000000.00}>", x, y, z);
    }
}


text:
namespace Merchello.Web.Models
{
    using System.Collections.Generic;

    /// <summary>
    /// Represents a product filter that includes pre queried counts.
    /// </summary>
    public interface IPrimedProductFilterGroup : IEntityCollectionProxy
    {
        /// <inheritdoc/>
        IEnumerable<IPrimedProductFilter> Filters { get; set; }

        /// <summary>
        /// Gets or sets the count of items in the filter group would matches in the current context.
        /// </summary>
        int Count { get; set; }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import java.io.Serializable;
import javax.persistence.Embeddable;

/**
 *
 * @author Chema
 */
@Embeddable
public class Motor implements Serializable {

    private Integer cilindrada;

    /**
     * Get the value of cilindrada
     *
     * @return the value of cilindrada
     */
    public Integer getCilindrada() {
        return cilindrada;
    }

    /**
     * Set the value of cilindrada
     *
     * @param cilindrada new value of cilindrada
     */
    public void setCilindrada(Integer cilindrada) {
        this.cilindrada = cilindrada;
    }
}


text:
@implementation WKRouteTableViewCell

- (void)setModel:(WKRouteModel *)model {
    _model = model;
    [_image_urlImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", model.image_url]] placeholderImage:PLACEHOLDER];
    _image_urlImage.contentMode = UIViewContentModeScaleAspectFill;
    _image_urlImage.clipsToBounds = YES;
    _image_urlImage.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _nameLabel.text = [NSString stringWithFormat:@"%@", model.name];
    _dayslabel.text = [NSString stringWithFormat:@"%@/", model.plan_days_count];
    _plan_nodes_countsLabel.text = [NSString stringWithFormat:@" 7个游行地"];
    _descLabel.text = [NSString stringWithFormat:@"%@", model.descriptioN];
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="true"
         syntaxCheck="true">
    <testsuites>
        <testsuite name="Email checker Test Suite">
            <file>tests/MxCheckerTest.php</file>
            <file>tests/SmtpCheckerTest.php</file>
            <file>tests/EmailCheckerTest.php</file>
            <file>tests/ResponseCheckerTest.php</file>
            <file>tests/DisponsableCheckerTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>


text:
package clair

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

// GetLayer displays a Layer and optionally all of its features and vulnerabilities.
func (c *Clair) GetLayer(name string, features, vulnerabilities bool) (*Layer, error) {
	url := c.url("/v1/layers/%s?features=%t&vulnerabilities=%t", name, features, vulnerabilities)
	c.Logf("clair.layers.get url=%s name=%s", url, name)

	var respLayer layerEnvelope
	if _, err := c.getJSON(url, &respLayer); err != nil {
		return nil, err
	}

	if respLayer.Error != nil {
		return nil, fmt.Errorf("clair error: %s", respLayer.Error.Message)
	}

	return respLayer.Layer, nil
}

// PostLayer performs the analysis of a Layer from the provided path.
func (c *Clair) PostLayer(layer *Layer) (*Layer, error) {
	url := c.url("/v1/layers")
	c.Logf("clair.layers.post url=%s name=%s", url, layer.Name)

	b, err := json.Marshal(layerEnvelope{Layer: layer})
	if err != nil {
		return nil, err
	}

	resp, err := c.Client.Post(url, "application/json", bytes.NewReader(b))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var respLayer layerEnvelope
	if err := json.NewDecoder(resp.Body).Decode(&respLayer); err != nil {
		return nil, err
	}

	if respLayer.Error != nil {
		return nil, fmt.Errorf("clair error: %s", respLayer.Error.Message)
	}

	return respLayer.Layer, err
}

// DeleteLayer removes a layer reference from clair.
func (c *Clair) DeleteLayer(name string) error {
	url := c.url("/v1/layers/%s", name)
	c.Logf("clair.layers.delete url=%s name=%s", url, name)

	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}

	resp, err := c.Client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusAccepted || resp.StatusCode == http.StatusNotFound {
		return nil
	}

	return fmt.Errorf("Got status code: %d", resp.StatusCode)
}


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

import static org.apache.hadoop.hbase.client.BufferedMutatorParams.UNSET;

import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.yetus.audience.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *

 * Used to communicate with a single HBase table similar to {@link Table} but meant for batched,
 * potentially asynchronous puts. Obtain an instance from a {@link Connection} and call
 * {@link #close()} afterwards. Provide an alternate to this implementation by setting
 * {@link BufferedMutatorParams#implementationClassName(String)} or by setting alternate classname
 * via the key {} in Configuration.
 *

 *

 * While this can be used across threads, great care should be used when doing so. Errors are global
 * to the buffered mutator and the Exceptions can be thrown on any thread that causes the flush for
 * requests.
 *

 * @see ConnectionFactory
 * @see Connection
 * @since 1.0.0
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class BufferedMutatorImpl implements BufferedMutator {

  private static final Logger LOG = LoggerFactory.getLogger(BufferedMutatorImpl.class);

  private final ExceptionListener listener;

  private final TableName tableName;

  private final Configuration conf;
  private final ConcurrentLinkedQueue<Mutation> writeAsyncBuffer = new ConcurrentLinkedQueue<>();
  private final AtomicLong currentWriteBufferSize = new AtomicLong(0);
  /**
   * Count the size of {@link BufferedMutatorImpl#writeAsyncBuffer}. The
   * {@link ConcurrentLinkedQueue#size()} is NOT a constant-time operation.
   */
  private final AtomicInteger undealtMutationCount = new AtomicInteger(0);
  private final long writeBufferSize;

  private final AtomicLong writeBufferPeriodicFlushTimeoutMs = new AtomicLong(0);
  private final AtomicLong writeBufferPeriodicFlushTimerTickMs =
    new AtomicLong(MIN_WRITE_BUFFER_PERIODIC_FLUSH_TIMERTICK_MS);
  private Timer writeBufferPeriodicFlushTimer = null;

  private final int maxKeyValueSize;
  private final ExecutorService pool;
  private final AtomicInteger rpcTimeout;
  private final AtomicInteger operationTimeout;
  private final boolean cleanupPoolOnClose;
  private volatile boolean closed = false;
  private final AsyncProcess ap;

  BufferedMutatorImpl(ClusterConnection conn, BufferedMutatorParams params, AsyncProcess ap) {
    if (conn == null || conn.isClosed()) {
      throw new IllegalArgumentException("Connection is null or closed.");
    }
    this.tableName = params.getTableName();
    this.conf = conn.getConfiguration();
    this.listener = params.getListener();
    if (params.getPool() == null) {
      this.pool = HTable.getDefaultExecutor(conf);
      cleanupPoolOnClose = true;
    } else {
      this.pool = params.getPool();
      cleanupPoolOnClose = false;
    }
    ConnectionConfiguration tableConf = new ConnectionConfiguration(conf);
    this.writeBufferSize = params.getWriteBufferSize() != UNSET
      ? params.getWriteBufferSize()
      : tableConf.getWriteBufferSize();

    // Set via the setter because it does value validation and starts/stops the TimerTask
    long newWriteBufferPeriodicFlushTimeoutMs =
      params.getWriteBufferPeriodicFlushTimeoutMs() != UNSET
        ? params.getWriteBufferPeriodicFlushTimeoutMs()
        : tableConf.getWriteBufferPeriodicFlushTimeoutMs();
    long newWriteBufferPeriodicFlushTimerTickMs =
      params.getWriteBufferPeriodicFlushTimerTickMs() != UNSET
        ? params.getWriteBufferPeriodicFlushTimerTickMs()
        : tableConf.getWriteBufferPeriodicFlushTimerTickMs();
    this.setWriteBufferPeriodicFlush(newWriteBufferPeriodicFlushTimeoutMs,
      newWriteBufferPeriodicFlushTimerTickMs);

    this.maxKeyValueSize = params.getMaxKeyValueSize() != UNSET
      ? params.getMaxKeyValueSize()
      : tableConf.getMaxKeyValueSize();

    this.rpcTimeout = new AtomicInteger(params.getRpcTimeout() != UNSET
      ? params.getRpcTimeout()
      : conn.getConnectionConfiguration().getWriteRpcTimeout());

    this.operationTimeout = new AtomicInteger(params.getOperationTimeout() != UNSET
      ? params.getOperationTimeout()
      : conn.getConnectionConfiguration().getOperationTimeout());
    this.ap = ap;
  }

  BufferedMutatorImpl(ClusterConnection conn, RpcRetryingCallerFactory rpcCallerFactory,
    RpcControllerFactory rpcFactory, BufferedMutatorParams params) {
    this(conn, params,
      // puts need to track errors globally due to how the APIs currently work.
      new AsyncProcess(conn, conn.getConfiguration(), rpcCallerFactory, rpcFactory));
  }

  private void checkClose() {
    if (closed) {
      throw new IllegalStateException("Cannot put when the BufferedMutator is closed.");
    }
  }

  ExecutorService getPool() {
    return pool;
  }

  AsyncProcess getAsyncProcess() {
    return ap;
  }

  @Override
  public TableName getName() {
    return tableName;
  }

  @Override
  public Configuration getConfiguration() {
    return conf;
  }

  @Override
  public void mutate(Mutation m)
    throws InterruptedIOException, RetriesExhaustedWithDetailsException {
    mutate(Collections.singletonList(m));
  }

  @Override
  public void mutate(List<? extends Mutation> ms)
    throws InterruptedIOException, RetriesExhaustedWithDetailsException {
    checkClose();

    long toAddSize = 0;
    int toAddCount = 0;
    for (Mutation m : ms) {
      if (m instanceof Put) {
        ConnectionUtils.validatePut((Put) m, maxKeyValueSize);
      }
      toAddSize += m.heapSize();
      ++toAddCount;
    }

    if (currentWriteBufferSize.get() == 0) {
      firstRecordInBufferTimestamp.set(EnvironmentEdgeManager.currentTime());
    }
    currentWriteBufferSize.addAndGet(toAddSize);
    writeAsyncBuffer.addAll(ms);
    undealtMutationCount.addAndGet(toAddCount);
    doFlush(false);
  }

  protected long getExecutedWriteBufferPeriodicFlushes() {
    return executedWriteBufferPeriodicFlushes.get();
  }

  private final AtomicLong firstRecordInBufferTimestamp = new AtomicLong(0);
  private final AtomicLong executedWriteBufferPeriodicFlushes = new AtomicLong(0);

  private void timerCallbackForWriteBufferPeriodicFlush() {
    if (currentWriteBufferSize.get() == 0) {
      return; // Nothing to flush
    }
    long now = EnvironmentEdgeManager.currentTime();
    if (firstRecordInBufferTimestamp.get() + writeBufferPeriodicFlushTimeoutMs.get() > now) {
      return; // No need to flush yet
    }
    // The first record in the writebuffer has been in there too long --> flush
    try {
      executedWriteBufferPeriodicFlushes.incrementAndGet();
      flush();
    } catch (InterruptedIOException | RetriesExhaustedWithDetailsException e) {
      LOG.error("Exception during timerCallbackForWriteBufferPeriodicFlush --> " + e.getMessage());
    }
  }

  @Override
  public synchronized void close() throws IOException {
    if (closed) {
      return;
    }
    // Stop any running Periodic Flush timer.
    disableWriteBufferPeriodicFlush();
    try {
      // As we can have an operation in progress even if the buffer is empty, we call
      // doFlush at least one time.
      doFlush(true);
    } finally {
      if (cleanupPoolOnClose) {
        this.pool.shutdown();
        try {
          if (!pool.awaitTermination(600, TimeUnit.SECONDS)) {
            LOG.warn("close() failed to terminate pool after 10 minutes. Abandoning pool.");
          }
        } catch (InterruptedException e) {
          LOG.warn("waitForTermination interrupted");
          Thread.currentThread().interrupt();
        }
      }
      closed = true;
    }
  }

  private AsyncProcessTask createTask(QueueRowAccess access) {
    return new AsyncProcessTask(AsyncProcessTask.newBuilder().setPool(pool).setTableName(tableName)
      .setRowAccess(access).setSubmittedRows(AsyncProcessTask.SubmittedRows.AT_LEAST_ONE).build()) {
      @Override
      public int getRpcTimeout() {
        return rpcTimeout.get();
      }

      @Override
      public int getOperationTimeout() {
        return operationTimeout.get();
      }
    };
  }

  @Override
  public void flush() throws InterruptedIOException, RetriesExhaustedWithDetailsException {
    checkClose();
    doFlush(true);
  }

  /**
   * Send the operations in the buffer to the servers.
   * @param flushAll - if true, sends all the writes and wait for all of them to finish before
   *                 returning. Otherwise, flush until buffer size is smaller than threshold
   */
  private void doFlush(boolean flushAll)
    throws InterruptedIOException, RetriesExhaustedWithDetailsException {
    List<RetriesExhaustedWithDetailsException> errors = new ArrayList<>();
    while (true) {
      if (!flushAll && currentWriteBufferSize.get() <= writeBufferSize) {
        // There is the room to accept more mutations.
        break;
      }
      AsyncRequestFuture asf;
      try (QueueRowAccess access = createQueueRowAccess()) {
        if (access.isEmpty()) {
          // It means someone has gotten the ticker to run the flush.
          break;
        }
        asf = ap.submit(createTask(access));
      }
      // DON'T do the wait in the try-with-resources. Otherwise, the undealt mutations won't
      // be released.
      asf.waitUntilDone();
      if (asf.hasError()) {
        errors.add(asf.getErrors());
      }
    }

    RetriesExhaustedWithDetailsException exception = makeException(errors);
    if (exception == null) {
      return;
    } else if (listener == null) {
      throw exception;
    } else {
      listener.onException(exception, this);
    }
  }

  private static RetriesExhaustedWithDetailsException
    makeException(List<RetriesExhaustedWithDetailsException> errors) {
    switch (errors.size()) {
      case 0:
        return null;
      case 1:
        return errors.get(0);
      default:
        List<Throwable> exceptions = new ArrayList<>();
        List<Row> actions = new ArrayList<>();
        List<String> hostnameAndPort = new ArrayList<>();
        errors.forEach(e -> {
          exceptions.addAll(e.exceptions);
          actions.addAll(e.actions);
          hostnameAndPort.addAll(e.hostnameAndPort);
        });
        return new RetriesExhaustedWithDetailsException(exceptions, actions, hostnameAndPort);
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public long getWriteBufferSize() {
    return this.writeBufferSize;
  }

  @Override
  public synchronized void setWriteBufferPeriodicFlush(long timeoutMs, long timerTickMs) {
    long originalTimeoutMs = this.writeBufferPeriodicFlushTimeoutMs.get();
    long originalTimerTickMs = this.writeBufferPeriodicFlushTimerTickMs.get();

    // Both parameters have minimal values.
    writeBufferPeriodicFlushTimeoutMs.set(Math.max(0, timeoutMs));
    writeBufferPeriodicFlushTimerTickMs
      .set(Math.max(MIN_WRITE_BUFFER_PERIODIC_FLUSH_TIMERTICK_MS, timerTickMs));

    // If something changed we stop the old Timer.
    if (
      writeBufferPeriodicFlushTimeoutMs.get() != originalTimeoutMs
        || writeBufferPeriodicFlushTimerTickMs.get() != originalTimerTickMs
    ) {
      if (writeBufferPeriodicFlushTimer != null) {
        writeBufferPeriodicFlushTimer.cancel();
        writeBufferPeriodicFlushTimer = null;
      }
    }

    // If we have the need for a timer and there is none we start it
    if (writeBufferPeriodicFlushTimer == null && writeBufferPeriodicFlushTimeoutMs.get() > 0) {
      writeBufferPeriodicFlushTimer = new Timer(true); // Create Timer running as Daemon.
      writeBufferPeriodicFlushTimer.schedule(new TimerTask() {
        @Override
        public void run() {
          BufferedMutatorImpl.this.timerCallbackForWriteBufferPeriodicFlush();
        }
      }, writeBufferPeriodicFlushTimerTickMs.get(), writeBufferPeriodicFlushTimerTickMs.get());
    }
  }

  @Override
  public long getWriteBufferPeriodicFlushTimeoutMs() {
    return writeBufferPeriodicFlushTimeoutMs.get();
  }

  @Override
  public long getWriteBufferPeriodicFlushTimerTickMs() {
    return writeBufferPeriodicFlushTimerTickMs.get();
  }

  @Override
  public void setRpcTimeout(int rpcTimeout) {
    this.rpcTimeout.set(rpcTimeout);
  }

  @Override
  public void setOperationTimeout(int operationTimeout) {
    this.operationTimeout.set(operationTimeout);
  }

  long getCurrentWriteBufferSize() {
    return currentWriteBufferSize.get();
  }

  /**
   * Count the mutations which haven't been processed.
   * @return count of undealt mutation
   */
  int size() {
    return undealtMutationCount.get();
  }

  /**
   * Count the mutations which haven't been flushed
   * @return count of unflushed mutation
   */
  int getUnflushedSize() {
    return writeAsyncBuffer.size();
  }

  QueueRowAccess createQueueRowAccess() {
    return new QueueRowAccess();
  }

  class QueueRowAccess implements RowAccess<Row>, Closeable {
    private int remainder = undealtMutationCount.getAndSet(0);
    private Mutation last = null;

    private void restoreLastMutation() {
      // restore the last mutation since it isn't submitted
      if (last != null) {
        writeAsyncBuffer.add(last);
        currentWriteBufferSize.addAndGet(last.heapSize());
        last = null;
      }
    }

    @Override
    public void close() {
      restoreLastMutation();
      if (remainder > 0) {
        undealtMutationCount.addAndGet(remainder);
        remainder = 0;
      }
    }

    @Override
    public Iterator<Row> iterator() {
      return new Iterator<Row>() {
        private int countDown = remainder;

        @Override
        public boolean hasNext() {
          return countDown > 0;
        }

        @Override
        public Row next() {
          restoreLastMutation();
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
          last = writeAsyncBuffer.poll();
          if (last == null) {
            throw new NoSuchElementException();
          }
          currentWriteBufferSize.addAndGet(-last.heapSize());
          --countDown;
          return last;
        }

        @Override
        public void remove() {
          if (last == null) {
            throw new IllegalStateException();
          }
          --remainder;
          last = null;
        }
      };
    }

    @Override
    public int size() {
      return remainder;
    }

    @Override
    public boolean isEmpty() {
      return remainder <= 0;
    }
  }
}


text:
package info.dourok.lruimage.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.widget.ImageView.ScaleType;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import info.dourok.lruimage.LruImage;

/**
 * Created by John on 2015/9/23.
 * Modified from volley
 */
public class WebImage extends UrlImage {

    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 10000;

    private final String url;
    /**
     * load Bitmap from net to memory
     *
     * @return bytes of bitmap
     * @throws IOException
     */
    byte[] tempData;

    public WebImage(String url) {
        this(url, 0, 0, null, null);
    }

    public WebImage(String url, int maxWidth, int maxHeight,
                    ScaleType scaleType, Config decodeConfig) {
        super(maxWidth, maxHeight, scaleType, decodeConfig);
        this.url = url;
        setCacheLevel(LruImage.CACHE_LEVEL_DISK_CACHE | LruImage.CACHE_LEVEL_MEMORY_CACHE);
    }

    private URLConnection newConnection() throws IOException {
        URLConnection conn = new URL(url).openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        return conn;
    }

    @Override
    protected void prepareData(Context context) throws IOException {
        URLConnection conn = newConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte data[];
        data = new byte[8192];
        final int total = conn.getContentLength();
        int sum = 0;
        int n;
        while ((n = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, n);
            progressUpdate(total, sum += n);
        }
        buffer.flush();
        tempData = buffer.toByteArray();
    }

    @Override
    protected Bitmap decodingBitmap(Context context, BitmapFactory.Options decodeOptions) {
        return BitmapFactory.decodeByteArray(tempData, 0, tempData.length, decodeOptions);
    }

    @Override
    protected void onDecodeFinish() {
        tempData = null;
    }

    @Override
    public String getKey() {
        String s = url + super.getKey();
        return Integer.toHexString(s.hashCode());
        //s = s.replace(":", "_").replace("/", "_").replace(".", "_");
        //return s.substring(s.length() > 64 ? s.length() - 64 : 0, s.length());
    }
}


text:
<?php

namespace app\modules\shop;

class Module extends \app\core\base\Module
{

    public function init()
    {
        parent::init();

        // \Yii::configure($this, require(__DIR__ . '/config.php'));

        // custom initialization code goes here
    }

}


text:
require "byebug/subcommands"

require "byebug/commands/enable/breakpoints"
require "byebug/commands/enable/display"

module Byebug
  #
  # Enabling custom display expressions or breakpoints.
  #
  class EnableCommand < Command
    include Subcommands

    self.allow_in_post_mortem = true

    def self.regexp
      /^\s* en(?:able)? (?:\s+ (.+))? \s*$/x
    end

    def self.description
      <<-DESCRIPTION
        en[able][[ b[reakpoints]| d[isplay])][ n1[ n2[ ...[ nn]]]]]

        #{short_description}
      DESCRIPTION
    end

    def self.short_description
      "Enables breakpoints or displays"
    end
  end
end


text:
package uk.ac.man.cs.llvm.ir.module;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;

import uk.ac.man.cs.llvm.bc.ParserListener;
import uk.ac.man.cs.llvm.bc.records.Records;
import uk.ac.man.cs.llvm.ir.ModuleGenerator;
import uk.ac.man.cs.llvm.ir.module.records.TypesRecord;
import uk.ac.man.cs.llvm.ir.types.ArrayType;
import uk.ac.man.cs.llvm.ir.types.FloatingPointType;
import uk.ac.man.cs.llvm.ir.types.FunctionType;
import uk.ac.man.cs.llvm.ir.types.IntegerType;
import uk.ac.man.cs.llvm.ir.types.MetaType;
import uk.ac.man.cs.llvm.ir.types.PointerType;
import uk.ac.man.cs.llvm.ir.types.StructureType;
import uk.ac.man.cs.llvm.ir.types.Type;
import uk.ac.man.cs.llvm.ir.types.VectorType;

public final class Types implements ParserListener, Iterable<Type> {

    public static Type[] toTypes(Types types, long[] args, long from, long to) {
        Type[] t = new Type[(int) (to - from)];

        for (int i = 0; i < t.length; i++) {
            t[i] = types.get(args[(int) from + i]);
        }

        return t;
    }

    private final ModuleGenerator generator;

    private Type[] table = new Type[0];

    private int size = 0;

    public Types(ModuleGenerator generator) {
        this.generator = generator;
    }

    @Override
    public Iterator<Type> iterator() {
        return Collections.unmodifiableList(Arrays.asList(table)).iterator();
    }

    @Override
    public void record(long id, long[] args) {
        TypesRecord record = TypesRecord.decode(id);
        Type type;

        switch (record) {
            case NUMBER_OF_ENTRIES:
                table = new Type[(int) args[0]];
                return;

            case VOID:
                type = MetaType.VOID;
                break;

            case FLOAT:
                type = FloatingPointType.FLOAT;
                break;

            case DOUBLE:
                type = FloatingPointType.DOUBLE;
                break;

            case LABEL:
                type = MetaType.LABEL;
                break;

            case OPAQUE:
                type = MetaType.OPAQUE;
                break;

            case INTEGER:
                type = new IntegerType((int) args[0]);
                break;

            case POINTER: {
                int idx = (int) args[0];

                if (idx > size) {
                    table[size] = new PointerType(null);
                    table[idx] = new UnresolvedPointeeType(size);
                    size++;
                    return;
                } else {
                    type = new PointerType(get(idx));
                }
                break;
            }
            case FUNCTION_OLD: {
                int i = 2;
                Type returnType = get(args[i++]);
                type = new FunctionType(returnType, toTypes(this, args, i, args.length), args[0] != 0);
                break;
            }
            case HALF:
                type = FloatingPointType.HALF;
                break;

            case ARRAY:
                type = new ArrayType(get(args[1]), (int) args[0]);
                break;

            case VECTOR:
                type = new VectorType(get(args[1]), (int) args[0]);
                break;

            case X86_FP80:
                type = FloatingPointType.X86_FP80;
                break;

            case FP128:
                type = FloatingPointType.FP128;
                break;

            case PPC_FP128:
                type = FloatingPointType.PPC_FP128;
                break;

            case METADATA:
                type = MetaType.METADATA;
                break;

            case X86_MMX:
                type = MetaType.X86_MMX;
                break;

            case STRUCT_ANON:
                type = new StructureType(args[0] != 0, toTypes(this, args, 1, args.length));
                break;

            case STRUCT_NAME: {
                String name = Records.toString(args);
                if (table[size] instanceof UnresolvedPointeeType) {
                    table[size] = new UnresolvedNamedPointeeType(name, ((UnresolvedPointeeType) table[size]).getIndex());
                } else {
                    table[size] = new UnresolvedNamedType(name);
                }
                return;
            }
            case STRUCT_NAMED: {
                StructureType structure = new StructureType(args[0] != 0, toTypes(this, args, 1, args.length));
                if (table[size] != null) {
                    if (table[size] instanceof UnresolvedNamedPointeeType) {
                        structure.setName(((UnresolvedNamedPointeeType) table[size]).getName());
                    } else {
                        structure.setName(((UnresolvedNamedType) table[size]).getName());
                    }
                }
                type = structure;
                break;
            }
            case FUNCTION:
                type = new FunctionType(get(args[1]), toTypes(this, args, 2, args.length), args[0] != 0);
                break;

            case TOKEN:
                type = MetaType.TOKEN;
                break;

            default:
                type = MetaType.UNKNOWN;
                break;
        }

        if (table[size] instanceof UnresolvedPointeeType) {
            PointerType pointer = (PointerType) table[((UnresolvedPointeeType) table[size]).getIndex()];
            pointer.setPointeeType(type);
            generator.createType(pointer);
        }
        table[size++] = type;
        generator.createType(type);
    }

    public int size() {
        return table.length;
    }

    public Type get(long index) {
        return table[(int) index];
    }

    private static class UnresolvedPointeeType implements Type {

        private final int idx;

        UnresolvedPointeeType(int idx) {
            this.idx = idx;
        }

        public int getIndex() {
            return idx;
        }

        @Override
        public int sizeof() {
            return 0;
        }
    }

    private static final class UnresolvedNamedPointeeType extends UnresolvedPointeeType {

        private final String name;

        UnresolvedNamedPointeeType(String name, int idx) {
            super(idx);
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    private static final class UnresolvedNamedType implements Type {

        private final String name;

        UnresolvedNamedType(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public int sizeof() {
            return 0;
        }
    }
}


text:
<?php

namespace Map\Service;

use Map\Entity\Map;
use Position\Entity\Area;
use Position\Entity\Position;

class MapService
{
	/**
	 * @var Map
	 */
	protected $map;

	public function __construct(
		Map $map
	)
	{
		$this->map = $map;
		$this->prepareMap();
	}

	/**
	 * @return Map
	 */
	public function getMap()
	{
		return $this->map;
	}

	protected function prepareMap()
	{
		$this->map->setArea(new Area(
			new Position(0, 0),
			new Position(1000, 1000)
		));
		$this->map->setSchema([]);
	}
}


text:
package com.tvajjala.test;

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

public class AssumeTest {

    @Test
    public void simpleAssumptionTest() {
        Assume.assumeFalse(true);
        Assert.assertTrue(true);
    }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require 'open3'

describe "Open3.pipeline" do
  it "needs to be reviewed for spec completeness"
end


text:
package org.hisp.dhis.api.mobile.model;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.xml.bind.annotation.XmlAttribute;

public class DataValue
    implements DataStreamSerializable
{
    private int id;

    private String clientVersion;

    private int categoryOptComboID;

    private String value;

    @XmlAttribute
    public int getId()
    {
        return id;
    }

    public void setId( int id )
    {
        this.id = id;
    }

    @XmlAttribute
    public String getValue()
    {
        return value;
    }

    public void setValue( String value )
    {
        this.value = value;
    }

    @XmlAttribute
    public int getCategoryOptComboID()
    {
        return categoryOptComboID;
    }

    public void setCategoryOptComboID( int categoryOptComboID )
    {
        this.categoryOptComboID = categoryOptComboID;
    }

    public String getClientVersion()
    {
        return clientVersion;
    }

    public void setClientVersion( String clientVersion )
    {
        this.clientVersion = clientVersion;
    }

    @Override
    public void serialize( DataOutputStream dataOutputStream )
        throws IOException
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void deSerialize( DataInputStream din )
        throws IOException
    {
        setId( din.readInt() );
        setCategoryOptComboID( din.readInt() );
        setValue( din.readUTF() );
    }

    @Override
    public void serializeVersion2_8( DataOutputStream dataOutputStream )
        throws IOException
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void serializeVersion2_9( DataOutputStream dataOutputStream )
        throws IOException
    {
        // TODO Auto-generated method stub
    }

    @Override
    public void serializeVersion2_10( DataOutputStream dataOutputStream )
        throws IOException
    {
        // TODO Auto-generated method stub

    }

}


text:
<?php

defined('_JEXEC') or die;

/**
 * Profile controller class for Users.
 *
 * @since  3.5
 */
class UsersControllerProfile_Base_Json extends JControllerLegacy
{
	/**
	 * Returns the updated options for help site selector
	 *
	 * @return  void
	 *
	 * @since   3.5
	 * @throws  Exception
	 */
	public function gethelpsites()
	{
		jimport('joomla.filesystem.file');

		// Set FTP credentials, if given
		JClientHelper::setCredentialsFromRequest('ftp');

		if (($data = file_get_contents('http://update.joomla.org/helpsites/helpsites.xml')) === false)
		{
			throw new Exception(JText::_('COM_CONFIG_ERROR_HELPREFRESH_FETCH'), 500);
		}
		elseif (!JFile::write(JPATH_ADMINISTRATOR . '/help/helpsites.xml', $data))
		{
			throw new Exception(JText::_('COM_CONFIG_ERROR_HELPREFRESH_ERROR_STORE'), 500);
		}

		$options = array_merge(
			array(
				JHtml::_('select.option', '', JText::_('JOPTION_USE_DEFAULT'))
			),
			JHelp::createSiteList(JPATH_ADMINISTRATOR . '/help/helpsites.xml')
		);

		echo json_encode($options);
		JFactory::getApplication()->close();
	}
}


text:
namespace eja
{
	// Component
	derived_id_component(session_component, session);

	// Container
	derived_type(session_list_component, list_component<session>);
	derived_type(session_map_component, map_component<std::string, session>);
	derived_type(session_queue_component, queue_component<session>);
	derived_type(session_vector_component, vector_component<session>);

	derived_type(session_entity_list_component, entity_list_component);
	derived_type(session_entity_map_component, entity_map_component);
	derived_type(session_entity_queue_component, entity_queue_component);
	derived_type(session_entity_vector_component, entity_vector_component);
}

#endif


text:
namespace Microsoft.Azure.Management.ContainerRegistry.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The definition of Azure Monitoring metrics list.
    /// </summary>
    public partial class OperationServiceSpecificationDefinition
    {
        /// <summary>
        /// Initializes a new instance of the
        /// OperationServiceSpecificationDefinition class.
        /// </summary>
        public OperationServiceSpecificationDefinition()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// OperationServiceSpecificationDefinition class.
        /// </summary>
        /// <param name="metricSpecifications">A list of Azure Monitoring
        /// metrics definition.</param>
        public OperationServiceSpecificationDefinition(IList<OperationMetricSpecificationDefinition> metricSpecifications = default(IList<OperationMetricSpecificationDefinition>))
        {
            MetricSpecifications = metricSpecifications;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets a list of Azure Monitoring metrics definition.
        /// </summary>
        [JsonProperty(PropertyName = "metricSpecifications")]
        public IList<OperationMetricSpecificationDefinition> MetricSpecifications { get; set; }

    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>cops_and_robots.test.map_tools.particle_layer module — Cops and Robots 1.0 documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

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

    <link rel="top" title="Cops and Robots 1.0 documentation" href="index.html"/>

         Cops and Robots

  <form id ="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

 Robo Tools

cops_and_robots.robo_tools.fusion package

cops_and_robots.robo_tools.cop module

cops_and_robots.robo_tools.iRobot_create module

cops_and_robots.robo_tools.planner module

cops_and_robots.robo_tools.robber module

cops_and_robots.robo_tools.robot module

     Cop

 Map Tools

cops_and_robots.map_tools.feasible_layer module

cops_and_robots.map_tools.human_interface module

cops_and_robots.map_tools.layer module

cops_and_robots.map_tools.map module

cops_and_robots.map_tools.map_obj module

cops_and_robots.map_tools.occupancy_layer module

cops_and_robots.map_tools.particle_layer module

cops_and_robots.map_tools.probability_layer module

cops_and_robots.map_tools.shape_layer module

        Cops and Robots

Docs »

cops_and_robots.test.map_tools.particle_layer module

           View page source

cops_and_robots.test.map_tools.particle_layer module¶

Provides a discrete particle representation of robot locations.

When using the discrete <tt class="docutils literal">fusion_engine</tt> type, the particle
layer is used to represent the distribution of a cop’s expecation of
robber locations. One particle layer exists per robot, with n particles
per particle layer, to estimate the collected probability of all
robbers’ locations.

class <tt class="descname">ParticleLayer</tt><big>(</big>particle_size=200, colorbar_visible=False, n_particles=2000, **kwargs<big>)</big>[source]¶

Bases: <tt class="xref py py-class docutils literal">cops_and_robots.map_tools.layer.Layer</tt>

Visually represents a collection of particles.

<col class="field-name" />
<col class="field-body" />

Parameters:

particle_size (int, optional) – The marker size of each particle. Default is 200.

colorbar_visible (bool, optional) – Whether to show the colorbar object. Default it False.

n_particles (int, optional) – Number of particles to display. Default is 2000.

**kwargs –
Keyword arguments given to the <tt class="docutils literal">Layer</tt> superclass.

<tt class="descname">plot</tt><big>(</big>robber_names, fusion_engine, **kwargs<big>)</big>[source]¶

Plot the particles as a scatter plot.

<col class="field-name" />
<col class="field-body" />

Parameters:

robber_names (list of str) – The list of all robbers.

fusion_engine (FusionEngine) – A robot’s fusion engine.

**kwargs –
Arguments passed to the scatter plot function.

Returns:
The scatter plot data.

Return type:
list of PathCollection

        © Copyright 2015, Nick Sweet.

  Sphinx theme provided by Read the Docs


text:
{% extends "Grundgeruest/ilja.html" %}

{% block kopfleiste %}

  {% if request.user.is_authenticated %}
    {% include "Grundgeruest/kopfleiste_nutzer.html" %}
  {% else %}
    {% include "Grundgeruest/kopfleiste_gast.html" %}
  {% endif %}

{% endblock kopfleiste %}

{% block menueleiste %}

        {% include "Grundgeruest/menueleiste.html" with liste_menue=liste_menue %}

{% endblock menueleiste %}


text:
using UnityEngine;
using System.Collections;

public class UtilityTools : MonoBehaviour
{
	public static UtilityTools Instance;

	IEnumerator LoadTexture2DFromDisk(string file_loc = "", Texture2D textureShader = null)
	{
		Debug.Log (file_loc);
		textureShader = new Texture2D(4, 4, TextureFormat.DXT5, false);
		WWW www = new WWW(file_loc);
		yield return www;
		textureShader = www.texture;
	}

	void Awake()
	{
		Instance = this;
	}
}


text:
Attention: Work is taking place on the wiki, the information here is mostly outdated. The build is no longer being maintained as it's undertaking a rewrite.

# Acolyte

Acolyte is an open source alternative runtime and compiler for projects written
in [GameMaker: Studio]. Games are compiled by first converting them into
compliant C++ code and then optionally piping them into a compiler of choice to
produce object files. These object files can then be linked directly with
swappable runtime components which provide systems like graphics, audio and
physics.

This is equivalent to the process undertaken by the proprietary [YoYo Compiler].

[GameMaker: Studio]: http://www.yoyogames.com/studio
[YoYo Compiler]: http://www.youtube.com/watch?v=i3ECuXBc7Ks

## Getting Started

### Build System

Acolyte uses [CMake] as its provider for build system tools. This requires some
initial setup, but offers many advantages over traditional GNU makefiles (such
as the ability to automatically generate IDE project files and compile outside
MinGW on Windows).

1. Download and install CMake from the [CMake downloads page] or from your
   systems package manager (`sudo apt-get install cmake` on Debian,
   `pacman -Sy cmake` on ArchLinux or even `brew install cmake` on OSX using
   [Homebrew]).
2. Open your system terminal and ensure that CMake is on path and that it is at
   least version 1.8. You can use `cmake --version` to test this.
3. Decide which build provider you would like to use for the next step. You can
   either leave this as default (Visual Studio on Windows, Makefiles on
   Linux/OSX) or pick one of `Unix Makefiles`, `Ninja`, `Xcode` or
   `CodeBlocks - Unix Makefiles`.
   See `cmake --help` for more information and additional generators.
4. Navigate to the top-level directory of this repository in your terminal. Run
   `cmake .` _or_ `cmake . -G"Unix Makefiles"`, optionally replacing
   `Unix Makefiles` with another generator picked above.

You can now use the build system of your choice to build Acolyte. If you chose
to generate makefiles this means that you can use `make` to build. If you used
Visual Studio (default on Windows) or Xcode, you can open the project file
generated in the top level directory and use the regular build system for that
particular IDE. Binaries can generally be found in the `build/` directory.

If you need to change which generator you would like to use, you should delete
`CMakeCache.txt` from the top-level directory and run one of the commands above
with your new desired generator. If you plan to swap generators frequently you
may decide to build outside the source tree using a command such as
`cmake ../path/to/source`.

[CMake]: http://cmake.org
[CMake downloads page]: http://cmake.org/cmake/resources/software.html
[Homebrew]: http://brew.sh
[as explained here]: http://www.cmake.org/Wiki/CMake_FAQ#CMake_does_not_generate_a_.22make_distclean.22_target._Why.3F

### Layout

Acolyte is split into seperate packages. These can be found in the `packages/`
directory of the source tree. Each package is compiled into a different static
library or binary. See `packages/README.md` for more information.

## Testing

[![Build Status](https://travis-ci.org/acolyte-sf/acolyte.png?branch=master)](https://travis-ci.org/acolytesf/acolyte)

### Unit Tests

This is under construction.

### Bug Reports

Use the [GitHub issue tracker] to file bug reports.

[GitHub issue tracker]: https://github.com/AcolyteSF/acolyte/issues

## Contributing

### IRC

Our IRC channel is `#acolyte` on `irc.freenode.net`.

### Style Guidelines

Style standards are adopted from the [Google C++ Style Guide]. Use common sense
when editing source files to make sure that formatting is consistent. Avoid
using pointers directly, don't use exceptions, allocate on the stack when
possible and be aware that templates or verbose code are preferred over using
preprocessor macros.

[Google C++ Style Guide]: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

### Pull Requests

Pull requests are accepted if they meet quality guidelines. To find out where
you can help out, you should first express interest on IRC.

## License

Acolyte is licensed under a BSD3-style license. A summary of the license is as
follows;

* Don't remove the license text from the source code.
* Include the license text when distributing binaries of Acolyte.
* Don't use Acolyte Strike Force or the names of any of it's members when
  advertising your products.

See `LICENSE` for more information.

Third party libraries and dependencies are licensed independently.

## Troubleshooting & Links

* [GM:S Reference](http://docs.yoyogames.com)
* [C/C++ Reference](http://en.cppreference.com/w/)
* [CMake Wiki](http://www.cmake.org/Wiki/CMake)
* [OpenGL Wiki](http://www.opengl.org/wiki/Main_Page)

You may also be interested in [ENIGMA].

[ENIGMA]: http://enigma-dev.org


text:
module ActiveSupport
  module Testing
    module Isolation
      require "thread"

      def self.included(klass) #:nodoc:
        klass.class_eval do
          parallelize_me!
        end
      end

      def self.forking_env?
        !ENV["NO_FORK"] && Process.respond_to?(:fork)
      end

      def run
        serialized = run_in_isolation do
          super
        end

        Marshal.load(serialized)
      end

      module Forking
        def run_in_isolation(&blk)
          read, write = IO.pipe
          read.binmode
          write.binmode

          pid = fork do
            read.close
            yield
            begin
              if error?
                failures.map! { |e|
                  begin
                    Marshal.dump e
                    e
                  rescue TypeError
                    ex = Exception.new e.message
                    ex.set_backtrace e.backtrace
                    Minitest::UnexpectedError.new ex
                  end
                }
              end
              result = Marshal.dump(self.dup)
            end

            write.puts [result].pack("m")
            exit!
          end

          write.close
          result = read.read
          Process.wait2(pid)
          return result.unpack("m")[0]
        end
      end

      module Subprocess
        ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)

        # Crazy H4X to get this working in windows / jruby with
        # no forking.
        def run_in_isolation(&blk)
          require "tempfile"

          if ENV["ISOLATION_TEST"]
            yield
            File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
              file.puts [Marshal.dump(dup)].pack("m")
            end
            exit!
          else
            Tempfile.open("isolation") do |tmpfile|
              env = {
                "ISOLATION_TEST" => self.class.name,
                "ISOLATION_OUTPUT" => tmpfile.path
              }

              load_paths = $-I.map { |p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
              orig_args = ORIG_ARGV.join(" ")
              test_opts = "-n#{self.class.name}##{self.name}"
              command = "#{Gem.ruby} #{load_paths} #{$0} '#{orig_args}' #{test_opts}"

              # IO.popen lets us pass env in a cross-platform way
              child = IO.popen(env, command)

              begin
                Process.wait(child.pid)
              rescue Errno::ECHILD # The child process may exit before we wait
                nil
              end

              return tmpfile.read.unpack("m")[0]
            end
          end
        end
      end

      include forking_env? ? Forking : Subprocess
    end
  end
end


text:
// This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.

package encryption.actions;

import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixObject;
import com.mendix.webui.CustomJavaAction;
import encryption.pgp.PGPFileProcessor;

/**
 * Encrypt the FileDocument using PGP encryption.
 *  This is allowed to be the same FileDocument instance and the action will just store the encrypted file in the provided entity.
 *
 * The certificate must be a valid public PGP key provided by the external party. If you want to sign the document you can optionally provide the private key to used for signing.
 * The external party would have to validate the signature against the pub key from signature key.
 *
 * This action will either return true or an exception
 */
public class PGPEncryptDocument extends CustomJavaAction<java.lang.Boolean>
{
	private IMendixObject __ExternalPublicKey;
	private system.proxies.FileDocument ExternalPublicKey;
	private IMendixObject __DocumentToEncrypt;
	private system.proxies.FileDocument DocumentToEncrypt;
	private IMendixObject __OutputDocument;
	private system.proxies.FileDocument OutputDocument;
	private IMendixObject __SigningCertificate;
	private encryption.proxies.PGPCertificate SigningCertificate;

	public PGPEncryptDocument(IContext context, IMendixObject ExternalPublicKey, IMendixObject DocumentToEncrypt, IMendixObject OutputDocument, IMendixObject SigningCertificate)
	{
		super(context);
		this.__ExternalPublicKey = ExternalPublicKey;
		this.__DocumentToEncrypt = DocumentToEncrypt;
		this.__OutputDocument = OutputDocument;
		this.__SigningCertificate = SigningCertificate;
	}

	@java.lang.Override
	public java.lang.Boolean executeAction() throws Exception
	{
		this.ExternalPublicKey = __ExternalPublicKey == null ? null : system.proxies.FileDocument.initialize(getContext(), __ExternalPublicKey);

		this.DocumentToEncrypt = __DocumentToEncrypt == null ? null : system.proxies.FileDocument.initialize(getContext(), __DocumentToEncrypt);

		this.OutputDocument = __OutputDocument == null ? null : system.proxies.FileDocument.initialize(getContext(), __OutputDocument);

		this.SigningCertificate = __SigningCertificate == null ? null : encryption.proxies.PGPCertificate.initialize(getContext(), __SigningCertificate);

		// BEGIN USER CODE

		PGPFileProcessor p = new PGPFileProcessor();
		p.setInputFileDocument(this.DocumentToEncrypt.getMendixObject());
		p.setOutputFileDocument(this.OutputDocument.getMendixObject());
		p.setAsciiArmored(true);
		p.setPublicKeyFileName(this.ExternalPublicKey.getMendixObject());

		// If we are going to validate the signature we also need the private key and passphrase
		// p.setPassphrase( Microflows.decrypt(getContext(), this.SigningCertificate.getPassPhrase_Encrypted()) );

		return p.encrypt(getContext());
		// END USER CODE
	}

	/**
	 * Returns a string representation of this action
	 */
	@java.lang.Override
	public java.lang.String toString()
	{
		return "PGPEncryptDocument";
	}

	// BEGIN EXTRA CODE
	// END EXTRA CODE
}


text:
package http

import (
	"net/http"

	"github.com/wothing/caldav-go/utils"
)

// a client for making HTTP requests
type Client struct {
	native         *http.Client
	server         *Server
	requestHeaders map[string]string
}

func (c *Client) SetHeader(key string, value string) {
	if c.requestHeaders == nil {
		c.requestHeaders = map[string]string{}
	}
	c.requestHeaders[key] = value
}

// downcasts to the native HTTP interface
func (c *Client) Native() *http.Client {
	return c.native
}

// returns the embedded HTTP server reference
func (c *Client) Server() *Server {
	return c.server
}

// executes an HTTP request
func (c *Client) Do(req *Request) (*Response, error) {
	for key, value := range c.requestHeaders {
		req.Header.Add(key, value)
	}
	if resp, err := c.Native().Do((*http.Request)(req)); err != nil {
		return nil, utils.NewError(c.Do, "unable to execute HTTP request", c, err)
	} else {
		return NewResponse(resp), nil
	}
}

// creates a new client for communicating with an HTTP server
func NewClient(server *Server, native *http.Client) *Client {
	return &Client{server: server, native: native}
}

// creates a new client for communicating with a server
// uses the default HTTP client from net/http
func NewDefaultClient(server *Server) *Client {
	return NewClient(server, http.DefaultClient)
}


text:
require "spec_helper"
require "rift/parser"

describe Rift::Parser do
  let(:parser) { Rift::Parser.new }

  describe ".on_error" do
    it "should raise a parse error" do
      expect {
        parser.on_error(3, 'a', [])
      }.to raise_error "Unexpected token IDENTIFIER 'a' on line "
    end
  end

  describe ".parse" do
    context "with an empty string" do
      it "should return an empty array" do
        expect(parser.parse("")).to be_empty
      end
    end

    context "with valid thrift IDL" do
      it "should return a syntax tree" do
        expect(parser.parse("struct X { }").size).to eq(1)
      end
    end

    context "with invalid thrift IDL" do
      it "should raise an error" do
        expect {
          parser.parse("a")
        }.to raise_error "Unexpected token IDENTIFIER 'a' on line 1"
      end
    end

    it "should permit comments" do
      expression = <<-eos
        // comment
        struct X { /* * / comment */ }
        # comment
        /**
         * comment
         */
        struct Y { 1: required /*comment */ i32 x; }
      eos

      expect(parser.parse(expression).size).to eq(2)
    end
  end
end


text:
#include </usr/local/sicstus/include/sicstus/sicstus.h>
#include <stdio.h>
#include <string.h>
#include "types.h"
#include "input_output.h"
#include "background.h"

/*========================================================================
  query_literal
  =========================================================================
  */

int query_literal(tliteral *a_literal, targ *a_cube_args, int a_part,int *a_substitution, int *a_result)
{
  /* Tertius Related Variables */
  register int the_result;
  register int the_arity;

  int the_error = 0 ;

  /* Prolog Query Related Variables */
  int arg_no,param_no,call_result;
  SP_term_ref arg,arg_list;

  /* Initiating 'the_arity' */
  the_arity = the_predicate_table[a_literal->predicate].num_param + the_predicate_table[a_literal->predicate].arity;

  /* Initialise the variable 'X' */
  call_result = SP_put_variable(the_variable);
  if(call_result!=1){
    /*    printf("Variable not constructed\n");*/
    return ERR_PROLOG;
  }

  /*Add all arguments to 'arg_list' */
  arg = SP_new_term_ref();
  if(arg==0){
    /*    printf("Term reference for 'arg' not constructed\n");*/
    return ERR_PROLOG;
  }
  arg_list = SP_new_term_ref();
  if(arg_list==0){
    /*    printf("Term reference for 'arg_list' not constructed\n");*/
    return ERR_PROLOG;
  }
  arg_no = the_predicate_table[a_literal->predicate].arity;
  param_no = the_predicate_table[a_literal->predicate].num_param;
  while (param_no + arg_no > 0) {
    /* Check whether the argument is a parameter */
    if (the_predicate_table[a_literal->predicate].params[param_no + arg_no - 1] == TRUE) {
      call_result = SP_cons_list(arg_list,the_type_table[the_predicate_table[a_literal->predicate].types[param_no-1]]
				 .term_ref[0] [the_predicate_table[a_literal->predicate]
					     .subpredicates[a_literal->subpredicate]->val_params[param_no-1]],arg_list);
      if(call_result!=1) {
	/*	printf("'arg' not added to list\n");*/
	return ERR_PROLOG;
      }
      param_no -= 1;
    }
    /* Check whether the argument is a variable */
    else if (a_cube_args[a_literal->args[arg_no-1]].flip == VAR) {
      /* The argument is a variable */
      call_result = SP_cons_list(arg_list,the_type_table[the_predicate_table[a_literal->predicate].types[the_predicate_table[a_literal->predicate].num_param + arg_no-1]].term_ref[a_part][a_substitution[a_literal->args[arg_no-1]]],arg_list);
      if(call_result!=1){
	/*	printf("'arg' not added to list\n");*/
	return ERR_PROLOG;
      }
      arg_no -= 1;
    }
    else {
      /* The argument is a constant */
      call_result = SP_cons_list(arg_list,the_type_table[the_predicate_table[a_literal->predicate].types[the_predicate_table[a_literal->predicate].num_param + arg_no-1]].term_ref[0][a_cube_args[arg_no-1].value],arg_list);
      if(call_result!=1){
	/*	printf("'arg' not added to list\n");*/
	return ERR_PROLOG;
      }
      arg_no -= 1;
    }
  }

  /* Add Predicate to List */
  call_result = SP_cons_list(arg_list,the_predicate_table[a_literal->predicate].term_ref,arg_list);
  if(call_result!=1){
    /*    printf("'the_arg' not added to list\n");*/
    return ERR_PROLOG;
  }

  /* Create literal 'X=..[arg1,arg2,...]' */
  call_result = SP_cons_functor(arg,SP_atom_from_string("=.."),2,the_variable,arg_list);
  if(call_result!=1){
    /*    printf("Term 'X =.. [arg1,arg2,...]' not created");*/
    return ERR_PROLOG;
  }

  /* Query 'X=..[arg1,arg2,...],X' */
  the_result = SP_query(the_conjunction_reference,arg,the_variable);
  if(the_result==-1){
    /*    printf("Query not posed\n");*/
    return ERR_PROLOG;
  }
  the_prolog_query_count++;

  /* Count prolog query and garbage collect */
  if(the_prolog_query_count>=GARBAGE_COLLECT_LIMIT){
    call_result = SP_query(the_garbage_collect_reference,0);
    if(call_result!=1){
      /*      printf("Did not garbage collect\n");*/
      return ERR_PROLOG;
    }
    the_prolog_query_count=0;
  }

  /* Return result */
  *a_result = the_result;
  return the_error;
}