text:
#include "aes.h"

/*
 * Notes on chosen AES implementations:
 *
 * We only include implementations that are constant-time, or at least include
 * some hardening measures against cache-timing attacks.  By necessity we
 * tolerate implementations that try to be "constant-time" by prefetching the
 * lookup table(s) into cache, though this isn't guaranteed to be sufficient.
 *
 * For the portable implementation, we use aes_ti.c from Linux.  This is a
 * staightforward AES implementation that uses the 256-byte S-box and 256-byte
 * inverse S-box.  Each is prefetched before use.
 *
 * For 32-bit ARM: for AES-XTS we use the NEON bit-sliced implementation from
 * Linux; this is fastest and also constant-time.  For single blocks, we use the
 * ARM scalar AES cipher from Linux, which uses a 1024-byte table for
 * encryption, and a 1024-byte and a 256-byte table for decryption.  Even after
 * prefetching these tables, this implementation is much faster than aes_ti.c.
 * The 1024-byte tables combine the SubBytes (or InvSubBytes) and MixColumns (or
 * InvMixColumns) steps.  Normally 4096-byte tables would be needed for this,
 * but since rotations are "free" in ARM assembly only the first part is needed.
 */

#ifdef __arm__
void aesbs_convert_key(u8 out[], u32 const rk[], int rounds);
void aesbs_xts_encrypt(u8 out[], u8 const in[], u8 const rk[], int rounds,
		       int blocks, u8 iv[]);
void aesbs_xts_decrypt(u8 out[], u8 const in[], u8 const rk[], int rounds,
		       int blocks, u8 iv[]);
#endif

static void aes_setkey(struct aes_ctx *ctx, const u8 *key, int key_len)
{
	int err;

#ifdef __arm__
	err = aesti_expand_key(&ctx->aes_ctx, key, key_len);
	ASSERT(err == 0);
	ctx->rounds = 6 + key_len / 4;
	aesbs_convert_key(ctx->rk, ctx->aes_ctx.key_enc, ctx->rounds);
#else
	err = aesti_set_key(&ctx->aes_ctx, key, key_len);
	ASSERT(err == 0);
#endif
}

void aes128_setkey(struct aes_ctx *ctx, const u8 *key)
{
	aes_setkey(ctx, key, AES_KEYSIZE_128);
}

void aes256_setkey(struct aes_ctx *ctx, const u8 *key)
{
	aes_setkey(ctx, key, AES_KEYSIZE_256);
}

void aes_encrypt(const struct aes_ctx *ctx, u8 *out, const u8 *in)
{
#ifdef __arm__
	__aes_arm_encrypt(ctx->aes_ctx.key_enc, aes_nrounds(&ctx->aes_ctx),
			  in, out);
#else
	aesti_encrypt(&ctx->aes_ctx, out, in);
#endif
}

void aes_decrypt(const struct aes_ctx *ctx, u8 *out, const u8 *in)
{
#ifdef __arm__
	__aes_arm_decrypt(ctx->aes_ctx.key_dec, aes_nrounds(&ctx->aes_ctx),
			  in, out);
#else
	aesti_decrypt(&ctx->aes_ctx, out, in);
#endif
}

#ifdef __arm__
static void aes_xts_encrypt_neon(const struct aes_ctx *ctx,
				 u8 *out, const u8 *in,
				 unsigned int nbytes, void *tweak)
{
	aesbs_xts_encrypt(out, in, ctx->rk, ctx->rounds,
			  nbytes / AES_BLOCK_SIZE, tweak);
}

static void aes_xts_decrypt_neon(const struct aes_ctx *ctx,
				 u8 *out, const u8 *in,
				 unsigned int nbytes, void *tweak)
{
	aesbs_xts_decrypt(out, in, ctx->rk, ctx->rounds,
			  nbytes / AES_BLOCK_SIZE, tweak);
}
#endif /* __arm__ */

void test_aes(void)
{
	static const u8 tv128_key[16] =
		"\x00\x01\x02\x03\x04\x05\x06\x07"
		"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";
	static const u8 tv128_plaintext[16] =
		"\x00\x11\x22\x33\x44\x55\x66\x77"
		"\x88\x99\xaa\xbb\xcc\xdd\xee\xff";
	static const u8 tv128_ciphertext[16] =
		"\x69\xc4\xe0\xd8\x6a\x7b\x04\x30"
		"\xd8\xcd\xb7\x80\x70\xb4\xc5\x5a";

	static const u8 tv256_key[32] =
		"\x00\x01\x02\x03\x04\x05\x06\x07"
		"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
		"\x10\x11\x12\x13\x14\x15\x16\x17"
		"\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f";
	static const u8 tv256_plaintext[16] =
		"\x00\x11\x22\x33\x44\x55\x66\x77"
		"\x88\x99\xaa\xbb\xcc\xdd\xee\xff";
	static const u8 tv256_ciphertext[16] =
		"\x8e\xa2\xb7\xca\x51\x67\x45\xbf"
		"\xea\xfc\x49\x90\x4b\x49\x60\x89";
	struct aes_ctx ctx;
	u8 block[16];

	aes128_setkey(&ctx, tv128_key);
	aes_encrypt(&ctx, block, tv128_plaintext);
	ASSERT(!memcmp(block, tv128_ciphertext, 16));
	aes_decrypt(&ctx, block, block);
	ASSERT(!memcmp(block, tv128_plaintext, 16));

	aes256_setkey(&ctx, tv256_key);
	aes_encrypt(&ctx, block, tv256_plaintext);
	ASSERT(!memcmp(block, tv256_ciphertext, 16));
	aes_decrypt(&ctx, block, block);
	ASSERT(!memcmp(block, tv256_plaintext, 16));

#define ALGNAME		"AES-128"
#define BLOCK_BYTES	16
#define KEY_BYTES	16
#define KEY		struct aes_ctx
#define SETKEY		aes128_setkey
#define ENCRYPT		aes_encrypt
#define DECRYPT		aes_decrypt
#ifdef __arm__
#  define XTS_ENCRYPT_SIMD aes_xts_encrypt_neon
#  define XTS_DECRYPT_SIMD aes_xts_decrypt_neon
#endif
#include "xts_benchmark_template.h"

#define ALGNAME		"AES-256"
#define BLOCK_BYTES	16
#define KEY_BYTES	32
#define KEY		struct aes_ctx
#define SETKEY		aes256_setkey
#define ENCRYPT		aes_encrypt
#define DECRYPT		aes_decrypt
#ifdef __arm__
#  define XTS_ENCRYPT_SIMD aes_xts_encrypt_neon
#  define XTS_DECRYPT_SIMD aes_xts_decrypt_neon
#endif
#include "xts_benchmark_template.h"
}


text:
{-# LANGUAGE TemplateHaskell #-}

module Common.Types (
    Events
   ,EventsTag
   ,EventsMonad
   ,emptyEvents
   ,events
   ,pushEvent
   ,popEvent
) where

import           Data.Dynamic
import qualified Control.Monad.Ether.State.Strict as ES
import           Control.Ether.TH

newtype Events = EVList [Dynamic]

ethereal "EventsTag" "events"

type EventsMonad = ES.MonadState EventsTag Events

pushEvent'pure :: Typeable a => a -> Events -> Events
pushEvent'pure x (EVList xs) = EVList $ toDyn x:xs

event_pattern :: Typeable a => Events -> Maybe (a , Events)
event_pattern (EVList []) = Nothing
event_pattern (EVList (x:xs))
                     | Just x' <- fromDynamic x
                     = Just (x', EVList xs)
event_pattern (EVList (_:_)) = Nothing

--pattern Event x xs <- (event_pattern' -> Just (x,xs))

pushEvent :: (EventsMonad m, Typeable a) => a -> m ()
pushEvent x =
    ES.modify events (pushEvent'pure x)

popEvent :: (EventsMonad m, Typeable a) => m (Maybe a)
popEvent = do
    x <- ES.get events
    case event_pattern x of
         Nothing -> return Nothing
         Just (x,xs) -> do
             ES.put events xs
             return (Just x)

runEvents :: (EventsMonad m, Typeable a) => (a -> m (Maybe b)) -> m (Maybe b)
runEvents f = do
    x <- popEvent
    case x of
         Nothing -> return Nothing
         Just v  -> f v

emptyEvents :: Events
emptyEvents = EVList []

redpajama_set_name: RedPajamaGithub


text:
package org.mockserver.serialization;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import org.mockserver.serialization.model.WebSocketMessageDTO;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;

import java.io.IOException;
import java.util.Map;

/**
 * @author jamesdbloom
 */
public class WebSocketMessageSerializer {

    private ObjectMapper objectMapper = ObjectMapperFactory.createObjectMapper();
    private Map<Class, Serializer> serializers;

    public WebSocketMessageSerializer(MockServerLogger mockServerLogger) {
        serializers = ImmutableMap.of(
            HttpRequest.class, new HttpRequestSerializer(mockServerLogger),
            HttpResponse.class, new HttpResponseSerializer(mockServerLogger)
        );
    }

    public String serialize(Object message) throws JsonProcessingException {
        if (serializers.containsKey(message.getClass())) {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new WebSocketMessageDTO().setType(message.getClass().getName()).setValue(serializers.get(message.getClass()).serialize((message))));
        } else {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new WebSocketMessageDTO().setType(message.getClass().getName()).setValue(objectMapper.writeValueAsString(message)));
        }
    }

    public Object deserialize(String messageJson) throws ClassNotFoundException, IOException {
        WebSocketMessageDTO webSocketMessageDTO = objectMapper.readValue(messageJson, WebSocketMessageDTO.class);
        if (webSocketMessageDTO.getType() != null && webSocketMessageDTO.getValue() != null) {
            Class format = Class.forName(webSocketMessageDTO.getType());
            if (serializers.containsKey(format)) {
                return serializers.get(format).deserialize(webSocketMessageDTO.getValue());
            } else {
                return objectMapper.readValue(webSocketMessageDTO.getValue(), format);
            }
        } else {
            return null;
        }
    }
}


text:
package com.archermind.coolweather.gson;

/**
 * Created by archermind on 17-8-16.
 */

public class AQI {
    public AQICity city;
    public class AQICity{
        public String aqi;
        public String pm25;
    }
}


text:
/*
Sphinx-Gallery has compatible CSS to fix default sphinx themes
Tested for Sphinx 1.3.1 for all themes: default, alabaster, sphinxdoc,
scrolls, agogo, traditional, nature, haiku, pyramid
Tested for Read the Docs theme 0.1.7 */
.sphx-glr-thumbcontainer {
  background: #fff;
  border: solid #fff 1px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  box-shadow: none;
  float: left;
  margin: 5px;
  min-height: 230px;
  padding-top: 5px;
  position: relative;
}
.sphx-glr-thumbcontainer:hover {
  border: solid #b4ddfc 1px;
  box-shadow: 0 0 15px rgba(142, 176, 202, 0.5);
}
.sphx-glr-thumbcontainer a.internal {
  bottom: 0;
  display: block;
  left: 0;
  padding: 150px 10px 0;
  position: absolute;
  right: 0;
  top: 0;
}
/* Next one is to avoid Sphinx traditional theme to cover all the
thumbnail with its default link Background color */
.sphx-glr-thumbcontainer a.internal:hover {
  background-color: transparent;
}

.sphx-glr-thumbcontainer p {
  margin: 0 0 .1em 0;
}
.sphx-glr-thumbcontainer .figure {
  margin: 10px;
  width: 160px;
}
.sphx-glr-thumbcontainer img {
  display: inline;
  max-height: 112px;
  max-width: 160px;
}
.sphx-glr-thumbcontainer[tooltip]:hover:after {
  background: rgba(0, 0, 0, 0.8);
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  color: #fff;
  content: attr(tooltip);
  left: 95%;
  padding: 5px 15px;
  position: absolute;
  z-index: 98;
  width: 220px;
  bottom: 52%;
}
.sphx-glr-thumbcontainer[tooltip]:hover:before {
  border: solid;
  border-color: #333 transparent;
  border-width: 18px 0 0 20px;
  bottom: 58%;
  content: '';
  left: 85%;
  position: absolute;
  z-index: 99;
}

.sphx-glr-script-out {
  color: #888;
  margin: 0;
}
p.sphx-glr-script-out {
    padding-top: 0.7em;
}
.sphx-glr-script-out .highlight {
  background-color: transparent;
  margin-left: 2.5em;
  margin-top: -2.1em;
}
.sphx-glr-script-out .highlight pre {
  background-color: #fafae2;
  border: 0;
  max-height: 30em;
  overflow: auto;
  padding-left: 1ex;
  margin: 0px;
  word-break: break-word;
}
.sphx-glr-script-out + p {
  margin-top: 1.8em;
}
blockquote.sphx-glr-script-out {
  margin-left: 0pt;
}
.sphx-glr-script-out.highlight-pytb .highlight pre {
  color: #000;
  background-color: #ffe4e4;
  border: 1px solid #f66;
  margin-top: 10px;
  padding: 7px;
}

div.sphx-glr-footer {
    text-align: center;
}

div.sphx-glr-download {
  margin: 1em auto;
  vertical-align: middle;
}

div.sphx-glr-download a {
  background-color: #ffc;
  background-image: linear-gradient(to bottom, #FFC, #d5d57e);
  border-radius: 4px;
  border: 1px solid #c2c22d;
  color: #000;
  display: inline-block;
  font-weight: bold;
  padding: 1ex;
  text-align: center;
}

div.sphx-glr-download code.download {
  display: inline-block;
  white-space: normal;
  word-break: normal;
  overflow-wrap: break-word;
  /* border and background are given by the enclosing 'a' */
  border: none;
  background: none;
}

div.sphx-glr-download a:hover {
  box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
  text-decoration: none;
  background-image: none;
  background-color: #d5d57e;
}

.sphx-glr-example-title:target::before {
  display: block;
  content: "";
  margin-top: -50px;
  height: 50px;
  visibility: hidden;
}

ul.sphx-glr-horizontal {
  list-style: none;
  padding: 0;
}
ul.sphx-glr-horizontal li {
  display: inline;
}
ul.sphx-glr-horizontal img {
  height: auto !important;
}

.sphx-glr-single-img {
  margin: auto;
  display: block;
  max-width: 100%;
}

.sphx-glr-multi-img {
  max-width: 42%;
  height: auto;
}

div.sphx-glr-animation {
  margin: auto;
  display: block;
  max-width: 100%;
}
div.sphx-glr-animation .animation{
  display: block;
}

p.sphx-glr-signature a.reference.external {
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  padding: 3px;
  font-size: 75%;
  text-align: right;
  margin-left: auto;
  display: table;
}

.sphx-glr-clear{
  clear: both;
}

a.sphx-glr-backref-instance {
  text-decoration: none;
}


text:
<component name="libraryTable">
  <library name="play-services-nearby-9.0.1">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.google.android.gms/play-services-nearby/9.0.1/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.google.android.gms/play-services-nearby/9.0.1/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<?php

namespace Framework\SeguridadBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * FuncionalidadRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PermisoCompositeRepository extends EntityRepository {

}


text:
class MetaNexus::Wow::Item < MetaNexus::Wow

  # Find Item in Battle.net WoW Api
  # Required arguments:
  # id      - item id
  #
  # Example:
  #   item = MetaNexus::Wow::Item
  #   item.find(18803)
  # Response in Hash:
  #   {"id"=>18803, "disenchantingSkillRank"=>225, "description"=>"Property of Finkle Einhorn, ...
  #
  # Find Item set in Battle.net WoW Api
  # Required arguments:
  # set_id  - set id
  # Example:
  #   item = MetaNexus::Wow::Item
  #   item.set(1060)
  # Response in Hash:
  #   {"id"=>1060, "name"=>"Deep Earth Vestments", "setBonuses"=>[{"description"=>"Reduces the mana cost of ...
  #

  def self.find(id)
    call_url = "#{client.url}/item/#{id}?locale=#{MetaNexus.config.locale}&apikey=#{MetaNexus.config.api_key}"
    MetaNexus::Api.call_api(call_url)
  end

  def self.set(id)
    call_url = "#{client.url}/item/set/#{id}?locale=#{MetaNexus.config.locale}&apikey=#{MetaNexus.config.api_key}"
    MetaNexus::Api.call_api(call_url)
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Recovery procedures</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
    <link rel="up" href="transapp.html" title="Chapter 11.  Berkeley DB Transactional Data Store Applications" />
    <link rel="prev" href="transapp_logfile.html" title="Log file removal" />
    <link rel="next" href="transapp_hotfail.html" title="Hot failover" />

          Recovery procedures

          Prev
          Chapter 11.
		Berkeley DB Transactional Data Store Applications

           Next

Recovery procedures

The fifth component of the infrastructure, recovery procedures, concerns
the recoverability of the database.  After any application or system
failure, there are two possible approaches to database recovery:

There is no need for recoverability, and all databases can be re-created
from scratch.  Although these applications may still need transaction
protection for other reasons, recovery usually consists of removing the
Berkeley DB environment home directory and all files it contains, and then
restarting the application.
Such an application may use the DB_TXN_NOT_DURABLE flag to avoid
writing log records.

        It is necessary to recover information after system or application
        failure.  In this case, recovery processing must be performed on
        any database environments that were active at the time of the
        failure.  Recovery processing involves running the db_recover utility or
        calling the DB_ENV->open() method with the DB_RECOVER or
        DB_RECOVER_FATAL flags.

        During recovery processing, all database changes made by aborted or
        unfinished transactions are undone, and all database changes made
        by committed transactions are redone, as necessary.  Database
        applications must not be restarted until recovery completes.  After
        recovery finishes, the environment is properly initialized so that
        applications may be restarted.

If performing recovery, there are two types of recovery processing:
normal and catastrophic.
Which you choose depends on the source for the database and log files you are
using to recover.

    If up-to-the-minute database and log files are accessible on a stable
    filesystem, normal recovery is sufficient.  Run the db_recover utility or
    call the DB_ENV->open() method specifying the DB_RECOVER flag.  However, the
    normal recovery case never includes
    recovery using hot backups of the database environment.  For example,
    you cannot perform a hot backup of databases and log files, restore the
    backup and then run normal recovery — you must always run catastrophic
    recovery when using hot backups.

    If the database or log files have been destroyed or corrupted, or
    normal recovery fails, catastrophic recovery is required.  For example,
    catastrophic failure includes the case where the disk drive on which
    the database or log files are stored has been physically destroyed, or
    when the underlying filesystem is corrupted and the operating system's
    normal filesystem checking procedures cannot bring that filesystem to a
    consistent state.  This is often difficult to detect, and a common sign
    of the need for catastrophic recovery is when normal Berkeley DB
    recovery procedures fail, or when checksum errors are displayed during
    normal database procedures.  When catastrophic recovery is necessary,
    take the following steps:

Restore the most recent snapshots of the database and log files from
the backup media into the directory where recovery will be performed.

        If any log files were archived since the last snapshot was made,
        they should be restored into the directory where recovery will be
        performed.

        If any log files are available from the database environment that
        failed (for example, the disk holding the database files crashed,
        but the disk holding the log files is fine), those log files should
        be copied into the directory where recovery will be performed.

        Be sure to restore all log files in the order they were written.
        The order is important because it's possible the same log file
        appears on multiple backups, and you want to run recovery using the
        most recent version of each log file.

        Run the db_recover utility, specifying its -c option; or call the DB_ENV->open() method,
        specifying the DB_RECOVER_FATAL flag.  The catastrophic recovery
        process will review the logs and database files to bring the
        environment databases to a consistent state as of the time of the
        last uncorrupted log file that is found.  It is important to
        realize that only transactions committed before that date will
        appear in the databases.

        It is possible to re-create the database in a location different
        from the original by specifying appropriate pathnames to the
        -h option of the db_recover utility. In
        order for this to work properly, it is important that your
        application refer to files by names relative to the database home
        directory or the pathname(s) specified in calls to
        DB_ENV->set_data_dir(), instead of using full pathnames.

          Prev

            Up

           Next

          Log file removal

            Home

           Hot failover


text:
declare @tableName nvarchar(max) = '[' + @schema + '].[' + @tablePrefix + 'SubscriptionData]';

if not exists
(
    select *
    from sys.objects
    where
        object_id = object_id(@tableName) and
        type in ('U')
)
begin
declare @createTable nvarchar(max);
set @createTable = '
    create table ' + @tableName + '(
        Subscriber nvarchar(200) not null,
        Endpoint nvarchar(200),
        MessageType nvarchar(200) not null,
        PersistenceVersion varchar(23) not null,
        primary key clustered
        (
            Subscriber,
            MessageType
        )
    )
';
exec(@createTable);
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
    <artifactId>washing-scheduler</artifactId>
    <groupId>ch.protonmail.vladyslavbond</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>
    <groupId>ch.protonmail.vladyslavbond.washing-scheduler</groupId>
    <artifactId>washing-scheduler-domain</artifactId>
    <name>washing-scheduler-domain</name>
    <dependencies>
    	<dependency>
    		<groupId>
    			ch.protonmail.vladyslavbond.washing-scheduler
    		</groupId>
    		<artifactId>washing-scheduler-datasource</artifactId>
    		<version>1.0-SNAPSHOT</version>
    	</dependency>
    	<dependency>
    		<groupId>org.postgresql</groupId>
    		<artifactId>postgresql</artifactId>
    		<version>9.4-1206-jdbc42</version>
    	</dependency>
    </dependencies>
</project>


text:
import {Component} from 'angular2/core';

@Component({
    templateUrl: 'app/views/something/somethingViewComponent.html'

})

export class SomethingView {}


text:
package com.github.flyinghe.tools;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Stack;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * JDBC工具类
 * ,本类采用的数据库连接池是c3p0。c3p0连接池的配置文件必须在src目录下,且名称必须为c3p0-config.xml,并且采用的是默认配置。
 *
 * @author Flying
 */
public class JDBCUtils {
    // 创建一个连接池
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    // 事务专用连接 , 本连接是线程安全的
    private static ThreadLocal<Connection> tl_conn = new ThreadLocal<Connection>();
    // 用于在事务中设置保存点,这是线程安全的
    private static ThreadLocal<Stack<Savepoint>> tl_sp = new ThreadLocal<Stack<Savepoint>>();

    /**
     * 获取数据库连接池对象,一般提供给第三方dbUtils使用
     *
     * @return 连接池对象
     */
    public static DataSource getDataSource() {
        return JDBCUtils.dataSource;
    }

    /**
     * 获取连接池里的一个数据库连接。若为有事务连接则直接返回事务连接,事务连接是线程安全的。
     *
     * @return 返回一个数据库连接, 失败返回null
     */
    public static Connection getConnection() {
        Connection connection = tl_conn.get();
        try {
            // 若tl.get()返回不是null说明当前线程有事务连接,直接返回事务连接
            if (connection != null) {
                return connection;
            }
            // 若为null则从连接池里返回一个连接
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    /**
     * 获取与数据库的连接,数据库配置文件需要在当前类目录(即源文件夹src目录下,或者类文件夹下,对于JavaProject项目是在bin目录下,
     * 对于webProject项目是在classes目录下)下,数据库配置文件名为JDBCInfo.properties
     *
     * @return connection 一个与数据库的连接对象
     */
    // public static Connection getConnection() {
    // Properties properties = null;
    // Connection connection = null;
    // try {
    // properties = new Properties();
    // properties.load(JDBCTools.class.getClassLoader()
    // .getResourceAsStream("JDBCInfo.properties"));
    // // 为兼容JDBC4.0以下的Jar包,需要先注册驱动
    // Class.forName(properties.getProperty("driver"));
    //
    // connection = DriverManager.getConnection(
    // properties.getProperty("url"),
    // properties.getProperty("user"),
    // properties.getProperty("password"));
    // } catch (IOException e) {
    // e.printStackTrace();
    // } catch (SQLException e) {
    // e.printStackTrace();
    // } catch (ClassNotFoundException e) {
    // e.printStackTrace();
    // }
    // return connection;
    // }

    /**
     * 开始一个事务,该事务连接是线程安全的。
     */
    public static void startTransaction() {
        Connection connection = tl_conn.get();
        if (connection != null) {
            throw new RuntimeException(
                    "You have started a Transaction and can not start transaction repeatedly for the same connection!");
        }

        try {
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);
            tl_conn.set(connection);
            tl_sp.set(new Stack<Savepoint>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用于在事务中设置一个保存点,属于线程安全的
     */
    public static void setSavePoint() {
        Connection connection = tl_conn.get();
        if (connection == null) {
            throw new RuntimeException("You do not start a Transaction so you can not set a savepoint!");
        }
        try {
            Stack<Savepoint> stack_sp = tl_sp.get();
            Savepoint sp = connection.setSavepoint();
            stack_sp.push(sp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交事务并关闭该事务,该事务连接是线程安全的。提交失败会回滚事务。
     */
    public static void commitTransaction() {
        Connection connection = tl_conn.get();
        if (connection == null) {
            throw new RuntimeException("You do not start a Transaction so you can not commit a transaction!");
        }
        try {
            connection.commit();
            connection.close();
            tl_conn.remove();
            tl_sp.remove();
        } catch (SQLException e) {
            JDBCUtils.rollbackTransaction();
            throw new RuntimeException(e);
        }
    }

    /**
     * 回滚事务并关闭该连接,该事务连接是线程安全的。
     */
    public static void rollbackTransaction() {
        Connection connection = tl_conn.get();
        if (connection == null) {
            throw new RuntimeException("You do not start a Transaction so you can not rollback a transaction!");
        }
        try {
            connection.rollback();
            connection.close();
            tl_conn.remove();
            tl_sp.remove();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将事务回滚到最近的一个保存点,若没有保存点则回滚到开始事务处
     */
    public static void rollbackTransactionToTheLatestSavepoint() {
        Connection connection = tl_conn.get();
        if (connection == null) {
            throw new RuntimeException("You do not start a Transaction so you can not rollback a transaction!");
        }
        try {
            Stack<Savepoint> stack_sp = tl_sp.get();
            if (stack_sp.empty()) {
                JDBCUtils.rollbackTransaction();
                return;
            }
            connection.rollback(stack_sp.pop());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭连接,若不是事务连接则直接关闭,若是事务连接则不执行任何操作,事务连接由提交事务方法关闭
     *
     * @param connection 一个连接
     */
    private static void release(Connection connection) {
        Connection con = tl_conn.get();
        try {
            // 若不是事务连接则直接关闭,若是事务连接不执行任何操作,事务连接由提交事务方法关闭
            if (con == null || con != connection) {
                connection.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭与数据库的连接资源,包括'ResultSet''Statement''Connection' 的实例对象所占用的资源,注意顺序不能颠倒
     *
     * @param result     结果集
     * @param statement  执行SQL语句的Statement对象
     * @param connection 连接数据库的连接对象
     */
    public static void release(ResultSet result, Statement statement, Connection connection) {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            JDBCUtils.release(connection);
        }
    }

    /**
     * 关闭与数据库的连接资源,包括'Statement''Connection' 的实例对象所占用的资源,注意顺序不能颠倒
     *
     * @param statement  执行SQL语句的Statement对象
     * @param connection 连接数据库的连接对象
     */
    public static void release(Statement statement, Connection connection) {

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            JDBCUtils.release(connection);
        }
    }

}


text:
using System;
using System.Net;

namespace SharpVectors.Net
{
    [Serializable]
    public sealed class DataWebRequest : WebRequest, IWebRequestCreate
	{
        private Uri requestUri;

		public static bool Register()
		{
            return WebRequest.RegisterPrefix("data", new DataWebRequest());
		}

		public new WebRequest Create(Uri uri)
		{
			return new DataWebRequest(uri);
		}

		//only for use from Register();
		private DataWebRequest()
		{
		}

		public DataWebRequest(Uri uri)
		{
			requestUri = uri;
		}

		public override Uri RequestUri
		{
			get
			{
				return requestUri;
			}
		}

		public override WebResponse GetResponse()
		{
			return new DataWebResponse(RequestUri);
		}
	}
}


text:
package org.jkiss.dbeaver.model.impl.data;

import org.jkiss.dbeaver.model.DBConstants;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.data.DBDContent;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;

/**
 * AbstractContent
 *
 * @author Serge Rider
 */
public abstract class AbstractContent implements DBDContent {

    protected final DBPDataSource dataSource;
    protected boolean modified = false;

    protected AbstractContent(DBPDataSource dataSource)
    {
        this.dataSource = dataSource;
    }

    public AbstractContent(AbstractContent copyFrom) {
        this.dataSource = copyFrom.dataSource;
        this.modified = copyFrom.modified;
    }

    @Override
    public DBPDataSource getDataSource() {
        return dataSource;
    }

    @Override
    public void resetContents()
    {
        // do nothing
    }

    @Override
    public String toString()
    {
        String displayString = getDisplayString(DBDDisplayFormat.UI);
        return displayString == null ? DBConstants.NULL_VALUE_LABEL : displayString;
    }

    @Override
    public boolean isModified() {
        return modified;
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="test"  parent="test2"/>
  <bean id="test2" parent="test3"/>
  <bean id="test3" parent="<error>unknown</error>"/>

  <bean name="aa, bb, cc" parent="<error>unknown</error>"/>
  <bean name="dd" parent="bb"/>

  <alias name="cc" alias="cc_2"/>
  <bean name="dd1" parent="cc_2"/>

  <bean id="parent" class="ParentBean"/>
  <bean id="child" parent="parent" class="ChildBean"/>
</beans>


text:
#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <linux/limits.h>
#include <signal.h>
#include "torrent.h"
#include "tracker.h"
#include "connections.h"
#include "uploadhash.h"
#include "client.h"

#define THREAD_MAX 4096

/* client_cmd sends a local command through the upload
   fifo to the upload daemon.
*/
static void client_cmd(int, char *, unsigned char *);

/* readchunk reads a size chunk of the file described by
   fd. It makes sure that all size bytes are read, as opposed
   to read, which does not make that gaurantee.
*/
static int readchunk(int fd, char *buffy, int size) {
    char *ptr = buffy;
    int n, total = 0, eof = 0;
    while(!eof && total < size) {
        n = read(fd, (void*)ptr, size-total);
        switch(n) {
        case -1:
            perror("read");
            exit(0);
        case 0:
            eof = 1;
            break;
        default:
            ptr += n;
            total += n;
            break;
        }
    }
    return total;
}

/* writechunk writes a size chunk of the file described at
   fd. It makes sure that all size bytes are written, as opposed
   to write, which does not make that gaurantee.
*/
static int writechunk(int fd, char *buffy, int size) {
    char *ptr = buffy;
    int n, total = 0, eof = 0;
    while(!eof && total < size) {
        n = write(fd, (void*)ptr, size-total);
        switch(n) {
        case -1:
            perror("write");
            exit(0);
        case 0:
            eof = 1;
            break;
        default:
            ptr += n;
            total += n;
            break;
        }
    }
    return total;
}

typedef struct thread_arg_send {
    int cfd;
    int read_pipefd;
    download_request rq;
} thread_arg_send;

void *send_chunk(void *arg) {
    thread_arg_send *targ = (thread_arg_send*)arg;
    int fd, total;
    char buffy[CHUNK_SIZE];
    char file[PATH_MAX];
    unsigned char hash[SHA1_SIZE];
    memcpy((void*)hash, (void*)targ->rq.hash, SHA1_SIZE);

    // send a request to the table manager to find the filename
    client_cmd(UPLOAD_CMD_FIND, NULL, hash);
    memset(file, 0, PATH_MAX);
    read(targ->read_pipefd, (void*)file, PATH_MAX);

    // open the file to read a chunk starting at chunk*CHUNK_SIZE
    fd = open(file, O_RDONLY);
    if (fd < 0) {
        perror("open");
        fprintf(stderr, "send_chunk: couldn't open %s\n", file);
        exit(0);
    }
    if (lseek(fd, CHUNK_SIZE*targ->rq.chunk, SEEK_SET) < 0) {
        perror("lseek");
        exit(0);
    }

    // now read it and send it to the client who requested it.
    total = readchunk(fd, buffy, CHUNK_SIZE);
    total = writechunk(targ->cfd, buffy, total);
    close(fd);
    close(targ->cfd);
    pthread_exit(NULL);
}

static int stop_serving = 0;

// a handler to intercept the SIGINT signal sent
// by upload_daemon to stop the upload_server.
void handler(int n) {
    stop_serving = 1;
}

void upload_server(int read_pipefd) {
    int sfd, cfd;
    sfd = server_listen(CLIENT_PORT);
    pthread_t threads[THREAD_MAX];
    thread_arg_send args[THREAD_MAX];
    int num_threads = 0;
    signal(SIGINT, handler);
    while (!stop_serving) {
        cfd = accept(sfd, NULL, NULL);
        args[num_threads].read_pipefd = read_pipefd;
        args[num_threads].cfd = cfd;
        // read the request from cfd into the thread argument
        read(cfd, (void*)&args[num_threads].rq, sizeof(args[num_threads].rq));
        // create a thread to send a chunk back to cfd
        pthread_create(&threads[num_threads], NULL, send_chunk, (void*)&args[num_threads]);
        num_threads++;
    }
    close(sfd);
    close(read_pipefd);
    upload_free_table();
}

void upload_daemon() {
    int pipefd[2];
    int pid;
    int stop;
    upload_local_request ur;
    char *filename;
    int sfd, cfd;
    sfd = server_listen(LOCAL_PORT);
    for (stop=0; !stop; ) {
        cfd = accept(sfd, NULL, NULL);
        if (cfd < 0) {
            perror("upload_daemon: accept");
            exit(0);
        }
        memset((void*)&ur, 0, sizeof(ur));
        read(cfd, (void*)&ur, sizeof(ur));
        switch(ur.cmd) {
        case UPLOAD_CMD_START:
            upload_init_table();
            // this pipe is used to send the results of upload_find_hash
            // to the server:
            pipe(pipefd);
            // fork the upload server here so we can kill it
            // when we receive the UPLOAD_CMD_STOP_ALL command.
            if ((pid = fork()) == 0) {
                close(pipefd[1]);
                upload_server(pipefd[0]);
                exit(0);
            }
            close(pipefd[0]);
            break;
        case UPLOAD_CMD_STOP_ALL:
            // kill the server.
            kill(pid, SIGINT);
            close(pipefd[1]);
            close(cfd);
            stop=1;
            break;
        case UPLOAD_CMD_UPLOAD:
            upload_add_hash(ur.name, ur.hash);
            break;
        case UPLOAD_CMD_DUMP:
            upload_dump_table();
            break;
        case UPLOAD_CMD_FIND:
            filename = upload_find_hash(ur.hash);
            // send the results to the upload server.
            write(pipefd[1], (void*)filename, PATH_MAX);
            break;
        default:
            break;
        }
        close(cfd);
    }
}

static void client_cmd(int cmd, char *fn, unsigned char *fh) {
    int fd;
    char me[HOST_MAX];
    upload_local_request ur;
    getmyaddr(me);
    fd = client_connect(me, LOCAL_PORT);
    if(fd < 0) {
        fprintf(stderr, "client_cmd: could not connect to %s\n", me);
        exit(0);
    }
    memset((void*)&ur, 0, sizeof(ur));
    ur.cmd = cmd;
    if (fn) {
        strcpy(ur.name, fn);
    }
    if (fh) {
        memcpy((void*)ur.hash, (void*)fh, SHA1_SIZE);
    }
    write(fd, (void*)&ur, sizeof(ur));
    close(fd);
}

void client_start() {
    char me[HOST_MAX];
    int cfd;
    getmyaddr(me);
    if((cfd = client_connect(me, LOCAL_PORT)) < 0) {
        if(fork() == 0) {
            upload_daemon();
            exit(0);
        }
        while((cfd = client_connect(me, LOCAL_PORT)) < 0) continue;
        close(cfd);
        client_cmd(UPLOAD_CMD_START, NULL, NULL);
    } else {
        close(cfd);
    }
}

void client_upload(char *fn, unsigned char *fh) {
    client_cmd(UPLOAD_CMD_UPLOAD, fn, fh);
}

void client_dump() {
    client_cmd(UPLOAD_CMD_DUMP, NULL, NULL);
}

void client_stop() {
    client_cmd(UPLOAD_CMD_STOP_ALL, NULL, NULL);
}

typedef struct thread_arg_receive {
    int fd;
    int chunk;
    int buffy_size;
    char buffy[CHUNK_SIZE];
} thread_arg_receive;

void *receive_chunk(void *arg) {
    thread_arg_receive *targ = (thread_arg_receive*)arg;
    int total = readchunk(targ->fd, targ->buffy, CHUNK_SIZE);
    targ->buffy_size = total;
    close(targ->fd);
    pthread_exit(NULL);
}

static int new_outfd(char *fn) {
    struct stat sbuf;
    char new[PATH_MAX];
    int i;
    strcpy(new, fn);
    for (i=1; stat(new, &sbuf) == 0; i++) {
        memset(new, 0, PATH_MAX);
        sprintf(new, "(%d)%s", i, fn);
    }
    return creat(new, 0666);
}

void client_download(torrent t) {
    download_request dr;
    int sfd = tracker_download(t.tracker, t.file_hash);
    pthread_t *threads;
    thread_arg_receive *args;
    int i, j, outfd, peeri, valid_peers, npeers;
    char **peers;
    if (read(sfd, (void*)&npeers, sizeof(npeers)) < 0) {
        perror("read");
        exit(0);
    }
    if (npeers == 0) {
        return;
    }
    peers = malloc(sizeof(*peers) * npeers);
    threads = malloc(sizeof(*threads) * t.num_chunks);
    args = malloc(sizeof(*args) * t.num_chunks);

    // read the peers from the tracker
    for (i=0;i<npeers;i++) {
        peers[i] = (char*) malloc(HOST_MAX+1);
        memset(peers[i], 0, HOST_MAX+1);
        read(sfd, (void*)peers[i], HOST_MAX);
    }

    outfd = new_outfd(t.friendly_name);
    if (outfd < 0) {
        perror("creat");
        exit(0);
    }

    // send a request for each chunk
    memcpy(dr.hash, t.file_hash, SHA1_SIZE);
    valid_peers = npeers;
    for (j=0; j<t.num_chunks; j+=npeers*CHUNKS_PER_PEER) {
        for (i=j; i<j+npeers*CHUNKS_PER_PEER && i<t.num_chunks; i++) {
            peeri = i%npeers;
            while (peers[peeri] == NULL) peeri = (peeri+1)%npeers;
            dr.chunk = i;
            args[i].chunk = i;
            args[i].fd = client_connect(peers[peeri], CLIENT_PORT);
            if (args[i].fd < 0) { // if we couldn't connect to the peer...
                fprintf(stderr, "client_download: could not connect to %s, removing it for the peer list\n", peers[peeri]);
                free(peers[peeri]);
                peers[peeri] = NULL;
                valid_peers--;
                if (valid_peers == 0) {
                    fprintf(stderr, "client_download: couldn't connect to any peers!\n");
                    exit(0);
                }
                // try getting the chunk from another peer
                i--;
                continue;
            }
            write(args[i].fd, (void*)&dr, sizeof(dr));
            pthread_create(&threads[i], NULL, receive_chunk, (void*)&args[i]);
        }
        for(i=j; i<j+npeers*CHUNKS_PER_PEER && i<t.num_chunks; i++) {
            pthread_join(threads[i], NULL);
            // TODO: verify the hash
            writechunk(outfd, args[i].buffy, args[i].buffy_size);
        }
    }
    close(outfd);
    close(sfd);
    for (i=0; i<npeers; i++) {
        free(peers[i]);
    }
    free(peers);
    free(threads);
    free(args);
}


text:
* Add a setting file. (Now `Toggle Comment` will use `// `)

## 0.3.0 - First Release
* Add CGINCLUDE to grammar

## 0.2.0 - First Release
* Add CG includes (.cginc files) to the list of supported file types.

## 0.1.0 - First Release
* Adds syntax highlighting to Unity 3D ShaderLab .shader files in Atom.


text:
<?php

use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;
use GW2Treasures\GW2Api\V2\Authentication\Exception\InvalidPermissionsException;
use Stubs\AuthenticatedEndpointStub;

class AuthenticatedEndpointTest extends TestCase {
    protected function getAuthenticatedEndpoint( $apiKey ) {
        return new AuthenticatedEndpointStub( $this->api(), $apiKey );
    }

    public function testBasic() {
        $this->mockResponse('[]');

        $endpoint = $this->getAuthenticatedEndpoint('test');

        $this->assertEndpointIsAuthenticated( $endpoint );

        $endpoint->test();

        $request = $this->getLastRequest();
        $this->assertTrue( $request->hasHeader('Authorization'),
            'AuthenticatedEndpoint sets Authorization header' );
        $header_values = $request->getHeader('Authorization');
        $this->assertEquals( 'Bearer test', array_shift($header_values),
            'AuthenticatedEndpoint sets correct Authorization header' );
    }

    /**
     * @expectedException \GW2Treasures\GW2Api\V2\Authentication\Exception\AuthenticationException
     * @expectedExceptionMessage invalid key
     */
    public function testInvalidKey() {
        $this->mockResponse( new Response(
            400, [ 'Content-Type' => 'application/json; charset=utf-8' ],
            Psr7\stream_for( '{"text":"invalid key"}' )
        ));

        $this->getAuthenticatedEndpoint('invalid')->test();
    }

    public function testInvalidPermissions() {
        $this->mockResponse( new Response(
            400, [ 'Content-Type' => 'application/json; charset=utf-8' ],
            Psr7\stream_for( '{"text":"requires scope characters"}' )
        ));

        try {
            $this->getAuthenticatedEndpoint('invalid')->test();
        } catch( InvalidPermissionsException $ex ) {
            $this->assertEquals( 'requires scope characters', $ex->getMessage(),
                'InvalidPermissionsException has correct error message.' );
            $this->assertEquals( 'characters', $ex->getMissingScope(),
                'InvalidPermissionsException has correct missing scope' );

            return;
        }

        $this->fail('Accessing IAuthenticatedEndpoint with an api_key that is missing scopes throws InvalidPermissionsException');
    }

    /**
     * @expectedException \GW2Treasures\GW2Api\Exception\ApiException
     * @expectedExceptionMessage unknown error
     */
    public function testUnknownError() {
        $this->mockResponse( new Response(
            400, [ 'Content-Type' => 'application/json; charset=utf-8' ],
            Psr7\stream_for( '{"text":"unknown error"}' )
        ));

        $this->getAuthenticatedEndpoint('invalid')->test();
    }
}


text:
@class VKUser;
@interface VKAudio : VKApiObject

@property (nonatomic, strong) NSNumber *id;
@property (nonatomic, strong) NSNumber *owner_id;
@property (nonatomic, strong) NSString *artist;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSNumber *duration;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSNumber *lyrics_id;
@property (nonatomic, strong) NSNumber *album_id;
@property (nonatomic, strong) NSNumber *genre_id;

@property (nonatomic, assign) BOOL fromCache;
@property (nonatomic, assign) BOOL ignoreCache;

@end

@interface VKAudios : VKApiObjectArray
@property (nonatomic, strong) VKUser * user;
@end


text:
class PolicyAssetSubtypeRule < ActiveRecord::Base

  # Include the numeric sanitizers mixin
  include TransamNumericSanitizers
  include FiscalYear

  #-----------------------------------------------------------------------------
  # Callbacks
  #-----------------------------------------------------------------------------
  after_initialize :set_defaults

  #-----------------------------------------------------------------------------
  # Associations
  #-----------------------------------------------------------------------------
  # Every policy rule belongs to a policy, and thus an organization
  belongs_to  :policy
  # Every one of these rules applies to an asset type
  belongs_to  :asset_subtype
  # Every one of these rules applies to an asset type
  belongs_to  :replace_asset_subtype, :class_name => 'AssetSubtype', :foreign_key => :replace_asset_subtype_id

  #-----------------------------------------------------------------------------
  # Validations
  #-----------------------------------------------------------------------------
  validates :policy,                  :presence => true
  validates :asset_subtype,           :presence => true

  validates :min_service_life_months,  :presence => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates :replacement_cost,         :presence => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates :cost_fy_year,             :presence => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates_inclusion_of :replace_with_new, :in => [true, false]
  validates_inclusion_of :replace_with_leased, :in => [true, false]
  validates :lease_length_months,       :allow_nil => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}

  validates :rehabilitation_service_month,     :presence => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates :rehabilitation_labor_cost,     :allow_nil => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates :rehabilitation_parts_cost,     :allow_nil => true,  :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}
  validates :extended_service_life_months, :numericality => {:only_integer => :true,   :greater_than_or_equal_to => 0}

  validates :min_used_purchase_service_life_months, :presence => true, :numericality => {:only_integer => :true, :greater_than_or_equal_to => 0}

  # Custom validator for checking values against parent policies
  validate :validate_min_allowable_policy_values

  #------------------------------------------------------------------------------
  # Scopes
  #------------------------------------------------------------------------------
  default_scope { order(:asset_subtype_id) }

  #-----------------------------------------------------------------------------
  # List of hash parameters allowed by the controller
  #-----------------------------------------------------------------------------
  FORM_PARAMS = [
    :id,
    :policy_id,
    :asset_subtype_id,
    :min_service_life_months,
    :replacement_cost,
    :cost_fy_year,
    :replace_with_new,
    :replace_with_leased,
    :replace_asset_subtype_id,
    :replacement_cost,
    :lease_length_months,

    :rehabilitation_service_month,
    :rehabilitation_labor_cost,
    :rehabilitation_parts_cost,
    :extended_service_life_months,

    :min_used_purchase_service_life_months
  ]

  #-----------------------------------------------------------------------------
  #
  # Class Methods
  #
  #-----------------------------------------------------------------------------
  def self.allowable_params
    FORM_PARAMS
  end

  #-----------------------------------------------------------------------------
  #
  # Instance Methods
  #
  #-----------------------------------------------------------------------------

  # Returns the total rehabilitation cost for the asset type
  def total_rehabilitation_cost
    rehabilitation_labor_cost.to_i + rehabilitation_parts_cost.to_i
  end

  def to_s
    "#{asset_subtype.asset_type}: #{asset_subtype}"
  end

  def name
    "Policy Rule #{asset_subtype}"
  end

  # Override setters to remove any extraneous formats from the number strings eg $, etc.
  def min_service_life_months=(num)
    self[:min_service_life_months] = sanitize_to_int(num)
  end
  def replacement_cost=(num)
    self[:replacement_cost] = sanitize_to_int(num)
  end
  def lease_length_months=(num)
    self[:lease_length_months] = sanitize_to_int(num)
  end
  def rehabilitation_service_month=(num)
    self[:rehabilitation_service_month] = sanitize_to_int(num)
  end
  def rehabilitation_labor_cost=(num)
    self[:rehabilitation_labor_cost] = sanitize_to_int(num)
  end
  def rehabilitation_parts_cost=(num)
    self[:rehabilitation_parts_cost] = sanitize_to_int(num)
  end
  def extended_service_life_months=(num)
    self[:extended_service_life_months] = sanitize_to_int(num)
  end
  def min_used_purchase_service_life_months=(num)
    self[:min_used_purchase_service_life_months] = sanitize_to_int(num)
  end

  #-----------------------------------------------------------------------------
  def minimum_value(attr, default = 0)
    # This method determines the minimum value allowed for an input for a particular attribute.
    # It allows us to set the appropriate minimum value for the inputs on the form.

    if policy.parent.present?
      parent_rule = policy.parent.policy_asset_subtype_rules.find_by(asset_subtype: self.asset_subtype)
      if parent_rule.present?
        parent_rule.send attr.to_s
      else
        default
      end
    else
      default
    end
  end

  def min_allowable_policy_values(subtype=nil)
    subtype = self.asset_subtype if subtype.nil?
    # This method gets the min values for child orgs that are not less than the value
    # set by the parent org
    results = Hash.new

    if policy.present? and policy.parent.present?
      attributes_to_compare = [
        :min_service_life_months,
        :extended_service_life_months,
        :min_used_purchase_service_life_months
      ]

      parent_rule = policy.parent.policy_asset_subtype_rules.find_by(asset_subtype: subtype)

      if parent_rule.present?
        attributes_to_compare.each do |attr|
          results[attr] = parent_rule.send(attr)
        end
      end
    end
    results
  end
  #-----------------------------------------------------------------------------
  # Protected Methods
  #-----------------------------------------------------------------------------
  protected

  # Set resonable defaults for a new policy
  def set_defaults
    self.min_service_life_months ||= 0
    self.replacement_cost ||= 0
    self.lease_length_months ||= 0
    self.rehabilitation_service_month ||= 0
    self.rehabilitation_labor_cost ||= 0
    self.rehabilitation_parts_cost ||= 0
    self.extended_service_life_months ||= 0
    self.min_used_purchase_service_life_months ||= 0
    self.cost_fy_year ||= current_planning_year_year
  end

  #-----------------------------------------------------------------------------
  private
  #-----------------------------------------------------------------------------

  def validate_min_allowable_policy_values
    # This method validates that values for child orgs are not less than the value
    # set by the parent org
    return_value = true

    min_allowable_policy_values.each do |attr, val|
      # Make sure we don't try to test nil values. Other validations should
      # take care of these
      if self.send(attr).blank?
        next
      end

      if self.send(attr) < val
        errors.add(attr, "cannot be less than #{val}, which is the minimum set by #{ policy.parent.organization.short_name}'s policy")
        return_value = false
      end
    end

    return_value
  end

end


text:
package com.gmail.htaihm.criminalintent;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

public abstract class SingleFragmentActivity extends AppCompatActivity {
    protected abstract Fragment createFragment();

    @LayoutRes
    protected int getLayoutResId() {
        return R.layout.activity_fragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);
        if (fragment == null) {
            fragment = createFragment();
            fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
        }
    }
}


text:
======
 HScD
======

*HScD* is a command line tool and library to access SoundCloud_.

Usage
=====

::

    hscd
      -t URL   --track=URL    Indicate the URL of the track to be downloaded.
      -o FILE  --output=FILE  Output File
      -i URL   --info=URL     Get info about the resource pointed by the URL
      -r URL   --resolve=URL  Resolve the SoundCloud's API URL for an arbitrary URL. Supports users, tracks, sets, groups and apps
      -h       --help         Show usage info

Installation
============

Clone the source code using hg or git and run cabal install from the main directory.

.. _SoundCloud: http://soundcloud.com/


text:
namespace Microsoft.Azure.Management.PostgreSQL.Models
{

    /// <summary>
    /// Defines values for MinimalTlsVersionEnum.
    /// </summary>
    public static class MinimalTlsVersionEnum
    {
        public const string TLS10 = "TLS1_0";
        public const string TLS11 = "TLS1_1";
        public const string TLS12 = "TLS1_2";
        public const string TLSEnforcementDisabled = "TLSEnforcementDisabled";
    }
}


text:
/**
 * Drop shadow w/ lifted corners
 *
 * @thanks Nicolas Gallagher @necolas
 * @link http://nicolasgallagher.com/css-drop-shadows-without-images/demo/
 */


text:
namespace web_modal {

// Tracks persistent state changes of the native WC-modal dialog manager.
class NativeManagerTracker {
 public:
  enum DialogState {
    UNKNOWN,
    NOT_SHOWN,
    SHOWN,
    HIDDEN,
    CLOSED
  };

  NativeManagerTracker() : state_(UNKNOWN), was_shown_(false) {}

  void SetState(DialogState state) {
    state_ = state;
    if (state_ == SHOWN)
      was_shown_ = true;
  }

  DialogState state_;
  bool was_shown_;
};

NativeManagerTracker unused_tracker;

class TestNativeWebContentsModalDialogManager
    : public SingleWebContentsDialogManager {
 public:
  TestNativeWebContentsModalDialogManager(
      NativeWebContentsModalDialog dialog,
      SingleWebContentsDialogManagerDelegate* delegate,
      NativeManagerTracker* tracker)
      : delegate_(delegate),
        dialog_(dialog),
        tracker_(tracker) {
    if (tracker_)
      tracker_->SetState(NativeManagerTracker::NOT_SHOWN);
  }

  virtual void Show() OVERRIDE {
    if (tracker_)
      tracker_->SetState(NativeManagerTracker::SHOWN);
  }
  virtual void Hide() OVERRIDE {
    if (tracker_)
      tracker_->SetState(NativeManagerTracker::HIDDEN);
  }
  virtual void Close() OVERRIDE {
    if (tracker_)
      tracker_->SetState(NativeManagerTracker::CLOSED);
    delegate_->WillClose(dialog_);
  }
  virtual void Focus() OVERRIDE {
  }
  virtual void Pulse() OVERRIDE {
  }
  virtual void HostChanged(WebContentsModalDialogHost* new_host) OVERRIDE {
  }
  virtual NativeWebContentsModalDialog dialog() OVERRIDE {
      return dialog_;
  }

  void StopTracking() {
    tracker_ = NULL;
  }

 private:
  SingleWebContentsDialogManagerDelegate* delegate_;
  NativeWebContentsModalDialog dialog_;
  NativeManagerTracker* tracker_;

  DISALLOW_COPY_AND_ASSIGN(TestNativeWebContentsModalDialogManager);
};

class WebContentsModalDialogManagerTest
    : public content::RenderViewHostTestHarness {
 public:
  WebContentsModalDialogManagerTest()
      : next_dialog_id(1),
        manager(NULL) {
  }

  virtual void SetUp() {
    content::RenderViewHostTestHarness::SetUp();

    delegate.reset(new TestWebContentsModalDialogManagerDelegate);
    WebContentsModalDialogManager::CreateForWebContents(web_contents());
    manager = WebContentsModalDialogManager::FromWebContents(web_contents());
    manager->SetDelegate(delegate.get());
    test_api.reset(new WebContentsModalDialogManager::TestApi(manager));
  }

  virtual void TearDown() {
    test_api.reset();
    content::RenderViewHostTestHarness::TearDown();
  }

 protected:
  NativeWebContentsModalDialog MakeFakeDialog() {
    // WebContentsModalDialogManager treats the NativeWebContentsModalDialog as
    // an opaque type, so creating fake NativeWebContentsModalDialogs using
    // reinterpret_cast is valid.
    return reinterpret_cast<NativeWebContentsModalDialog>(next_dialog_id++);
  }

  int next_dialog_id;
  scoped_ptr<TestWebContentsModalDialogManagerDelegate> delegate;
  WebContentsModalDialogManager* manager;
  scoped_ptr<WebContentsModalDialogManager::TestApi> test_api;

  DISALLOW_COPY_AND_ASSIGN(WebContentsModalDialogManagerTest);
};

SingleWebContentsDialogManager*
WebContentsModalDialogManager::CreateNativeWebModalManager(
    NativeWebContentsModalDialog dialog,
    SingleWebContentsDialogManagerDelegate* native_delegate) {
  NOTREACHED();
  return new TestNativeWebContentsModalDialogManager(
      dialog,
      native_delegate,
      &unused_tracker);
}

// Test that the dialog is shown immediately when the delegate indicates the web
// contents is visible.
TEST_F(WebContentsModalDialogManagerTest, WebContentsVisible) {
  // Dialog should be shown while WebContents is visible.
  const NativeWebContentsModalDialog dialog = MakeFakeDialog();

  NativeManagerTracker tracker;
  TestNativeWebContentsModalDialogManager* native_manager =
      new TestNativeWebContentsModalDialogManager(dialog, manager, &tracker);
  manager->ShowDialogWithManager(dialog,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager).Pass());

  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker.state_);
  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_TRUE(tracker.was_shown_);

  native_manager->StopTracking();
}

// Test that the dialog is not shown immediately when the delegate indicates the
// web contents is not visible.
TEST_F(WebContentsModalDialogManagerTest, WebContentsNotVisible) {
  // Dialog should not be shown while WebContents is not visible.
  delegate->set_web_contents_visible(false);

  const NativeWebContentsModalDialog dialog = MakeFakeDialog();

  NativeManagerTracker tracker;
  TestNativeWebContentsModalDialogManager* native_manager =
      new TestNativeWebContentsModalDialogManager(dialog, manager, &tracker);
  manager->ShowDialogWithManager(dialog,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager).Pass());

  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker.state_);
  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_FALSE(tracker.was_shown_);

  native_manager->StopTracking();
}

// Test that only the first of multiple dialogs is shown.
TEST_F(WebContentsModalDialogManagerTest, ShowDialogs) {
  const NativeWebContentsModalDialog dialog1 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog2 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog3 = MakeFakeDialog();

  NativeManagerTracker tracker1;
  NativeManagerTracker tracker2;
  NativeManagerTracker tracker3;
  TestNativeWebContentsModalDialogManager* native_manager1 =
      new TestNativeWebContentsModalDialogManager(dialog1, manager, &tracker1);
  TestNativeWebContentsModalDialogManager* native_manager2 =
      new TestNativeWebContentsModalDialogManager(dialog2, manager, &tracker2);
  TestNativeWebContentsModalDialogManager* native_manager3 =
      new TestNativeWebContentsModalDialogManager(dialog3, manager, &tracker3);
  manager->ShowDialogWithManager(dialog1,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager1).Pass());
  manager->ShowDialogWithManager(dialog2,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager2).Pass());
  manager->ShowDialogWithManager(dialog3,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager3).Pass());

  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker2.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker3.state_);

  native_manager1->StopTracking();
  native_manager2->StopTracking();
  native_manager3->StopTracking();
}

// Test that the dialog is shown/hidden when the WebContents is shown/hidden.
TEST_F(WebContentsModalDialogManagerTest, VisibilityObservation) {
  const NativeWebContentsModalDialog dialog = MakeFakeDialog();

  NativeManagerTracker tracker;
  TestNativeWebContentsModalDialogManager* native_manager =
      new TestNativeWebContentsModalDialogManager(dialog, manager, &tracker);
  manager->ShowDialogWithManager(dialog,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager).Pass());

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker.state_);

  test_api->WebContentsWasHidden();

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::HIDDEN, tracker.state_);

  test_api->WebContentsWasShown();

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker.state_);

  native_manager->StopTracking();
}

// Test that attaching an interstitial page closes all dialogs.
TEST_F(WebContentsModalDialogManagerTest, InterstitialPage) {
  const NativeWebContentsModalDialog dialog1 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog2 = MakeFakeDialog();

  NativeManagerTracker tracker1;
  NativeManagerTracker tracker2;
  TestNativeWebContentsModalDialogManager* native_manager1 =
      new TestNativeWebContentsModalDialogManager(dialog1, manager, &tracker1);
  TestNativeWebContentsModalDialogManager* native_manager2 =
      new TestNativeWebContentsModalDialogManager(dialog2, manager, &tracker2);
  manager->ShowDialogWithManager(dialog1,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager1).Pass());
  manager->ShowDialogWithManager(dialog2,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager2).Pass());

  test_api->DidAttachInterstitialPage();

#if defined(USE_AURA)
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker2.state_);
#else
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker2.state_);
#endif

  EXPECT_TRUE(tracker1.was_shown_);
  EXPECT_FALSE(tracker2.was_shown_);

#if !defined(USE_AURA)
  native_manager1->StopTracking();
  native_manager2->StopTracking();
#endif
}

// Test that the first dialog is always shown, regardless of the order in which
// dialogs are closed.
TEST_F(WebContentsModalDialogManagerTest, CloseDialogs) {
  // The front dialog is always shown regardless of dialog close order.
  const NativeWebContentsModalDialog dialog1 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog2 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog3 = MakeFakeDialog();
  const NativeWebContentsModalDialog dialog4 = MakeFakeDialog();

  NativeManagerTracker tracker1;
  NativeManagerTracker tracker2;
  NativeManagerTracker tracker3;
  NativeManagerTracker tracker4;
  TestNativeWebContentsModalDialogManager* native_manager1 =
      new TestNativeWebContentsModalDialogManager(dialog1, manager, &tracker1);
  TestNativeWebContentsModalDialogManager* native_manager2 =
      new TestNativeWebContentsModalDialogManager(dialog2, manager, &tracker2);
  TestNativeWebContentsModalDialogManager* native_manager3 =
      new TestNativeWebContentsModalDialogManager(dialog3, manager, &tracker3);
  TestNativeWebContentsModalDialogManager* native_manager4 =
      new TestNativeWebContentsModalDialogManager(dialog4, manager, &tracker4);
  manager->ShowDialogWithManager(dialog1,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager1).Pass());
  manager->ShowDialogWithManager(dialog2,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager2).Pass());
  manager->ShowDialogWithManager(dialog3,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager3).Pass());
  manager->ShowDialogWithManager(dialog4,
      scoped_ptr<SingleWebContentsDialogManager>(native_manager4).Pass());

  native_manager1->Close();

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker2.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker3.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker4.state_);

  native_manager3->Close();

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker2.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker3.state_);
  EXPECT_EQ(NativeManagerTracker::NOT_SHOWN, tracker4.state_);
  EXPECT_FALSE(tracker3.was_shown_);

  native_manager2->Close();

  EXPECT_TRUE(manager->IsDialogActive());
  EXPECT_TRUE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker2.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker3.state_);
  EXPECT_EQ(NativeManagerTracker::SHOWN, tracker4.state_);
  EXPECT_FALSE(tracker3.was_shown_);

  native_manager4->Close();

  EXPECT_FALSE(manager->IsDialogActive());
  EXPECT_FALSE(delegate->web_contents_blocked());
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker1.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker2.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker3.state_);
  EXPECT_EQ(NativeManagerTracker::CLOSED, tracker4.state_);
  EXPECT_TRUE(tracker1.was_shown_);
  EXPECT_TRUE(tracker2.was_shown_);
  EXPECT_FALSE(tracker3.was_shown_);
  EXPECT_TRUE(tracker4.was_shown_);
}

// Test that CloseAllDialogs does what it says.
TEST_F(WebContentsModalDialogManagerTest, CloseAllDialogs) {
  const int kWindowCount = 4;
  NativeManagerTracker trackers[kWindowCount];
  TestNativeWebContentsModalDialogManager* native_managers[kWindowCount];
  for (int i = 0; i < kWindowCount; i++) {
    const NativeWebContentsModalDialog dialog = MakeFakeDialog();
    native_managers[i] =
        new TestNativeWebContentsModalDialogManager(
            dialog, manager, &(trackers[i]));
    manager->ShowDialogWithManager(dialog,
    scoped_ptr<SingleWebContentsDialogManager>(
        native_managers[i]).Pass());
  }

  for (int i = 0; i < kWindowCount; i++)
    EXPECT_NE(NativeManagerTracker::CLOSED, trackers[i].state_);

  test_api->CloseAllDialogs();

  EXPECT_FALSE(delegate->web_contents_blocked());
  EXPECT_FALSE(manager->IsDialogActive());
  for (int i = 0; i < kWindowCount; i++)
    EXPECT_EQ(NativeManagerTracker::CLOSED, trackers[i].state_);
}

}  // namespace web_modal


text:
package net.imglib2.ops.operation.complex.unary;

import net.imglib2.type.numeric.ComplexType;
import net.imglib2.type.numeric.complex.ComplexDoubleType;

//Formula taken from MATLAB documentation

/**
 * Sets an output complex number to the hyperbolic cosecant of an input
 * complex number.
 *
 * @author Barry DeZonia
 * @deprecated Use net.imagej.ops instead.
 */
@Deprecated
public final class ComplexCsch<I extends ComplexType<I>, O extends ComplexType<O>>
	implements ComplexUnaryOperation<I,O>
{
	private final ComplexSinh<I,ComplexDoubleType>
		sinhFunc = new ComplexSinh<I,ComplexDoubleType>();
	private final ComplexReciprocal<ComplexDoubleType,O>
		recipFunc = new ComplexReciprocal<ComplexDoubleType,O>();

	private final ComplexDoubleType sinh = new ComplexDoubleType();

	@Override
	public O compute(I z, O output) {
		sinhFunc.compute(z, sinh);
		recipFunc.compute(sinh, output);
		return output;
	}

	@Override
	public ComplexCsch<I,O> copy() {
		return new ComplexCsch<I,O>();
	}

}


text:
package org.apache.hadoop.yarn.server.federation.store.records.impl.pb;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.thirdparty.protobuf.TextFormat;
import org.apache.hadoop.yarn.federation.proto.YarnServerFederationProtos.RouterRMTokenResponseProto;
import org.apache.hadoop.yarn.federation.proto.YarnServerFederationProtos.RouterRMTokenResponseProtoOrBuilder;
import org.apache.hadoop.yarn.federation.proto.YarnServerFederationProtos.RouterStoreTokenProto;
import org.apache.hadoop.yarn.server.federation.store.records.RouterRMTokenResponse;
import org.apache.hadoop.yarn.server.federation.store.records.RouterStoreToken;

@Private
@Unstable
public class RouterRMTokenResponsePBImpl extends RouterRMTokenResponse {

  private RouterRMTokenResponseProto proto = RouterRMTokenResponseProto.getDefaultInstance();
  private RouterRMTokenResponseProto.Builder builder = null;
  private boolean viaProto = false;
  private RouterStoreToken routerStoreToken = null;

  public RouterRMTokenResponsePBImpl() {
    builder = RouterRMTokenResponseProto.newBuilder();
  }

  public RouterRMTokenResponsePBImpl(RouterRMTokenResponseProto requestProto) {
    this.proto = requestProto;
    viaProto = true;
  }

  public RouterRMTokenResponseProto getProto() {
    mergeLocalToProto();
    proto = viaProto ? proto : builder.build();
    viaProto = true;
    return proto;
  }

  private void mergeLocalToProto() {
    if (viaProto) {
      maybeInitBuilder();
    }
    mergeLocalToBuilder();
    proto = builder.build();
    viaProto = true;
  }

  private void maybeInitBuilder() {
    if (viaProto || builder == null) {
      builder = RouterRMTokenResponseProto.newBuilder(proto);
    }
    viaProto = false;
  }

  private void mergeLocalToBuilder() {
    if (this.routerStoreToken != null) {
      RouterStoreTokenPBImpl routerStoreTokenPBImpl =
          (RouterStoreTokenPBImpl) this.routerStoreToken;
      RouterStoreTokenProto storeTokenProto = routerStoreTokenPBImpl.getProto();
      if (!storeTokenProto.equals(builder.getRouterStoreToken())) {
        builder.setRouterStoreToken(convertToProtoFormat(this.routerStoreToken));
      }
    }
  }

  @Override
  public RouterStoreToken getRouterStoreToken() {
    RouterRMTokenResponseProtoOrBuilder p = viaProto ? proto : builder;
    if (this.routerStoreToken != null) {
      return this.routerStoreToken;
    }
    if (!p.hasRouterStoreToken()) {
      return null;
    }
    this.routerStoreToken = convertFromProtoFormat(p.getRouterStoreToken());
    return this.routerStoreToken;
  }

  @Override
  public void setRouterStoreToken(RouterStoreToken storeToken) {
    maybeInitBuilder();
    if (storeToken == null) {
      builder.clearRouterStoreToken();
    }
    this.routerStoreToken = storeToken;
  }

  private RouterStoreTokenProto convertToProtoFormat(RouterStoreToken storeToken) {
    return ((RouterStoreTokenPBImpl) storeToken).getProto();
  }

  private RouterStoreToken convertFromProtoFormat(RouterStoreTokenProto storeTokenProto) {
    return new RouterStoreTokenPBImpl(storeTokenProto);
  }

  @Override
  public int hashCode() {
    return getProto().hashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other == null) {
      return false;
    }
    if (other.getClass().isAssignableFrom(this.getClass())) {
      return this.getProto().equals(this.getClass().cast(other).getProto());
    }
    return false;
  }

  @Override
  public String toString() {
    return TextFormat.shortDebugString(getProto());
  }
}


text:
title: ibis Auckland Ellerslie

listing-type: accommodation
island: north
region: auckland
destination: Auckland

order: c
image-path: ibis-auckland-ellerslie.jpg
image-alt: ibis Auckland Ellerslie
refer-url: http://www.accorhotels.com/gb/hotel-3059-ibis-auckland-ellerslie/index.shtml
---
Located just off the Greenlane highway interchange, offering modern, comfortable rooms with king size beds, air conditioning, Sky TV and broadband internet.


text:
@interface GKToutiaoVideoViewController ()

@end

@implementation GKToutiaoVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.gk_navBackgroundImage = [UIImage imageNamed:@"video_nav"];
    self.gk_navRightBarButtonItem = [UIBarButtonItem itemWithTitle:@"关闭" target:self action:@selector(closeAction)];

    UIImageView *pageImage = [UIImageView new];
    pageImage.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - GK_TABBAR_HEIGHT);
    pageImage.image = [UIImage imageNamed:@"video_page"];
    [self.view addSubview:pageImage];

    pageImage.userInteractionEnabled = YES;
    [pageImage addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageAction)]];
}

- (void)pageAction {
    GKToutiaoDetailViewController *detailVC = [GKToutiaoDetailViewController new];

    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)closeAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
<?php
/**
 * 模板库要自动创建的频道的数据处理类
 * @category iCMS
 * @package iCMS_FrameWork1_RuleClass_DataProvider_Template
 * @author 525
 */
class TemplateLibraryChannelManageData extends BaseManageData {

    /**
     * 新增频道
     * @param array $httpPostData $_post数组
     * @return int 新增id
     */
    public function Create($httpPostData) {
        $result=-1;
        $dataProperty = new DataProperty();
        $addFieldName = "";
        $addFieldValue = "";
        $preNumber = "";
        $addFieldNames = array();
        $addFieldValues = array();
        if(!empty($httpPostData)){
            $sql=parent::GetInsertSql($httpPostData, self::TableName_TemplateLibraryChannel, $dataProperty, $addFieldName, $addFieldValue, $preNumber, $addFieldNames, $addFieldValues);
            $result=$this->dbOperator->LastInsertId($sql,$dataProperty);
        }
        return $result;

    }

    /**
     * 修改
     * @param array $httpPostData $_post数组
     * @param int $templateLibraryChannelId
     * @return int 执行结果
     */
    public function Modify($httpPostData,$templateLibraryChannelId) {
        $dataProperty = new DataProperty();
        $sql = parent::GetUpdateSql($httpPostData, self::TableName_TemplateLibraryChannel, self::TableId_TemplateLibraryChannel, $templateLibraryChannelId, $dataProperty);
        $result = $this->dbOperator->Execute($sql, $dataProperty);
        return $result;
    }

    /**
     * 取得管理列表
     * @param int $templateLibraryId
     * @return array 数据集
     */
    public function GetChannelList($templateLibraryId){
        $result=null;
        if($templateLibraryId>0){
            $sql="SELECT channel.*,
            (SELECT count(*) FROM ".self::TableName_TemplateLibraryContent." content WHERE content.TemplateLibraryChannelId=channel.TemplateLibraryChannelId ) AS TemplateCount
            FROM ".self::TableName_TemplateLibraryChannel." channel
            WHERE channel.TemplateLibraryId = :TemplateLibraryId AND channel.State!=100 ;";
            $dataProperty = new DataProperty();
            $dataProperty->AddField("TemplateLibraryId", $templateLibraryId);
            $result = $this->dbOperator->GetArrayList($sql,$dataProperty);
        }
        return $result;
    }

    /**
     * 取得列表用来导入
     * @param int $templateLibraryId
     * @param int $rank
     * @return array 数据集
     */
    public function GetChannelListOfRank($templateLibraryId,$rank=0){
        $result=null;
        if($templateLibraryId>0){
            $sql = "SELECT * FROM ".self::TableName_TemplateLibraryChannel." WHERE TemplateLibraryId = :TemplateLibraryId AND Rank=:Rank AND State!=100";
            $dataProperty = new DataProperty();
            $dataProperty->AddField("TemplateLibraryId", $templateLibraryId);
            $dataProperty->AddField("Rank", $rank);
            $result = $this->dbOperator->GetArrayList($sql,$dataProperty);
        }
        return $result;
    }

    /**
     * 取得列表 父频道id
     * @param int $templateLibraryId
     * @return array 数据集
     */
    public function GetParentTemplateLibraryChannelId($templateLibraryId){
        $result=-1;
        if($templateLibraryId>0){
            $sql = "SELECT ParentId FROM ".self::TableName_TemplateLibraryChannel." WHERE TemplateLibraryId = :TemplateLibraryId";
            $dataProperty = new DataProperty();
            $dataProperty->AddField("TemplateLibraryId", $templateLibraryId);
            $result = $this->dbOperator->GetInt($sql,$dataProperty);
        }
        return $result;
    }

    /**
     * 添加节点
     * @param int $templateLibraryChannelId
     * @param int $siteId
     * @param int $documentChannelId
     * @param int $rank
     * @param string $createDate
     * @return int
     */

    public function InsertChannel($templateLibraryChannelId,$siteId,$documentChannelId,$rank,$createDate){
        $sql = "INSERT INTO ".self::TableName_Channel."
        (
            ChannelName,
            Icon,
            Sort,
            ChannelType,
            PublishType,
            PublishPath,
            ManageUserId,
            State,
            HasFTP,
            ShowChildList,
            OpenComment,
            ChannelBrowserTitle,
            ChannelBrowserKeywords,
            ChannelBrowserDescription,
            TitlePic1UploadFileId,
            TitlePic2UploadFileId,
            TitlePic3UploadFileId,
            IsCircle,
            IsShowIndex,
            SiteId,
            ParentId,
            Rank,
            CreateDate
        ) SELECT
            ChannelName,
            Icon,
            Sort,
            ChannelType,
            PublishType,
            PublishPath,
            ManageUserId,
            State,
            HasFTP,
            ShowChildList,
            OpenComment,
            ChannelBrowserTitle,
            ChannelBrowserKeywords,
            ChannelBrowserDescription,
            TitlePic1UploadFileId,
            TitlePic2UploadFileId,
            TitlePic3UploadFileId,
            IsCircle,
            IsShowIndex,
            :SiteId,
            :ParentId,
            :Rank,
            '$createDate'
        FROM ".self::TableName_TemplateLibraryChannel." WHERE TemplateLibraryChannelId = :TemplateLibraryChannelId";
        $dataProperty = new DataProperty();
        $dataProperty->AddField("TemplateLibraryChannelId", $templateLibraryChannelId);
        $dataProperty->AddField("SiteId", $siteId);
        $dataProperty->AddField("ParentId", $documentChannelId);
        $dataProperty->AddField("Rank", $rank);
        $result = $this->dbOperator->LastInsertId($sql,$dataProperty);
        return $result;
    }

    /**
     * 获取模板库中的一个频道信息
     * @param int $templateLibraryChannelId 模板库的频道ID
     * @return Array 频道信息
     */
    public function GetOne($templateLibraryChannelId){
        $sql = "SELECT * FROM ".self::TableName_TemplateLibraryChannel." WHERE TemplateLibraryChannelId = :TemplateLibraryChannelId";
        $dataProperty = new DataProperty();
        $dataProperty->AddField("TemplateLibraryChannelId", $templateLibraryChannelId);
        $result = $this->dbOperator->GetArray($sql,$dataProperty);
        return $result;
    }

    /**
     * 删除模板库的一个频道
     * @param int $templateLibraryChannelId
     * @return int 影响行数
     */
    public function Delete($templateLibraryChannelId){
        $sql = "UPDATE ".self::TableName_TemplateLibraryChannel." SET State=100 WHERE TemplateLibraryChannelId = :TemplateLibraryChannelId";
        $dataProperty = new DataProperty();
        $dataProperty->AddField("TemplateLibraryChannelId", $templateLibraryChannelId);
        $result = $this->dbOperator->Execute($sql,$dataProperty);
        return $result;
    }

    /**
     * 取得模板库id
     * @param int $templateLibraryChannelId
     * @return int id
     */
    public function GetTemplateLibraryId($templateLibraryChannelId){
        $sql = "SELECT TemplateLibraryId FROM ".self::TableName_TemplateLibraryChannel." where TemplateLibraryChannelId = :TemplateLibraryChannelId";
        $dataProperty = new DataProperty();
        $dataProperty->AddField("TemplateLibraryChannelId", $templateLibraryChannelId);
        $result = $this->dbOperator->GetInt($sql,$dataProperty);
        return $result;
    }

    /**
     * 获取模板库中的一个频道rank
     * @param int $templateLibraryChannelId 模板库的频道ID
     * @return int rank
     */
    public function GetRank($templateLibraryChannelId){
        $result=-1;
        if($templateLibraryChannelId>0){
            $sql = "SELECT Rank FROM ".self::TableName_TemplateLibraryChannel." WHERE TemplateLibraryChannelId = :TemplateLibraryChannelId";
            $dataProperty = new DataProperty();
            $dataProperty->AddField("TemplateLibraryChannelId", $templateLibraryChannelId);
            $result = $this->dbOperator->GetInt($sql,$dataProperty);
        }
        return $result;
    }

    /**
     * 获取子节点id
     * @param $templateLibraryChannelId
     * @return array
     */
    public function GetChildrenId($templateLibraryChannelId){
        $result=null;
        if($templateLibraryChannelId>0){
            $sql = "SELECT TemplateLibraryChannelId FROM ".self::TableName_TemplateLibraryChannel." WHERE ParentId = :ParentId";
            $dataProperty = new DataProperty();
            $dataProperty->AddField("ParentId", $templateLibraryChannelId);
            $result = $this->dbOperator->GetArray($sql,$dataProperty);
        }
        return $result;
    }

    /**
     * 取得字段数据集
     * @param string $tableName 表名
     * @return array 字段数据集
     */
    public function GetFields($tableName = self::TableName_TemplateLibraryChannel){
        return parent::GetFields(self::TableName_TemplateLibraryChannel);
    }

}

?>


text:
package com.apexmob.skink;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class DefaultNodeManagerTest extends ParsingTest {

	private DefaultNodeManager mgr = null;
	private MockNodeListener mock1 = null;
	private MockNodeListener mock2 = null;

	private StartElement start = null;
	private EndElement end = null;
	private Text text = null;

	@Rule
	public ExpectedException thrown= ExpectedException.none();

	@Before
	public void setUp() {
		mgr = new DefaultNodeManager();

		mock1 = new MockNodeListener();
		mock2 = new MockNodeListener();

		start = buildStartElement("<div>");
		end = buildEndElement("</div>");
		text = buildText("text");
	}

	@After
	public void tearDown() {
		mgr = null;

		mock1 = null;
		mock2 = null;

		start = null;
		end = null;
		text = null;
	}

	@Test
	public void throwsIllegalArgumentExceptionRegisterListenerIsNull() {
		thrown.expect(IllegalArgumentException.class);

		mgr.registerListener(null);
	}

	@Test
	public void throwsIllegalArgumentExceptionDeregisterListenerIsNull() {
		thrown.expect(IllegalArgumentException.class);

		mgr.deregisterListener(null);
	}

	@Test
	public void throwsIllegalArgumentExceptionWhenStartElementIsNull() {
		thrown.expect(IllegalArgumentException.class);

		mgr.startElement(null);
	}

	@Test
	public void throwsIllegalArgumentExceptionWhenEndElementIsNull() {
		thrown.expect(IllegalArgumentException.class);

		mgr.endElement(null);
	}

	@Test
	public void throwsIllegalArgumentExceptionWhenTextIsNull() {
		thrown.expect(IllegalArgumentException.class);

		mgr.text(null);
	}

	@Test
	public void managerWorksWithNoListeners() {
		mgr.startElement(start);
		mgr.endElement(end);
		mgr.text(text);
	}

	@Test
	public void managerWorksWithOneListener() {
		mgr.registerListener(mock1);

		mgr.startElement(start);
		mgr.text(text);
		mgr.endElement(end);

		assertEquals(3, mock1.getNodeStack().size());
		assertStartElement(mock1, 0, "div");
		assertText(mock1, 1, "text");
		assertEndElement(mock1, 2, "div");
	}

	@Test
	public void managerWorksWithTwoListeners() {
		mgr.registerListener(mock1);
		mgr.registerListener(mock2);

		mgr.startElement(start);
		mgr.text(text);
		mgr.endElement(end);

		assertEquals(3, mock1.getNodeStack().size());
		assertStartElement(mock1, 0, "div");
		assertText(mock1, 1, "text");
		assertEndElement(mock1, 2, "div");

		assertEquals(3, mock2.getNodeStack().size());
		assertStartElement(mock2, 0, "div");
		assertText(mock2, 1, "text");
		assertEndElement(mock2, 2, "div");
	}

	@Test
	public void deregisterListenerRemovesListener() {
		mgr.registerListener(mock1);
		mgr.registerListener(mock2);
		mgr.deregisterListener(mock1);

		mgr.startElement(start);
		mgr.text(text);
		mgr.endElement(end);

		assertEquals(0, mock1.getNodeStack().size());

		assertEquals(3, mock2.getNodeStack().size());
		assertStartElement(mock2, 0, "div");
		assertText(mock2, 1, "text");
		assertEndElement(mock2, 2, "div");
	}

	@Test
	public void throwsIllegalArgumentExceptionWhenDeregisteringAnUnregisteredListener() {
		thrown.expect(IllegalArgumentException.class);

		mgr.deregisterListener(mock1);
	}

	@Test
	public void listenerThrowingExceptionDoesNotStopStartElementListeners() {
		mgr.registerListener(new ExceptionThrowingListener());
		mgr.registerListener(mock1);

		mgr.startElement(start);

		assertEquals(1, mock1.getNodeStack().size());
		assertStartElement(mock1, 0, "div");
	}

	@Test
	public void listenerThrowingExceptionDoesNotStopEndElementListeners() {
		mgr.registerListener(new ExceptionThrowingListener());
		mgr.registerListener(mock1);

		mgr.endElement(end);

		assertEquals(1, mock1.getNodeStack().size());
		assertEndElement(mock1, 0, "div");
	}

	@Test
	public void listenerThrowingExceptionDoesNotStopTextListeners() {
		mgr.registerListener(new ExceptionThrowingListener());
		mgr.registerListener(mock1);

		mgr.text(text);

		assertEquals(1, mock1.getNodeStack().size());
		assertText(mock1, 0, "text");
	}

	private static class ExceptionThrowingListener implements NodeListener {

		public void onStartElement(StartElement start) {
			throw new RuntimeException();
		}

		public void onText(Text text) {
			throw new RuntimeException();
		}

		public void onEndElement(EndElement end) {
			throw new RuntimeException();
		}

	}

}


text:
package org.apache.wicket.examples.library;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.util.io.IClusterable;

/**
 * Trivial user model for example application
 *
 * @author Jonathan Locke
 */
public final class User implements IClusterable
{
	// The user's name
	private String name;

	// The user's personal book list
	private List<Book> books = new ArrayList<>();

	/**
	 * @return User name
	 */
	public final String getName()
	{
		return name;
	}

	/**
	 * @param string
	 *            User name
	 */
	public final void setName(final String string)
	{
		name = string;
	}

	/**
	 * @return User's book list
	 */
	public final List<Book> getBooks()
	{
		return books;
	}

	/**
	 * @param books
	 *            New book list
	 */
	public void setBooks(final List<Book> books)
	{
		this.books = books;
	}
}


text:
require 'psych'
require 'set'

module Overcover

  class RspecCollector

    class << self

      def paths
        @paths ||= []
      end

      def should_analyse?(path)
        paths.empty? || paths.any? {|p| path.start_with?(p) }
      end

      def add_filter(filter)
        paths << filter
      end

      def reset
        puts "[overcover] deleting log files in #{dir}"
        log_files.each do |f|
          File.delete(f)
        end
      end

      def record(result)
        open(@log_file, 'a') do |f|
          f.puts Psych.dump(result)
        end
      end

      def dir
        ENV["OVERCOVER_DIR"] || "."
      end

      def log_files
        files = Dir.glob(File.join(dir, "overcover.*.tmp"))
        if block_given?
          files.each do |f|
            yield f
          end
        end
        files
      end

      def log_file
        @log_file
      end

      def start

        @log_file = File.join(dir ,"overcover.#{Time.now.utc.strftime("%Y%m%d%H%M%S%N")}.tmp")

        yield self if block_given?

        puts "[overcover] writing to log file #{@log_file}"

        if CoverageCollector.supported?
          collector = CoverageCollector.new(self)
        else
          puts "[overcover] WARNING: Using the slow TraceCollector since this version of ruby"
          puts "[overcover] does not support Coverage.peek_result. Use MRI 2.3+ for faster results."
          collector = TraceCollector.new(self)
        end
        root_path = Dir.pwd.to_s

        RSpec.configure do |config|
          # overcover
          config.before(:example) do |example|
            # puts "BEFORE #{example} #{example.location}"
            # puts "puts pid=#{Process.pid}"
            file = example.file_path.sub(root_path, ".")
            collector.before(file)
          end

          config.after(:example) do |example|
            # puts "AFTER #{example} #{example.location}"
            # puts "puts pid=#{Process.pid}"
            file = example.file_path.sub(root_path, ".")
            collector.after(file)
          end

          config.after(:suite) do |suite|
            Overcover::Reporter.summarize
          end

        end

      end

    end

  end

end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Web Developer</title>
  <link href="common.css" rel="stylesheet">
  <link href="style-information.css" rel="stylesheet">


text:
package ru.javavlad.start;

/**
 * Создание исключительной ситуации для обеспечения
 * корректности пользовательского ввода.
 */

public class MenuOutException extends RuntimeException {
    public MenuOutException(String message) {
        super(message);
    }
}


text:
package commons

import (
	"encoding/json"
	"fmt"
	"time"
)

// NewMetric is a factory method for minimal valid Metric
func NewMetric(source, dimension, metric string, value interface{}) *Metric {
	return &Metric{
		Source:    source,
		Timestamp: time.Now(),
		Dimension: dimension,
		Metric:    metric,
		Value:     value,
	}
}

// Metric represents a generic sample of a metric in time
type Metric struct {

	// Source this collection represents
	Source string `json:"src"`

	// Timestamp of when the metric was captured
	Timestamp time.Time `json:"ts"`

	// Dimension of metrics this collection represents
	Dimension string `json:"dim"`

	// Dimension this metric represents
	Metric string `json:"met"`

	// Value of this metric
	Value interface{} `json:"val"`

	// Unit of this metric
	Unit string `json:"unit,omitempty"`

	// Context data for this metric
	Context map[string]string `json:"c,omitempty"`
}

// AddContext adds context to this metric
// and return itself to allow for chaining
func (m *Metric) AddContext(key, val string) *Metric {

	if m.Context == nil {
		m.Context = make(map[string]string)
	}

	m.Context[key] = val
	return m
}

// FormatFQName
func (m *Metric) FormatFQName() string {
	return fmt.Sprintf("src.%s.dim.%s.met.%s",
		m.Source, m.Dimension, m.Metric)
}

// String
func (m *Metric) String() string {
	return fmt.Sprintf(
		"Metric: [ Timestamp:%v, FQName:%s, Value:%v, Unit:%s, Context:%v ]",
		m.Timestamp, m.FormatFQName(), m.Value, m.Unit, m.Context,
	)
}

// ToBytes converts content of the current message into byte array
func (m *Metric) ToBytes() ([]byte, error) {
	b, err := json.Marshal(m)
	if err != nil {
		fmt.Printf("unable to marshal: %v", err.Error())
		return nil, err
	}
	return b, nil
}

// ParseMetricCollection converts array of bytes into MetricCollection pointer
func ParseMetric(data []byte) (*Metric, error) {
	col := &Metric{}
	if err := json.Unmarshal(data, &col); err != nil {
		fmt.Printf("unable to unmarshal: %s", string(data))
		return nil, err
	}
	return col, nil
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.kvm.resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import com.cloud.utils.script.Script;

public class KVMHAMonitor extends KVMHABase implements Runnable {
    private static final Logger s_logger = Logger.getLogger(KVMHAMonitor.class);
    private Map<String, NfsStoragePool> _storagePool = new ConcurrentHashMap<String, NfsStoragePool>();

    private String _hostIP; /* private ip address */

    public KVMHAMonitor(NfsStoragePool pool, String host, String scriptPath) {
        if (pool != null) {
            this._storagePool.put(pool._poolUUID, pool);
        }
        this._hostIP = host;
        this._heartBeatPath = scriptPath;
    }

    public void addStoragePool(NfsStoragePool pool) {
        synchronized (_storagePool) {
            this._storagePool.put(pool._poolUUID, pool);
        }
    }

    public void removeStoragePool(String uuid) {
        synchronized (_storagePool) {
            this._storagePool.remove(uuid);
        }
    }

    public List<NfsStoragePool> getStoragePools() {
        synchronized (_storagePool) {
            return new ArrayList<NfsStoragePool>(_storagePool.values());
        }
    }

    private class Monitor implements Runnable {

        @Override
        public void run() {
            synchronized (_storagePool) {
                for (NfsStoragePool primaryStoragePool : _storagePool.values()) {
                    String result = null;
                    for (int i = 0; i < 5; i++) {
                        Script cmd = new Script(_heartBeatPath,
                                _heartBeatUpdateTimeout, s_logger);
                        cmd.add("-i", primaryStoragePool._poolIp);
                        cmd.add("-p", primaryStoragePool._poolMountSourcePath);
                        cmd.add("-m", primaryStoragePool._mountDestPath);
                        cmd.add("-h", _hostIP);
                        result = cmd.execute();
                        if (result != null) {
                            s_logger.warn("write heartbeat failed: " + result
                                    + ", retry: " + i);
                        } else {
                            break;
                        }
                    }

                    if (result != null) {
                        s_logger.warn("write heartbeat failed: " + result
                                + "; reboot the host");
                        Script cmd = new Script(_heartBeatPath,
                                _heartBeatUpdateTimeout, s_logger);
                        cmd.add("-i", primaryStoragePool._poolIp);
                        cmd.add("-p", primaryStoragePool._poolMountSourcePath);
                        cmd.add("-m", primaryStoragePool._mountDestPath);
                        cmd.add("-c");
                        result = cmd.execute();
                    }
                }
            }

        }
    }

    @Override
    public void run() {
        // s_logger.addAppender(new org.apache.log4j.ConsoleAppender(new
        // org.apache.log4j.PatternLayout(), "System.out"));
        while (true) {
            Thread monitorThread = new Thread(new Monitor());
            monitorThread.start();
            try {
                monitorThread.join();
            } catch (InterruptedException e) {

            }

            try {
                Thread.sleep(_heartBeatUpdateFreq);
            } catch (InterruptedException e) {

            }
        }
    }

}


text:
```bash
$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
$ brew doctor
```


text:
namespace flow {

class TransformLayer : public ContainerLayer {
 public:
  TransformLayer();
  ~TransformLayer() override;

  void set_transform(const SkMatrix& transform) { transform_ = transform; }

  void Preroll(PrerollContext* context, const SkMatrix& matrix) override;
  void Paint(PaintContext& context) override;

 private:
  SkMatrix transform_;

  FTL_DISALLOW_COPY_AND_ASSIGN(TransformLayer);
};

}  // namespace flow

#endif  // FLUTTER_FLOW_LAYERS_TRANSFORM_LAYER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/coursedocs.iml" filepath="$PROJECT_DIR$/coursedocs.iml" />
    </modules>
  </component>
</project>


text:
package org.srplib.validation;

/**
 * Validates strings with regular expression.
 *
 * @author Anton Pechinsky
 */
public class ConstantValidator extends org.srplib.validation.AbstractValidator<String> {

    private final boolean valid;

    private final String message;

    public ConstantValidator(boolean valid, String message) {
        this.valid = valid;
        this.message = message;
    }

    protected boolean isValid(Validatable<String> validatable) {
        return valid;
    }

    protected ValidationError newError() {
        return Validators.newError(message);
    }
}