text:
namespace google {
namespace api {
namespace codegen {
namespace internal {

std::string LocalInclude(std::string header) {
  return absl::StrCat("\"", header, "\"");
}

std::string SystemInclude(std::string header) {
  return absl::StrCat("<", header, ">");
}

bool NoStreamingPredicate(pb::MethodDescriptor const* m) {
  return !m->client_streaming() && !m->server_streaming();
}

std::string CamelCaseToSnakeCase(std::string const& input) {
  std::string output;
  for (auto i = 0u; i < input.size(); ++i) {
    if (i + 2 < input.size()) {
      if (std::isupper(input[i + 1]) && std::islower(input[i + 2])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    if (i + 1 < input.size()) {
      if ((std::islower(input[i]) || std::isdigit(input[i])) &&
          std::isupper(input[i + 1])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    absl::StrAppend(&output, std::string(1, std::tolower(input[i])));
  }
  return output;
}

std::string ServiceNameToFilePath(std::string const& service_name) {
  std::vector<std::string> components = absl::StrSplit(service_name, '.');
  std::transform(components.begin(), components.end(), components.begin(),
                 CamelCaseToSnakeCase);
  return absl::StrJoin(components, "/");
}

std::string ProtoNameToCppName(std::string const& proto_name) {
  return "::" + absl::StrReplaceAll(proto_name, {{".", "::"}});
}

}  // namespace internal
}  // namespace codegen
}  // namespace api
}  // namespace google


text:
$: << File.join(File.dirname(__FILE__), '../lib')

require 'rubygems'
require 'test/unit'
require 'central_notifications'
require 'models/user'
require 'models/order'
require 'models/accounting'
require 'mocha'

redpajama_set_name: RedPajamaGithub


text:
<?php
//============================================================+
// File name   : example_023.php
// Begin       : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 023 for TCPDF class
//               Page Groups
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Page Groups.
 * @author Nicola Asuni
 * @since 2008-03-04
 */

// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 023');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 023', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set font
$pdf->SetFont('times', 'BI', 14);

// Start First Page Group
$pdf->startPageGroup();

// add a page
$pdf->AddPage();

// set some text to print
$txt = <<<EOD
Example of page groups.
Check the page numbers on the page footer.

This is the first page of group 1.
EOD;

// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);

// add second page
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the second page of group 1', 0, 1, 'L');

// Start Second Page Group
$pdf->startPageGroup();

// add some pages
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the first page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the second page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the third page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the fourth page of group 2', 0, 1, 'L');

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output('example_023.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+


text:
// Copyright (c) 2015 RAMBLER&Co
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <UIKit/UIKit.h>

@protocol LaunchHandler;

/**
 @author Egor Tolstoy

 This AppDelegate is responsible for handling application open from Spotlight
 */
@interface SpotlightAppDelegate : NSObject <UIApplicationDelegate>

- (instancetype)initWithLaunchHandlers:(NSArray <id<LaunchHandler>> *)launchHandlers;

@end


text:
module Azure::ARM::SQL
  module Models
    #
    # Defines values for TransparentDataEncryptionActivityStates
    #
    module TransparentDataEncryptionActivityStates
      Encrypting = "Encrypting"
      Decrypting = "Decrypting"
    end
  end
end


text:
<?php

namespace Puli\AssetPlugin\Api\Asset;

use Exception;
use Rhumsaa\Uuid\Uuid;

/**
 * Thrown when an asset mapping exists already.
 *
 * @since  1.0
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class DuplicateAssetMappingException extends Exception
{
    /**
     * Creates an exception for a UUID that exists already.
     *
     * @param Uuid      $uuid  The UUID of the mapping.
     * @param Exception $cause The exception that caused this exception.
     *
     * @return static The created exception.
     */
    public static function forUuid(Uuid $uuid, Exception $cause = null)
    {
        return new static(sprintf(
            'The asset mapping "%s" exists already.',
            $uuid->toString()
        ), 0, $cause);
    }
}


text:
shruti
------

What is it
-----------

Shruti is an open source notification system that lets one listen to all those
updates instead of reading them themselves.

It uses [Ivona service](http://www.ivona.com/) to convert text to speech.

It is meant to be used as a web based service, but its trivial to use it locally as
a desktop application.

Its written in Go, builds are available for Gnu\Linux, Mac OS X and Windows.

How it works
-------------
- There are 4 major parts of the system. Backend API server, Providers, Client and
a supporting ivona microservice.
- Backend API takes care of dumping data to postgres and serve it on demand
- Providers collect data from various sources and push it to the backend server
- Client manages to read these updates at loud for you
- Ivona service makes it easier to communicate with Ivona API

btw, it also supports instant push notifications using [pusher.com](http://pusher.com)

Why
----
- I am bored of reading everything myself. I would love if someone does the job for me
- Something that will check
    - HN, few reddit channels
    - twitter. My timeline and few accounts I like to keep up with
    - some headlines from bbc
    - some important server statuses
    - build server status updates if important
    - New email upon arrival. From and Subject
    - Share market updates. Few important share values I care about
    - any any other sites I can think of
    - any other devices that keep track of something
-... and read out loud every 15-30 minutes.
- Hence (:

About the name
-----------
- "shruti" is a Sanskrit term, which in the context of Indian music, is considered the smallest interval of pitch that the human ear can detect [Shruti - wikipedia](http://en.wikipedia.org/wiki/Shruti_%28music%29)
- besides, it is quite common name over here, and sounds catchy enough!

API Specification
-----------------

Please read the spcefication at [docs.shrutiapp.apiary.io](http://docs.shrutiapp.apiary.io/)

How to write a provider
-----------------------

Please read the documentation at [shruti-providers](https://github.com/Omie/shruti-providers/)

How to set it up
-------------

Please read the documentation at [shruti-deployment](https://github.com/Omie/shruti-deployment)

Goal
-----

- Improve and be ready for the time when IoT fianlly takes over our lives with data from everywhere
- Seriously, take a look at these few
    - [ThingSpeak](https://thingspeak.com/)
    - [xively](https://xively.com/)
    - [TEMBOO](https://www.temboo.com/)

Contributions, thoughts are welcome :)

License
-------

MIT License


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>iFrame message passing test</title>
		<meta name="description" content="iFrame message passing test">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">

		iFrame
		Toggle content

		Size(250)

		Nested

		:Hover

		TextArea

		Absolute Position

		Send Message

		Close

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

			But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?

			On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.


text:
require 'active_record'

ActiveRecord::Base.establish_connection(:adapter=>'sqlite3', :database=>File.join(File.dirname(File.expand_path(__FILE__)), 'db', 'fd_spec.sqlite3'))

class Artist < ActiveRecord::Base
  has_many :albums
end

class Album < ActiveRecord::Base
  belongs_to :artist
  has_and_belongs_to_many :tags
end

module Name; end
class Name::Tag < ActiveRecord::Base
  if ActiveRecord.respond_to?(:version) # Rails 4+
    has_and_belongs_to_many :albums, proc{order('id DESC')}
  else
    has_and_belongs_to_many :albums, :order=>'id DESC'
  end
end

class SelfRef < ActiveRecord::Base
  belongs_to :self_ref
  has_many :self_refs
end

class Account < ActiveRecord::Base
  has_many :addresses, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end


text:
<?xml version="1.0"?>
<project
    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" xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>example-module-ui</artifactId>
  <groupId>com.example.kylo.plugin</groupId>
  <version>0.10.1-SNAPSHOT</version>
  <name>example-module-ui</name>

  <parent>
    <groupId>com.example.kylo.plugin</groupId>
    <artifactId>example-module</artifactId>
    <version>0.10.1-SNAPSHOT</version>
    <relativePath>../</relativePath>
  </parent>
  <properties>
    <plugin.license.parentRelative>../../../../</plugin.license.parentRelative>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.google.code.findbugs</groupId>
      <artifactId>jsr305</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.thinkbiganalytics.kylo</groupId>
      <artifactId>kylo-ui-api</artifactId>
      <version>0.10.1-SNAPSHOT</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>license-maven-plugin</artifactId>
      <configuration>
        <roots>
          <root>src/main/java</root>
          <root>src/test</root>
        </roots>
        <excludes>
          <exclude>*.js</exclude>
          <exclued>*.html</exclued>
        </excludes>
      </configuration>
      <executions>
        <execution>
          <id>first</id>
          <goals>
            <goal>update-file-header</goal>
          </goals>
          <phase>process-sources</phase>
          <configuration>
            <roots>
              <root>src/main/java</root>
              <root>src/test/java</root>
            </roots>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>

</build>

</project>


text:
require(['/base/config/require.conf.js'], function() {
  'use strict';

  // first require.config overload: Karma specific
  require.config({
    baseUrl: '/base/src',

    paths: {
      'angular-mocks': '../bower_components/angular-mocks/angular-mocks'
    },

    shim: {
      'angular-mocks': {
        deps: ['angular']
      }
    }
  });

  require(['angular-mocks'], function() {

    var specFiles = [];
    for (var file in window.__karma__.files) {
      if (window.__karma__.files.hasOwnProperty(file)) {
        if (/\/base\/src\/.*_test\.js$/.test(file)) {
          specFiles.push(file);
        }
      }
    }

    // second overload to include specFiles and start Karma
    require.config({
      deps: specFiles,
      callback: window.__karma__.start
    });
  });
});


text:
<widget xmlns="http://www.w3.org/ns/widgets"
id=""><name>id-empty</name></widget>


text:
<?php

namespace Webtaxi\MainBundle\Entity;

use Doctrine\ORM\EntityRepository;

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


text:
**This is the repository for Apktool. If you are looking for the Apktool website. Click [here](https://github.com/iBotPeaches/Apktool/tree/gh-pages).**

[![Join the chat at https://gitter.im/iBotPeaches/Apktool](https://badges.gitter.im/iBotPeaches/Apktool.svg)](https://gitter.im/iBotPeaches/Apktool?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/iBotPeaches/Apktool.svg?branch=master)](https://travis-ci.org/iBotPeaches/Apktool)
[![Software License](https://img.shields.io/badge/license-Apache%202.0-brightgreen.svg)](https://github.com/iBotPeaches/Apktool/blob/master/LICENSE)

It is a tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications; it makes possible to debug smali code step by step. Also it makes working with app easier because of project-like files structure and automation of some repetitive tasks like building apk, etc.

It is NOT intended for piracy and other non-legal uses. It could be used for localizing, adding some features or support for custom platforms and other GOOD purposes. Just try to be fair with authors of an app, that you use and probably like.

#### Support
- [Project Page](http://ibotpeaches.github.io/Apktool/)
- [#apktool on freenode](http://webchat.freenode.net/?channels=apktool)

#### Sponsored by

* [Sourcetoad](https://www.sourcetoad.com/cool-tools/apktool/) - helping with a weekly sponsorship for continued improvement and maintenance of the project.

#### Security Vulnerabilities

If you discover a security vulnerability within Apktool, please send an e-mail to Connor Tumbleson at connor.tumbleson(at)gmail.com. All security vulnerabilities will be promptly addressed.

#### Links
- [Downloads](https://bitbucket.org/iBotPeaches/apktool/downloads)
- [Downloads Mirror](http://connortumbleson.com/apktool/)
- [How to Build](http://ibotpeaches.github.io/Apktool/build/)
- [Documentation](http://ibotpeaches.github.io/Apktool/documentation/)
- [Bug Reports](https://github.com/iBotPeaches/Apktool/issues)
- [Chat on Gitter](https://gitter.im/iBotPeaches/Apktool)
- [Changelog/Information](http://ibotpeaches.github.io/Apktool/changes/)
- [XDA Post](http://forum.xda-developers.com/showthread.php?p=28366939)
- [Source (Github)](https://github.com/iBotPeaches/Apktool)
- [Source (Bitbucket)](https://bitbucket.org/iBotPeaches/apktool/)


text:
import { BudgieUtilities } from "../../BudgieUtilities";
import { StringToNumberStartConversionType } from "../Languages/Properties/Syntax/StringToNumberSyntax";
import { LineResults } from "../LineResults";
import { CommandNames } from "../Names/CommandNames";
import { KeywordNames } from "../Names/KeywordNames";
import { Command } from "./Command";
import { CommandResult } from "./CommandResult";
import { CommandMetadata } from "./Metadata/CommandMetadata";
import { SingleParameter } from "./Metadata/Parameters/SingleParameter";
import { addLineEnder } from "./Utilities";

/**
 * Starts a block to be executed if a string can be converted to a double.
 */
export class IfStringToDoubleStartCommand extends Command {
    /**
     * Metadata on the command.
     */
    private static metadata: CommandMetadata = new CommandMetadata(CommandNames.IfStringToDoubleStart)
        .withDescription("Starts a block to be executed if a string can be converted to a double")
        .withIndentation([1])
        .withParameters([
            new SingleParameter("stringName", "Name of a string to try converting.", true),
            new SingleParameter("doubleName", "What to call the string in double form.", true),
        ]);

    /**
     * @returns Metadata on the command.
     */
    public getMetadata(): CommandMetadata {
        return IfStringToDoubleStartCommand.metadata;
    }

    /**
     * Renders the command for a language with the given parameters.
     *
     * @param parameters   The command's name, followed by any parameters.
     * @returns Line(s) of code in the language.
     */
    public render(parameters: string[]): LineResults {
        const conversionType: StringToNumberStartConversionType = this.language.syntax.strings.toDouble.conversionType;
        const lines: CommandResult[] = [];

        if (conversionType === StringToNumberStartConversionType.PredeclareConvertAndValidate) {
            this.predeclareVariables(parameters, lines);
        }

        if (conversionType !== StringToNumberStartConversionType.ValidateDirectly) {
            this.convertStrings(parameters, lines);
        }

        this.validateDoubles(parameters, lines);

        const results: LineResults = new LineResults(lines);

        results.withImports(this.language.syntax.strings.toDouble.requiredImports);
        results.commandResults[results.commandResults.length - 1].indentation = 1;

        return results;
    }

    /**
     * Adds pre-declared variables to the output lines.
     *
     * @param parameters   The command's name, followed by any parameters.
     * @param lines   Output lines of rendered language code.
     */
    private predeclareVariables(parameters: string[], lines: CommandResult[]): void {
        const initialValue = this.language.syntax.strings.toDouble.initialVariableValues;

        for (let i = 1; i < parameters.length; i += 2) {
            const declarationParameters: string[] = [CommandNames.Variable, parameters[i + 1], KeywordNames.Double];

            if (initialValue !== "") {
                declarationParameters.push(initialValue);
            }

            const declaration = this.context.convertParsed(declarationParameters).commandResults[0];
            declaration.text += this.language.syntax.style.semicolon;
            lines.push(declaration);
        }

        addLineEnder(lines, this.language.syntax.strings.toDouble.initializeVariablesEnd, 0);
    }

    /**
     * Adds string-to-double conversions to the output lines.
     *
     * @param parameters   The command's name, followed by any parameters.
     * @param lines   Output lines of rendered language code.
     */
    private convertStrings(parameters: string[], lines: CommandResult[]): void {
        if (lines.length === 0) {
            lines.push(new CommandResult("", 0));
        }

        for (let i = 1; i < parameters.length; i += 2) {
            const stringName = parameters[i];
            const doubleName = parameters[i + 1];

            addLineEnder(lines, this.language.syntax.strings.toDouble.perVariableConversionStartLeft, 0);
            addLineEnder(lines, doubleName, 0);
            addLineEnder(lines, this.language.syntax.strings.toDouble.perVariableConversionStartMiddle, 0);
            addLineEnder(lines, stringName, 0);
            addLineEnder(lines, this.language.syntax.strings.toDouble.perVariableConversionStartRight, 0);
        }
    }

    /**
     * Adds double validation checks to the output lines.
     *
     * @param parameters   The command's name, followed by any parameters.
     * @param lines   Output lines of rendered language code.
     */
    private validateDoubles(parameters: string[], lines: CommandResult[]): void {
        if (lines.length === 0) {
            lines.push(new CommandResult("", 0));
        }

        addLineEnder(lines, this.language.syntax.strings.toDouble.validationBlockLeft, 0);

        for (let i = 1; i < parameters.length; i += 2) {
            const stringName = parameters[i];
            const doubleName = parameters[i + 1];

            let comparison = this.language.syntax.strings.toDouble.validationBlockComparison;

            comparison = BudgieUtilities.stringReplaceAll(comparison, "{0}", stringName);
            comparison = BudgieUtilities.stringReplaceAll(comparison, "{1}", doubleName);

            addLineEnder(lines, comparison, 0);

            if (i < parameters.length - 2) {
                addLineEnder(lines, this.language.syntax.strings.toDouble.validationBlockMiddle, 0);
            }
        }

        addLineEnder(lines, this.language.syntax.strings.toDouble.validationBlockRight, 0);
    }
}


text:
<?php

/**
 * EDbMigration
 *
 * @link http://www.yiiframework.com/extension/extended-database-migration/
 * @link http://www.yiiframework.com/doc/guide/1.1/en/database.migration
 * @author Carsten Brandt <mail@cebe.cc>
 * @version 0.8.0-dev
 */
class EDbMigration extends CDbMigration
{
	/**
	 * @var EMigrateCommand
	 */
	private $migrateCommand;
	protected $interactive = true;

	/**
	 * @param EMigrateCommand $migrateCommand
	 */
	public function setCommand($migrateCommand)
	{
		$this->migrateCommand = $migrateCommand;
		$this->interactive = $migrateCommand->interactive;
	}

	/**
	 * @see CConsoleCommand::confirm()
	 * @param string $message
	 * @return bool
	 */
	public function confirm($message)
	{
		if (!$this->interactive) {
			return true;
		}
		return $this->migrateCommand->confirm($message);
	}

	/**
	 * @see CConsoleCommand::prompt()
	 * @param string $message
	 * @param mixed  $defaultValue will be returned when interactive is false
	 * @return string
	 */
	public function prompt($message, $defaultValue)
	{
		if (!$this->interactive) {
			return $defaultValue;
		}
		return $this->migrateCommand->prompt($message);
	}

	/**
	 * Executes a SQL statement. Silently. (only show sql on exception)
	 * This method executes the specified SQL statement using {@link dbConnection}.
	 * @param string $sql the SQL statement to be executed
	 * @param array $params input parameters (name=>value) for the SQL execution. See {@link CDbCommand::execute} for more details.
	 * @param boolean $verbose
	 */
	public function execute($sql, $params=array(), $verbose=true)
	{
		if ($verbose) {
			parent::execute($sql, $params);
		} else {
			try {
				echo "    > execute SQL ...";
				$time=microtime(true);
				$this->getDbConnection()->createCommand($sql)->execute($params);
				echo " done (time: ".sprintf('%.3f', microtime(true)-$time)."s)\n";
			} catch (CException $e) {
				echo " failed.\n\n";
				throw $e;
			}
		}
	}

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

<!--

    YamlForRails

  -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>YamlForRails</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<frameset rows="20%, 80%">
    <frameset cols="25%,35%,45%">
        <frame src="fr_file_index.html"   title="Files" name="Files" />
        <frame src="fr_class_index.html"  name="Classes" />
        <frame src="fr_method_index.html" name="Methods" />
    </frameset>
    <frame src="files/app/helpers/yaml_layout_helper_rb.html" name="docwin" />
</frameset>
</html>


text:
package com.raizlabs.android.dbflow.processor.definition;

import com.google.common.collect.Sets;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ForeignKeyReference;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.sql.QueryBuilder;
import com.raizlabs.android.dbflow.processor.Classes;
import com.raizlabs.android.dbflow.processor.DBFlowProcessor;
import com.raizlabs.android.dbflow.processor.model.ProcessorManager;
import com.raizlabs.android.dbflow.processor.utils.WriterUtils;
import com.raizlabs.android.dbflow.processor.validator.ColumnValidator;
import com.raizlabs.android.dbflow.processor.writer.CreationQueryWriter;
import com.raizlabs.android.dbflow.processor.writer.DeleteWriter;
import com.raizlabs.android.dbflow.processor.writer.ExistenceWriter;
import com.raizlabs.android.dbflow.processor.writer.FlowWriter;
import com.raizlabs.android.dbflow.processor.writer.LoadCursorWriter;
import com.raizlabs.android.dbflow.processor.writer.SQLiteStatementWriter;
import com.raizlabs.android.dbflow.processor.writer.WhereQueryWriter;
import com.squareup.javawriter.JavaWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;

/**
 * Description: Used in writing ModelAdapters
 */
public class TableDefinition extends BaseTableDefinition implements FlowWriter {

    public static final String DBFLOW_TABLE_TAG = "$Table";

    public static final String DBFLOW_TABLE_ADAPTER = "$Adapter";

    public String tableName;

    public String adapterName;

    public String databaseName;

    public ArrayList<ColumnDefinition> primaryColumnDefinitions;

    public ColumnDefinition autoIncrementDefinition;

    public ArrayList<ColumnDefinition> foreignKeyDefinitions;

    FlowWriter[] mMethodWriters;

    public TableDefinition(ProcessorManager manager, Element element) {
        super(element, manager);
        setDefinitionClassName(DBFLOW_TABLE_TAG);
        this.adapterName = getModelClassName() + DBFLOW_TABLE_ADAPTER;

        Table table = element.getAnnotation(Table.class);
        this.tableName = table.value();
        databaseName = table.databaseName();
        if (databaseName == null || databaseName.isEmpty()) {
            databaseName = DBFlowProcessor.DEFAULT_DB_NAME;
        }

        manager.addModelToDatabase(getModelClassName(), databaseName);

        if (tableName == null || tableName.isEmpty()) {
            tableName = element.getSimpleName().toString();
        }
        primaryColumnDefinitions = new ArrayList<>();
        foreignKeyDefinitions = new ArrayList<>();

        createColumnDefinitions((TypeElement) element);

        mMethodWriters = new FlowWriter[]{
                new SQLiteStatementWriter(this, false),
                new ExistenceWriter(this, false),
                new LoadCursorWriter(this, false),
                new WhereQueryWriter(this, false),
                new CreationQueryWriter(manager, this),
                new DeleteWriter(this, false)
        };

    }

    @Override
    public String getTableSourceClassName() {
        return definitionClassName;
    }

    @Override
    protected void createColumnDefinitions(TypeElement element) {
        List<? extends Element> variableElements = manager.getElements().getAllMembers(element);
        ColumnValidator columnValidator = new ColumnValidator();
        for (Element variableElement : variableElements) {
            if (variableElement.getAnnotation(Column.class) != null) {
                ColumnDefinition columnDefinition = new ColumnDefinition(manager, (VariableElement) variableElement);
                if (columnValidator.validate(manager, columnDefinition)) {
                    columnDefinitions.add(columnDefinition);
                    if (columnDefinition.columnType == Column.PRIMARY_KEY) {
                        primaryColumnDefinitions.add(columnDefinition);
                    } else if (columnDefinition.columnType == Column.FOREIGN_KEY) {
                        foreignKeyDefinitions.add(columnDefinition);
                    } else if (columnDefinition.columnType == Column.PRIMARY_KEY_AUTO_INCREMENT) {
                        autoIncrementDefinition = columnDefinition;
                    }
                }
            }
        }
    }

    public ColumnDefinition getAutoIncrementPrimaryKey() {
        return autoIncrementDefinition;
    }

    @Override
    public List<ColumnDefinition> getPrimaryColumnDefinitions() {
        return primaryColumnDefinitions;
    }

    public String getQualifiedAdapterClassName() {
        return packageName + "." + adapterName;
    }

    public String getQualifiedModelClassName() {
        return packageName + "." + getModelClassName();
    }

    @Override
    public void onWriteDefinition(JavaWriter javaWriter) throws IOException {
        javaWriter.emitEmptyLine();
        javaWriter.emitField("String", "TABLE_NAME", Sets.newHashSet(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL), "\"" + tableName + "\"");
        javaWriter.emitEmptyLine();
        for (ColumnDefinition columnDefinition : columnDefinitions) {
            columnDefinition.write(javaWriter);
        }
    }

    public void writeAdapter(ProcessingEnvironment processingEnvironment) throws IOException {
        JavaWriter javaWriter = new JavaWriter(processingEnvironment.getFiler().createSourceFile(packageName + "." + adapterName).openWriter());

        javaWriter.emitPackage(packageName);
        javaWriter.emitImports(Classes.MODEL_ADAPTER,
                Classes.FLOW_MANAGER,
                Classes.CONDITION_QUERY_BUILDER,
                Classes.CURSOR,
                Classes.CONTENT_VALUES,
                Classes.SQL_UTILS,
                Classes.SELECT,
                Classes.CONDITION
        );
        javaWriter.emitSingleLineComment("This table belongs to the %1s database", databaseName);
        javaWriter.beginType(adapterName, "class", Sets.newHashSet(Modifier.PUBLIC, Modifier.FINAL), "ModelAdapter<" + element.getSimpleName() + ">");
        InternalAdapterHelper.writeGetModelClass(javaWriter, getModelClassName());
        InternalAdapterHelper.writeGetTableName(javaWriter, getSourceFileName());

        WriterUtils.emitOverriddenMethod(javaWriter, new FlowWriter() {
            @Override
            public void write(JavaWriter javaWriter) throws IOException {
                QueryBuilder stringBuilder = new QueryBuilder("return \"INSERT INTO %1s (");

                List<String> columnNames = new ArrayList<String>();
                List<String> bindings = new ArrayList<String>();
                for (int i = 0; i < getColumnDefinitions().size(); i++) {
                    ColumnDefinition columnDefinition = getColumnDefinitions().get(i);

                    if (columnDefinition.columnType == Column.FOREIGN_KEY) {
                        for (ForeignKeyReference reference : columnDefinition.foreignKeyReferences) {
                            columnNames.add(reference.columnName());
                            bindings.add("?");
                        }
                    } else if (columnDefinition.columnType != Column.PRIMARY_KEY_AUTO_INCREMENT) {
                        columnNames.add(columnDefinition.columnName.toUpperCase());
                        bindings.add("?");
                    }
                }

                stringBuilder.appendList(columnNames).append(") VALUES (");
                stringBuilder.appendList(bindings).append(")\"");
                javaWriter.emitStatement(stringBuilder.toString(), tableName);
            }
        }, "String", "getInsertStatementQuery", Sets.newHashSet(Modifier.PROTECTED, Modifier.FINAL));

        for (FlowWriter writer : mMethodWriters) {
            writer.write(javaWriter);
        }

        WriterUtils.emitOverriddenMethod(javaWriter, new FlowWriter() {
            @Override
            public void write(JavaWriter javaWriter) throws IOException {
                javaWriter.emitStatement("return new %1s()", getQualifiedModelClassName());
            }
        }, getQualifiedModelClassName(), "newInstance", Sets.newHashSet(Modifier.PUBLIC, Modifier.FINAL));

        javaWriter.endType();
        javaWriter.close();
    }
}


text:
function changeOrientation(orientation) {
  if (typeof screen.lockOrientation == 'function')
    screen.lockOrientation('landscape');

}

angular.module('starter.directives')

.directive('game', function(GameService) {

  function link(scope, element, attrs) {
    GameService.element = element[0];
  }

  return {
    link: link,
    scope: {
      logic: '='
    }
  }

});


text:
package kuiperbelt

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/gorilla/websocket"
)

const (
	testRequestSessionHeader = "X-Kuiperbelt-Hogehoge"
	testSecWebSocketKey      = "AQIDBAUGBwgJCgsMDQ4PEA==" // from RFC sample
	testHelloMessage         = "hello"
)

type testSuccessConnectCallbackServer struct {
	mu           sync.Mutex
	isCallbacked bool
	isClosed     bool
	header       http.Header
}

func (s *testSuccessConnectCallbackServer) IsCallbacked() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.isCallbacked
}

func (s *testSuccessConnectCallbackServer) IsClosed() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.isClosed
}

func (s *testSuccessConnectCallbackServer) Header() http.Header {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.header
}

func (s *testSuccessConnectCallbackServer) SuccessHandler(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.isCallbacked = true
	s.header = r.Header
	s.mu.Unlock()

	if r.Header.Get("Connection") == "upgrade" {
		http.Error(w, "Connection header is upgrade", http.StatusBadRequest)
		return
	}
	if r.Header.Get("Upgrade") != "" {
		http.Error(w, "Upgrade header is sent", http.StatusBadRequest)
		return
	}
	for n := range r.Header {
		if strings.HasPrefix(strings.ToLower(n), "sec-websocket") {
			http.Error(w, n+" header is sent", http.StatusBadRequest)
			return
		}
	}
	if r.Header.Get("X-Forwarded-For") != "" {
		http.Error(w, "X-Forwarded-For must be removed", http.StatusBadRequest)
		return
	}
	if r.Header.Get("X-Foo") != "Foo" {
		http.Error(w, "X-Foo is unexpected", http.StatusBadRequest)
		return
	}

	w.Header().Add(TestConfig.SessionHeader, "hogehoge")
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, testHelloMessage)
}

func (s *testSuccessConnectCallbackServer) FailHandler(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.isCallbacked = true
	s.header = r.Header
	s.mu.Unlock()
	w.WriteHeader(http.StatusForbidden)
	io.WriteString(w, "fail authorization!")
}

func (s *testSuccessConnectCallbackServer) CloseHandler(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.isClosed = true
	s.header = r.Header
	s.mu.Unlock()
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, "")
}

func (s *testSuccessConnectCallbackServer) SlowHandler(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.isCallbacked = true
	s.header = r.Header
	s.mu.Unlock()
	time.Sleep(10 * time.Second)
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, "slow response")
}

func newTestWebSocketRequest(url string) (*http.Request, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Upgrade", "websocket")
	req.Header.Add("Connection", "upgrade")
	req.Header.Add("Sec-WebSocket-Protocol", "kuiperbelt")
	req.Header.Add("Sec-WebSocket-Version", "13")
	req.Header.Add("Sec-WebSocket-Key", testSecWebSocketKey)
	req.Header.Add("X-Forwarded-For", "192.168.1.1")
	req.Header.Add(testRequestSessionHeader, "hogehoge")

	return req, nil
}

func TestWebSocketServer__Handler__SuccessAuthorized(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))

	c := TestConfig
	c.Callback.Connect = tcc.URL

	server := NewWebSocketServer(c, NewStats(), &pool)

	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	req, err := newTestWebSocketRequest(tc.URL)
	if err != nil {
		t.Fatal("cannot create request error:", err)
	}

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("to server upgrade request unexpected error:", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusSwitchingProtocols {
		t.Error("unexpected status code:", resp.StatusCode)
	}

	if !callbackServer.IsCallbacked() {
		t.Error("callback server doesn't receive request")
	}
	if callbackServer.Header().Get(testRequestSessionHeader) != "hogehoge" {
		t.Error(
			"callback server doesn't receive session key:",
			callbackServer.Header().Get(testRequestSessionHeader),
		)
	}
	if callbackServer.Header().Get(ENDPOINT_HEADER_NAME) != c.Endpoint {
		t.Error(
			"callback server doesn't receive endpoint name:",
			callbackServer.Header().Get(testRequestSessionHeader),
		)
	}
}

func TestWebSocketServer__Handler__FailAuthorized(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc := httptest.NewServer(http.HandlerFunc(callbackServer.FailHandler))

	c := TestConfig
	c.Callback.Connect = tcc.URL

	server := NewWebSocketServer(c, NewStats(), &pool)

	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	req, err := newTestWebSocketRequest(tc.URL)
	if err != nil {
		t.Fatal("cannot create request error:", err)
	}

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("to server upgrade request unexpected error:", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusForbidden {
		t.Error("unexpected status code:", resp.StatusCode)
	}
	b := new(bytes.Buffer)
	b.ReadFrom(resp.Body)

	if b.String() != "fail authorization!" {
		t.Errorf("callback message is not in response: %s", b.String())
	}
}

func TestWebSocketServer__Handler__CloseByClient(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc1 := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))
	tcc2 := httptest.NewServer(http.HandlerFunc(callbackServer.CloseHandler))

	c := TestConfig
	c.Callback.Connect = tcc1.URL
	c.Callback.Close = tcc2.URL

	server := NewWebSocketServer(c, NewStats(), &pool)

	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	dialer := websocket.Dialer{}
	wsURL := strings.Replace(tc.URL, "http://", "ws://", -1)
	conn, _, err := dialer.Dial(wsURL, http.Header{testRequestSessionHeader: []string{"hogehoge"}})
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	conn.ReadMessage() // pull and drop initial message
	_, err = pool.Get("hogehoge")
	if err != nil {
		t.Fatal("cannot get session error:", err)
	}

	err = conn.WriteMessage(websocket.TextMessage, []byte("barbar"))
	if err != nil {
		t.Fatal("cannot write to connection error:", err)
	}

	err = conn.Close()
	if err != nil {
		t.Fatal("cannot close connection error:", err)
	}

	for i := 0; i < 5; i++ {
		time.Sleep(10 * time.Millisecond)

		_, err = pool.Get("hogehoge")
		if err != nil {
			break
		}
	}

	if err != errSessionNotFound {
		t.Error("not removed session:", err)
	}

	if !callbackServer.IsClosed() {
		t.Error("not receive close callback")
	}

}

func TestWebSocketSession__IdleTimeout(t *testing.T) {
	closeHandlerEvent := make(chan struct{})

	callbackServer := new(testSuccessConnectCallbackServer)
	tccConnect := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))
	tccClose := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			callbackServer.CloseHandler(w, r)
			closeHandlerEvent <- struct{}{}
		}),
	)

	c := TestConfig
	c.IdleTimeout = time.Second * 2
	c.Callback.Connect = tccConnect.URL
	c.Callback.Close = tccClose.URL

	var pool SessionPool
	server := NewWebSocketServer(c, NewStats(), &pool)
	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	dialer := websocket.Dialer{}
	wsURL := strings.Replace(tc.URL, "http://", "ws://", -1)
	conn, _, err := dialer.Dial(wsURL, http.Header{testRequestSessionHeader: []string{"hogehoge"}})
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}
	receivedPongCh := make(chan struct{}, 3)
	conn.SetPongHandler(func(msg string) error {
		receivedPongCh <- struct{}{}
		if msg != "hello" {
			t.Errorf("pong response is invalid: got: %s, expected: hello", msg)
			return fmt.Errorf("pong response is invalid: got: %s, expected: hello", msg)
		}
		return nil
	})

	go func() {
		var err error
		for err == nil {
			_, _, err = conn.ReadMessage() // drop messages
		}
	}()

	// Must not reach connection timeout when 1sec + ping(reset deadline) + 1sec
	time.Sleep(time.Second * 1)
	err = conn.WriteControl(websocket.PingMessage, []byte("hello"), time.Now().Add(time.Second))
	if err != nil {
		t.Errorf("fail send ping error: %s", err)
	}
	time.Sleep(time.Second * 1)
	if len(receivedPongCh) != 1 {
		t.Errorf("not receive pong: %d", len(receivedPongCh))
	}
	if len(closeHandlerEvent) != 0 {
		t.Fatal("rearch connection timeout with ping")
	}

	select {
	case <-closeHandlerEvent:
	case <-time.After(time.Millisecond * 1500):
		t.Error("connection timeout is not working")
	}
}

func TestWebSocketServer__Handler__SlowCallback(t *testing.T) {
	var pool SessionPool
	callbackServer := new(testSuccessConnectCallbackServer)
	tcc := httptest.NewServer(http.HandlerFunc(callbackServer.SlowHandler))

	c := TestConfig
	c.Callback.Connect = tcc.URL

	server := NewWebSocketServer(c, NewStats(), &pool)

	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	req, err := newTestWebSocketRequest(tc.URL)
	if err != nil {
		t.Fatal("cannot create request error:", err)
	}

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal("to server upgrade request unexpected error:", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusBadGateway {
		t.Error("unexpected status code:", resp.StatusCode)
	}
}

func TestWebSocketSession__CallbackReceiver(t *testing.T) {
	c := TestConfig

	receiveHandlerEvent := make(chan struct{})
	receiveBuf := &bytes.Buffer{}
	callbackServer := new(testSuccessConnectCallbackServer)
	tccConnect := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))
	tccReceive := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get("Content-Type") != "text/plain" {
				t.Errorf("received message Content-Type is not text/plain: %s", r.Header.Get("Content-Type"))
			}
			if r.Header.Get(c.SessionHeader) != "hogehoge" {
				t.Errorf("received message Session Key is not match: %s", r.Header.Get(c.SessionHeader))
			}
			io.Copy(receiveBuf, r.Body)
			defer r.Body.Close()
			receiveHandlerEvent <- struct{}{}
		}),
	)

	c.Callback.Connect = tccConnect.URL
	c.Callback.Receive = tccReceive.URL

	var pool SessionPool
	server := NewWebSocketServer(c, NewStats(), &pool)
	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	dialer := websocket.Dialer{}
	wsURL := strings.Replace(tc.URL, "http://", "ws://", -1)
	conn, _, err := dialer.Dial(wsURL, http.Header{testRequestSessionHeader: []string{"hogehoge"}})
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	go func() {
		var err error
		for err == nil {
			_, _, err = conn.ReadMessage() // drop messages
		}
	}()

	err = conn.WriteMessage(websocket.TextMessage, []byte("hello receive message"))
	if err != nil {
		t.Errorf("unexpected error on write message from client: %s", err)
	}
	<-receiveHandlerEvent

	if receiveBuf.String() != "hello receive message" {
		t.Errorf("calling back message is not match: %s", receiveBuf.String())
	}
}

func TestWebSocketSession__Handler__SuccessEstablished(t *testing.T) {
	c := TestConfig

	establishHandlerEvent := make(chan struct{}, 1)
	callbackServer := new(testSuccessConnectCallbackServer)
	tccConnect := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))
	tccEstablish := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get(c.SessionHeader) != "hogehoge" {
				t.Errorf("received message Session Key is not match: %s", r.Header.Get(c.SessionHeader))
			}
			establishHandlerEvent <- struct{}{}
		}),
	)

	c.Callback.Connect = tccConnect.URL
	c.Callback.Establish = tccEstablish.URL

	var pool SessionPool
	server := NewWebSocketServer(c, NewStats(), &pool)
	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	dialer := websocket.Dialer{}
	wsURL := strings.Replace(tc.URL, "http://", "ws://", -1)
	conn, _, err := dialer.Dial(wsURL, http.Header{testRequestSessionHeader: []string{"fugafuga"}})
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	_, p, _ := conn.ReadMessage()
	if string(p) != testHelloMessage {
		t.Fatal("cannot receive the first message:", err)
	}
	select {
	case <- establishHandlerEvent:
	default:
		t.Fatal("establish callback server doesn't receive request:")
	}

	_, err = pool.Get("hogehoge")
	if err != nil {
		t.Fatal("cannot get session error:", err)
	}

	err = conn.WriteMessage(websocket.TextMessage, []byte("barbar"))
	if err != nil {
		t.Fatal("cannot write to connection error:", err)
	}

	if !callbackServer.IsCallbacked() {
		t.Error("callback server doesn't receive request")
	}
	if callbackServer.Header().Get(testRequestSessionHeader) != "fugafuga" {
		t.Error(
			"callback server doesn't receive session key:",
			callbackServer.Header().Get(testRequestSessionHeader),
		)
	}
	if callbackServer.Header().Get(ENDPOINT_HEADER_NAME) != c.Endpoint {
		t.Error(
			"callback server doesn't receive endpoint name:",
			callbackServer.Header().Get(testRequestSessionHeader),
		)
	}
}

func TestWebSocketSession__Handler__FailEstablished(t *testing.T) {
	c := TestConfig

	callbackServer := new(testSuccessConnectCallbackServer)
	tccConnect := httptest.NewServer(http.HandlerFunc(callbackServer.SuccessHandler))
	tccEstablish := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Header.Get(c.SessionHeader) != "hogehoge" {
				t.Errorf("received message Session Key is not match: %s", r.Header.Get(c.SessionHeader))
			}
			w.WriteHeader(http.StatusInternalServerError)
		}),
	)

	c.Callback.Connect = tccConnect.URL
	c.Callback.Establish = tccEstablish.URL

	var pool SessionPool
	server := NewWebSocketServer(c, NewStats(), &pool)
	tc := httptest.NewServer(http.HandlerFunc(server.Handler))

	dialer := websocket.Dialer{}
	wsURL := strings.Replace(tc.URL, "http://", "ws://", -1)
	conn, _, err := dialer.Dial(wsURL, http.Header{testRequestSessionHeader: []string{"fugafuga"}})
	if err != nil {
		t.Fatal("cannot connect error:", err)
	}

	_, _, err = conn.ReadMessage()
	if !websocket.IsCloseError(err, websocket.CloseAbnormalClosure) {
		t.Fatal("should be closed error:", err)
	}
	_, err = pool.Get("hogehoge")
	if err != errSessionNotFound {
		t.Fatal("shouldn't save session error:", err)
	}
}


text:
@API(apiVersion = "2.9.0", owner = "lightningcraft", provides = "lightningcraftAPI")
package sblectric.lightningcraft.api;

import net.minecraftforge.fml.common.API;


text:
ES5Harness.registerTest({

    id: "15.4.4.20-5-16",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.20/15.4.4.20-5-16.js",

    description: "Array.prototype.filter - RegExp Object can be used as thisArg",

    test: function testcase() {

        var accessed = false;

        var objRegExp = new RegExp();

        function callbackfn(val, idx, obj) {
            accessed = true;
            return this === objRegExp;
        }

        var newArr = [11].filter(callbackfn, objRegExp);

        return newArr[0] === 11 && accessed;
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.filter);
    }

});


text:
<?php
/**
 * TOP API: taobao.caipiao.shop.info.input request
 *
 * @author auto create
 * @since 1.0, 2013-03-23 12:41:17
 */
class CaipiaoShopInfoInputRequest
{
	/**
	 * 活动结束时间,格式需严格遵守yyyy-MM-dd HH:mm:ss,不可为空
	 **/
	private $actEndDate;

	/**
	 * 活动开始时间,格式需严格遵守yyyy-MM-dd HH:mm:ss,不可为空
	 **/
	private $actStartDate;

	/**
	 * 赠送类型:0-满就送;1-好评送;2-分享送;3-游戏送;4-收藏送,不可为空
	 **/
	private $presentType;

	/**
	 * 店铺参加的送彩票活动描述
	 **/
	private $shopDesc;

	/**
	 * 店铺名称
	 **/
	private $shopName;

	/**
	 * 店铺类目编号,不可为空
	 **/
	private $shopType;

	private $apiParas = array();

	public function setActEndDate($actEndDate)
	{
		$this->actEndDate = $actEndDate;
		$this->apiParas["act_end_date"] = $actEndDate;
	}

	public function getActEndDate()
	{
		return $this->actEndDate;
	}

	public function setActStartDate($actStartDate)
	{
		$this->actStartDate = $actStartDate;
		$this->apiParas["act_start_date"] = $actStartDate;
	}

	public function getActStartDate()
	{
		return $this->actStartDate;
	}

	public function setPresentType($presentType)
	{
		$this->presentType = $presentType;
		$this->apiParas["present_type"] = $presentType;
	}

	public function getPresentType()
	{
		return $this->presentType;
	}

	public function setShopDesc($shopDesc)
	{
		$this->shopDesc = $shopDesc;
		$this->apiParas["shop_desc"] = $shopDesc;
	}

	public function getShopDesc()
	{
		return $this->shopDesc;
	}

	public function setShopName($shopName)
	{
		$this->shopName = $shopName;
		$this->apiParas["shop_name"] = $shopName;
	}

	public function getShopName()
	{
		return $this->shopName;
	}

	public function setShopType($shopType)
	{
		$this->shopType = $shopType;
		$this->apiParas["shop_type"] = $shopType;
	}

	public function getShopType()
	{
		return $this->shopType;
	}

	public function getApiMethodName()
	{
		return "taobao.caipiao.shop.info.input";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->actEndDate,"actEndDate");
		RequestCheckUtil::checkNotNull($this->actStartDate,"actStartDate");
		RequestCheckUtil::checkNotNull($this->presentType,"presentType");
		RequestCheckUtil::checkNotNull($this->shopType,"shopType");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
package com.roadtracking.mapper.impl;

import com.roadtracking.mapper.api.IDriverMapper;
import com.roadtracking.mapper.impl.driver.MapDriver;
import com.roadtracking.persistence.entity.Driver;
import com.roadtracking.rest.dto.DriverDto;

import javax.inject.Inject;

public class DriverMapper implements IDriverMapper {

    @Inject
    private MapDriver mapDriver;

    @Override
    public Driver map(DriverDto driverDto) {
        return mapDriver.map(driverDto, Driver.class);
    }

    @Override
    public DriverDto map(Driver driver) {
        return mapDriver.map(driver, DriverDto.class);
    }
}


text:
using System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Template10.Services.NavigationService
{
    // DOCS: https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-NavigationService
    public class NavigatedEventArgs : EventArgs
    {
        public NavigatedEventArgs() { }
        public NavigatedEventArgs(NavigationEventArgs e, Page page)
        {
            Page = page;
            PageType = e.SourcePageType;
            Parameter = e.Parameter;
            NavigationMode = e.NavigationMode;
        }

        public NavigationMode NavigationMode { get; set; }
        public Type PageType { get; set; }
        public object Parameter { get; set; }
        public Page Page { get; set; }
    }
}


text:
<?php

namespace PROCERGS\VPR\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RlCriterioType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('totValue')
            ->add('totProgram')
            ->add('program1')
            ->add('program2')
            ->add('program3')
            ->add('program4')
            ->add('poll')
            ->add('corede')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'PROCERGS\VPR\CoreBundle\Entity\RlCriterio'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'procergs_vpr_corebundle_rlcriterio';
    }
}


text:
import unittest
import os
from subprocess import check_call
import shutil

cwd = os.path.dirname(__file__)

class TestDistutils(unittest.TestCase):

    def test_setup_build(self):
        check_call(['python', 'setup.py', 'build'],
                   cwd=os.path.join(cwd, 'test_distutils'))
        check_call(['python', 'setup.py', 'install', '--prefix=demo_install'],
                   cwd=os.path.join(cwd, 'test_distutils'))
        check_call(['python', '-c', 'import demo'],
                   cwd=os.path.join(cwd, 'test_distutils', 'demo_install',
                                    'lib', 'python2.7', 'site-packages'))
        check_call(['python', 'setup.py', 'clean'],
                   cwd=os.path.join(cwd, 'test_distutils'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils', 'demo_install'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils', 'build'))

    def test_setup_sdist_install(self):
        check_call(['python', 'setup.py', 'sdist', "--dist-dir=sdist"],
                   cwd=os.path.join(cwd, 'test_distutils'))
        check_call(['tar', 'xzf', 'demo-1.0.tar.gz'],
                   cwd=os.path.join(cwd, 'test_distutils', 'sdist'))
        check_call(['python', 'setup.py', 'install', '--prefix=demo_install'],
                   cwd=os.path.join(cwd, 'test_distutils', 'sdist', 'demo-1.0'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils', 'sdist'))

    def test_setup_bdist_install(self):
        check_call(['python', 'setup.py', 'bdist', "--dist-dir=bdist"],
                   cwd=os.path.join(cwd, 'test_distutils'))
        dist_path = os.path.join(cwd, 'test_distutils', 'bdist')
        tgz = [f for f in os.listdir(dist_path) if f.endswith(".tar.gz")][0]
        check_call(['tar', 'xzf', tgz], cwd=dist_path)

        def find(name, path):
            for root, dirs, files in os.walk(path):
                if name in files:
                    return os.path.join(root, name)
        demo_so = find("demo.so", dist_path)
        self.assertIsNotNone(demo_so)
        shutil.rmtree(dist_path)

    def test_setup_build2(self):
        check_call(['python', 'setup.py', 'build'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged'))
        check_call(['python', 'setup.py', 'install', '--prefix=demo_install2'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged'))
        check_call(['python', '-c', 'import demo2.a'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged', 'demo_install2',
                                    'lib', 'python2.7', 'site-packages'))
        check_call(['python', 'setup.py', 'clean'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils_packaged', 'demo_install2'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils_packaged', 'build'))

    def test_setup_sdist_install2(self):
        check_call(['python', 'setup.py', 'sdist', "--dist-dir=sdist2"],
                   cwd=os.path.join(cwd, 'test_distutils_packaged'))
        check_call(['tar', 'xzf', 'demo2-1.0.tar.gz'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged', 'sdist2'))
        check_call(['python', 'setup.py', 'install', '--prefix=demo_install2'],
                   cwd=os.path.join(cwd, 'test_distutils_packaged', 'sdist2', 'demo2-1.0'))
        shutil.rmtree(os.path.join(cwd, 'test_distutils_packaged', 'sdist2'))

    def test_setup_bdist_install2(self):
        check_call(['python', 'setup.py', 'bdist', "--dist-dir=bdist"],
                   cwd=os.path.join(cwd, 'test_distutils_packaged'))
        dist_path = os.path.join(cwd, 'test_distutils_packaged', 'bdist')
        tgz = [f for f in os.listdir(dist_path) if f.endswith(".tar.gz")][0]
        check_call(['tar', 'xzf', tgz], cwd=dist_path)

        def find(name, path):
            for root, dirs, files in os.walk(path):
                if name in files:
                    return os.path.join(root, name)
        demo_so = find("a.so", dist_path)
        self.assertIsNotNone(demo_so)
        shutil.rmtree(dist_path)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="padding2X">20dp</dimen>
</resources>


text:
import React from "react"
import Link from "gatsby-link"

import SidebarBody from "../../components/sidebar-body"
import docsSidebar from "./doc-links.yaml"
import Container from "../../components/container"
import presets from "../../utils/presets"

class IndexRoute extends React.Component {
  render() {
    return (
      <Container>

Get started

Gatsby is a blazing-fast static site generator for React.

Install Gatsby's command line tool

          npm install --global gatsby-cli

Using the Gatsby CLI

            Create a new site (with the blog starter).
            {` `}
            gatsby new gatsby-site

            cd gatsby-site

            gatsby develop — Gatsby will start a hot-reloading
            development environment accessible at localhost:8000

            Try editing the javascript pages in src/pages. Saved
            changes will live reload in the browser.

            gatsby build — Gatsby will perform an optimized
            production build for your site generating static HTML and per-route
            JavaScript code bundles.

            gatsby serve — Gatsby starts a local HTML server for
            testing your built site.

Using other starters

          Running gatsby new installs the default Gatsby starter.
          There are{` `}
          <Link to="/docs/gatsby-starters/">
            many other official and community starters
          </Link>
          {` `}
          you can use to kickstart building your Gatsby site.

Work through the tutorial

          Part one of what will be a 4-part tutorial is finished. It walks you
          through building a Gatsby site from scratch to a finished polished
          site.
          {` `}
          <Link to="/tutorial/">Go to the tutorial</Link>.

        <div
          css={{
            display: `block`,
            [presets.Tablet]: {
              display: `none`,
            },
          }}
        >

Documentation

          <SidebarBody inline yaml={docsSidebar} />

      </Container>
    )
  }
}

export default IndexRoute


text:
/** @file
 * @brief    UART over BLE application using the app_uart library (event driven).
 *
 * This UART example is configured with flow control enabled which is necessary when softdevice
 * is enabled, in order to prevent data loss. To connect the development kit with your PC via
 * UART, connect the configured RXD, TXD, RTS and CTS pins to the RXD, TXD, RTS and CTS pins
 * on header P15 on the motherboard. Then connect the RS232 port on the nRFgo motherboard to
 * your PC. Configuration for UART pins is defined in the uart_conf.h header file.
 *
 * This file contains source code for a sample application that uses the Nordic UART service.
 * Connect to the UART example via Master Control Panel and the PCA10000 USB dongle, or via
 * nRF UART 2.0 app for Android, or nRF UART app for IOS, available on
 * https://www.nordicsemi.com/Products/nRFready-Demo-APPS.
 *
 * This example should be operated in the same way as the UART example for the evaluation board
 * in the SDK. Follow the same guide for this example, given on:
 * https://devzone.nordicsemi.com/documentation/nrf51/6.0.0/s110/html/a00066.html#project_uart_nus_eval_test
 *
 * This example uses FIFO RX and FIFO TX buffer to operate with the UART. You can set the size
 * for the FIFO buffers by modifying the RX_BUFFER_SIZE and TX_BUFFER_SIZE constants.
 *
 * Documentation for the app_uart library is given in UART driver documentation in the SDK at:
 * https://devzone.nordicsemi.com/documentation/nrf51/6.1.0/s110/html/a00008.html
 */

/** @file
 *
 * @defgroup ble_sdk_uart_over_ble_main main.c
 * @{
 * @ingroup  ble_sdk_app_nus_eval
 * @brief    UART over BLE application main file.
 *
 * This file contains the source code for a sample application that uses the Nordic UART service.
 * This application uses the @ref srvlib_conn_params module.
 */

#include <stdint.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf.h"
#include "nrf51_bitfields.h"
#include "ble_hci.h"
#include "ble_advdata.h"
#include "ble_conn_params.h"
#include "softdevice_handler.h"
#include "app_timer.h"
#include "app_button.h"
#include "ble_nus.h"
#include "app_uart.h"
#include "uart_conf.h"
#include "boards.h"
#include "ble_error_log.h"
#include "ble_debug_assert_handler.h"
#include "app_util_platform.h"

#define IS_SRVC_CHANGED_CHARACT_PRESENT 0                                           /**< Include or not the service_changed characteristic. if not enabled, the server's database cannot be changed for the lifetime of the device*/

#define WAKEUP_BUTTON_PIN               BUTTON_0                                    /**< Button used to wake up the application. */

#define ADVERTISING_LED_PIN_NO          LED_0                                       /**< LED to indicate advertising state. */
#define CONNECTED_LED_PIN_NO            LED_1                                       /**< LED to indicate connected state. */

#define DEVICE_NAME                     "Nordic_UART"                               /**< Name of device. Will be included in the advertising data. */

#define APP_ADV_INTERVAL                64                                          /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#define APP_ADV_TIMEOUT_IN_SECONDS      180                                         /**< The advertising timeout (in units of seconds). */

#define APP_TIMER_PRESCALER             0                                           /**< Value of the RTC1 PRESCALER register. */
#define APP_TIMER_MAX_TIMERS            2                                           /**< Maximum number of simultaneously created timers. */
#define APP_TIMER_OP_QUEUE_SIZE         4                                           /**< Size of timer operation queues. */

#define MIN_CONN_INTERVAL               7.5                                          /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL               60                                          /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
#define SLAVE_LATENCY                   0                                           /**< slave latency. */
#define CONN_SUP_TIMEOUT                400                                         /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
#define FIRST_CONN_PARAMS_UPDATE_DELAY  APP_TIMER_TICKS(5000, APP_TIMER_PRESCALER)  /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
#define NEXT_CONN_PARAMS_UPDATE_DELAY   APP_TIMER_TICKS(30000, APP_TIMER_PRESCALER) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
#define MAX_CONN_PARAMS_UPDATE_COUNT    3                                           /**< Number of attempts before giving up the connection parameter negotiation. */

#define BUTTON_DETECTION_DELAY          APP_TIMER_TICKS(50, APP_TIMER_PRESCALER)    /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */

#define SEC_PARAM_TIMEOUT               30                                          /**< Timeout for Pairing Request or Security Request (in seconds). */
#define SEC_PARAM_BOND                  1                                           /**< Perform bonding. */
#define SEC_PARAM_MITM                  0                                           /**< Man In The Middle protection not required. */
#define SEC_PARAM_IO_CAPABILITIES       BLE_GAP_IO_CAPS_NONE                        /**< No I/O capabilities. */
#define SEC_PARAM_OOB                   0                                           /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE          7                                           /**< Minimum encryption key size. */
#define SEC_PARAM_MAX_KEY_SIZE          16                                          /**< Maximum encryption key size. */

#define START_STRING                    "Start...\n"                                /**< The string that will be sent over the UART when the application starts. */

#define DEAD_BEEF                       0xDEADBEEF                                  /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */

#define APP_GPIOTE_MAX_USERS            1

static ble_gap_sec_params_t             m_sec_params;                               /**< Security requirements for this application. */
static uint16_t                         m_conn_handle = BLE_CONN_HANDLE_INVALID;    /**< Handle of the current connection. */
static ble_nus_t                        m_nus;                                      /**< Structure to identify the Nordic UART Service. */

static bool ble_buffer_available = true;
static bool tx_complete = false;

/**@brief     Error handler function, which is called when an error has occurred.
 *
 * @warning   This handler is an example only and does not fit a final product. You need to analyze
 *            how your product is supposed to react in case of error.
 *
 * @param[in] error_code  Error code supplied to the handler.
 * @param[in] line_num    Line number where the handler is called.
 * @param[in] p_file_name Pointer to the file name.
 */
void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name)
{
    // This call can be used for debug purposes during application development.
    // @note CAUTION: Activating this code will write the stack to flash on an error.
    //                This function should NOT be used in a final product.
    //                It is intended STRICTLY for development/debugging purposes.
    //                The flash write will happen EVEN if the radio is active, thus interrupting
    //                any communication.
    //                Use with care. Un-comment the line below to use.
    //ble_debug_assert_handler(error_code, line_num, p_file_name);

    // On assert, the system can only recover with a reset.
    NVIC_SystemReset();
}

/**@brief       Assert macro callback function.
 *
 * @details     This function will be called in case of an assert in the SoftDevice.
 *
 * @warning     This handler is an example only and does not fit a final product. You need to
 *              analyze how your product is supposed to react in case of Assert.
 * @warning     On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in]   line_num   Line number of the failing ASSERT call.
 * @param[in]   file_name  File name of the failing ASSERT call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(DEAD_BEEF, line_num, p_file_name);
}

/**@brief   Function for the LEDs initialization.
 *
 * @details Initializes all LEDs used by this application.
 */
static void leds_init(void)
{
    nrf_gpio_cfg_output(ADVERTISING_LED_PIN_NO);
    nrf_gpio_cfg_output(CONNECTED_LED_PIN_NO);
}

/**@brief   Function for Timer initialization.
 *
 * @details Initializes the timer module.
 */
static void timers_init(void)
{
    // Initialize timer module
    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_MAX_TIMERS, APP_TIMER_OP_QUEUE_SIZE, false);
}

/**@brief   Function for the GAP initialization.
 *
 * @details This function will setup all the necessary GAP (Generic Access Profile)
 *          parameters of the device. It also sets the permissions and appearance.
 */
static void gap_params_init(void)
{
    uint32_t                err_code;
    ble_gap_conn_params_t   gap_conn_params;
    ble_gap_conn_sec_mode_t sec_mode;

    BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);

    err_code = sd_ble_gap_device_name_set(&sec_mode,
                                          (const uint8_t *) DEVICE_NAME,
                                          strlen(DEVICE_NAME));
    APP_ERROR_CHECK(err_code);

    memset(&gap_conn_params, 0, sizeof(gap_conn_params));

    gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
    gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
    gap_conn_params.slave_latency     = SLAVE_LATENCY;
    gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;

    err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
    APP_ERROR_CHECK(err_code);
}

/**@brief   Function for the Advertising functionality initialization.
 *
 * @details Encodes the required advertising data and passes it to the stack.
 *          Also builds a structure to be passed to the stack when starting advertising.
 */
static void advertising_init(void)
{
    uint32_t      err_code;
    ble_advdata_t advdata;
    ble_advdata_t scanrsp;
    uint8_t       flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;

    ble_uuid_t adv_uuids[] = {{BLE_UUID_NUS_SERVICE, m_nus.uuid_type}};

    memset(&advdata, 0, sizeof(advdata));
    advdata.name_type               = BLE_ADVDATA_FULL_NAME;
    advdata.include_appearance      = false;
    advdata.flags.size              = sizeof(flags);
    advdata.flags.p_data            = &flags;

    memset(&scanrsp, 0, sizeof(scanrsp));
    scanrsp.uuids_complete.uuid_cnt = sizeof(adv_uuids) / sizeof(adv_uuids[0]);
    scanrsp.uuids_complete.p_uuids  = adv_uuids;

    err_code = ble_advdata_set(&advdata, &scanrsp);
    APP_ERROR_CHECK(err_code);
}

/**@brief    Function for handling the data from the Nordic UART Service.
 *
 * @details  This function will process the data received from the Nordic UART BLE Service and send
 *           it to the UART module.
 */
/**@snippet [Handling the data received over BLE] */
void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data, uint16_t length)
{
    for (int i = 0; i < length; i++)
    {
        app_uart_put(p_data[i]);
    }
    app_uart_put('\n');
}
/**@snippet [Handling the data received over BLE] */

/**@brief Function for initializing services that will be used by the application.
 */
static void services_init(void)
{
    uint32_t         err_code;
    ble_nus_init_t   nus_init;

    memset(&nus_init, 0, sizeof(nus_init));

    nus_init.data_handler = nus_data_handler;

    err_code = ble_nus_init(&m_nus, &nus_init);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for initializing security parameters.
 */
static void sec_params_init(void)
{
    m_sec_params.timeout      = SEC_PARAM_TIMEOUT;
    m_sec_params.bond         = SEC_PARAM_BOND;
    m_sec_params.mitm         = SEC_PARAM_MITM;
    m_sec_params.io_caps      = SEC_PARAM_IO_CAPABILITIES;
    m_sec_params.oob          = SEC_PARAM_OOB;
    m_sec_params.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
    m_sec_params.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
}

/**@brief       Function for handling an event from the Connection Parameters Module.
 *
 * @details     This function will be called for all events in the Connection Parameters Module
 *              which are passed to the application.
 *
 * @note        All this function does is to disconnect. This could have been done by simply setting
 *              the disconnect_on_fail config parameter, but instead we use the event handler
 *              mechanism to demonstrate its use.
 *
 * @param[in]   p_evt   Event received from the Connection Parameters Module.
 */
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
    uint32_t err_code;

    if(p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
    {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
    }
}

/**@brief       Function for handling errors from the Connection Parameters module.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void conn_params_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

/**@brief Function for initializing the Connection Parameters module.
 */
static void conn_params_init(void)
{
    uint32_t               err_code;
    ble_conn_params_init_t cp_init;

    memset(&cp_init, 0, sizeof(cp_init));

    cp_init.p_conn_params                  = NULL;
    cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
    cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
    cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
    cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
    cp_init.disconnect_on_fail             = false;
    cp_init.evt_handler                    = on_conn_params_evt;
    cp_init.error_handler                  = conn_params_error_handler;

    err_code = ble_conn_params_init(&cp_init);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for starting advertising.
 */
static void advertising_start(void)
{
    uint32_t             err_code;
    ble_gap_adv_params_t adv_params;

    // Start advertising
    memset(&adv_params, 0, sizeof(adv_params));

    adv_params.type        = BLE_GAP_ADV_TYPE_ADV_IND;
    adv_params.p_peer_addr = NULL;
    adv_params.fp          = BLE_GAP_ADV_FP_ANY;
    adv_params.interval    = APP_ADV_INTERVAL;
    adv_params.timeout     = APP_ADV_TIMEOUT_IN_SECONDS;

    err_code = sd_ble_gap_adv_start(&adv_params);
    APP_ERROR_CHECK(err_code);

    nrf_gpio_pin_set(ADVERTISING_LED_PIN_NO);
}

/**@brief       Function for the Application's S110 SoftDevice event handler.
 *
 * @param[in]   p_ble_evt   S110 SoftDevice event.
 */
static void on_ble_evt(ble_evt_t * p_ble_evt)
{
    uint32_t                         err_code;
    static ble_gap_evt_auth_status_t m_auth_status;
    ble_gap_enc_info_t *             p_enc_info;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            nrf_gpio_pin_set(CONNECTED_LED_PIN_NO);
            nrf_gpio_pin_clear(ADVERTISING_LED_PIN_NO);
            m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;

            break;

        case BLE_GAP_EVT_DISCONNECTED:
            nrf_gpio_pin_clear(CONNECTED_LED_PIN_NO);
            m_conn_handle = BLE_CONN_HANDLE_INVALID;

            advertising_start();

            break;

        case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
            err_code = sd_ble_gap_sec_params_reply(m_conn_handle,
                                                   BLE_GAP_SEC_STATUS_SUCCESS,
                                                   &m_sec_params);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GATTS_EVT_SYS_ATTR_MISSING:
            err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0);
            APP_ERROR_CHECK(err_code);
            break;

        case BLE_GAP_EVT_AUTH_STATUS:
            m_auth_status = p_ble_evt->evt.gap_evt.params.auth_status;
            break;

        case BLE_GAP_EVT_SEC_INFO_REQUEST:
            p_enc_info = &m_auth_status.periph_keys.enc_info;
            if (p_enc_info->div == p_ble_evt->evt.gap_evt.params.sec_info_request.div)
            {
                err_code = sd_ble_gap_sec_info_reply(m_conn_handle, p_enc_info, NULL);
                APP_ERROR_CHECK(err_code);
            }
            else
            {
                // No keys found for this device
                err_code = sd_ble_gap_sec_info_reply(m_conn_handle, NULL, NULL);
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BLE_GAP_EVT_TIMEOUT:
            if (p_ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISEMENT)
            {
                nrf_gpio_pin_clear(ADVERTISING_LED_PIN_NO);

                // Configure buttons with sense level low as wakeup source.
                nrf_gpio_cfg_sense_input(WAKEUP_BUTTON_PIN,
                                         BUTTON_PULL,
                                         NRF_GPIO_PIN_SENSE_LOW);

                // Go to system-off mode (this function will not return; wakeup will cause a reset)
                err_code = sd_power_system_off();
                APP_ERROR_CHECK(err_code);
            }
            break;
        case BLE_EVT_TX_COMPLETE:
            if(!ble_buffer_available) tx_complete = true;
            break;

        default:
            // No implementation needed.
            break;
    }
}

/**@brief       Function for dispatching a S110 SoftDevice event to all modules with a S110
 *              SoftDevice event handler.
 *
 * @details     This function is called from the S110 SoftDevice event interrupt handler after a
 *              S110 SoftDevice event has been received.
 *
 * @param[in]   p_ble_evt   S110 SoftDevice event.
 */
static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
    ble_conn_params_on_ble_evt(p_ble_evt);
    ble_nus_on_ble_evt(&m_nus, p_ble_evt);
    on_ble_evt(p_ble_evt);
}

/**@brief   Function for the S110 SoftDevice initialization.
 *
 * @details This function initializes the S110 SoftDevice and the BLE event interrupt.
 */
static void ble_stack_init(void)
{
    uint32_t err_code;

    // Initialize SoftDevice.
    SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, false);

    // Enable BLE stack
    ble_enable_params_t ble_enable_params;
    memset(&ble_enable_params, 0, sizeof(ble_enable_params));
    ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT;
    err_code = sd_ble_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);

    // Subscribe for BLE events.
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}

/**@brief  Function for configuring the buttons.
 */
static void buttons_init(void)
{
    nrf_gpio_cfg_sense_input(WAKEUP_BUTTON_PIN,
                             BUTTON_PULL,
                             NRF_GPIO_PIN_SENSE_LOW);
}

/**@brief  Function for placing the application in low power state while waiting for events.
 */
static void power_manage(void)
{
    uint32_t err_code = sd_app_evt_wait();
    APP_ERROR_CHECK(err_code);
}

void uart_putstring(const uint8_t * str)
{
    uint32_t err_code;

    uint8_t len = strlen((char *) str);
    for (uint8_t i = 0; i < len; i++)
    {
        err_code = app_uart_put(str[i]);
        APP_ERROR_CHECK(err_code);
    }

}

/**@brief   Function for handling UART interrupts.
 *
 * @details This function will receive a single character from the UART and append it to a string.
 *          The string will be be sent over BLE when the last character received was a 'new line'
 *          i.e '\n' (hex 0x0D) or if the string has reached a length of @ref NUS_MAX_DATA_LENGTH.
 */

void uart_evt_callback(app_uart_evt_t * uart_evt)
{
    //uint32_t err_code;

    switch (uart_evt->evt_type)
    {
        case APP_UART_DATA:
						//Data is ready on the UART
            break;

		case APP_UART_DATA_READY:
            //Data is ready on the UART FIFO
            break;

        case APP_UART_TX_EMPTY:
			//Data has been successfully transmitted on the UART
            break;

        default:
            break;
    }

}
/**@brief  Function for initializing the UART module.
 */
static void uart_init(void)
{
    uint32_t err_code;

    APP_UART_FIFO_INIT(&comm_params,
                        RX_BUF_SIZE,
                        TX_BUF_SIZE,
                        uart_evt_callback,
                        UART_IRQ_PRIORITY,
                        err_code);

    APP_ERROR_CHECK(err_code);
}

bool ble_attempt_to_send(uint8_t * data, uint8_t length)
{
    uint32_t err_code;

    err_code = ble_nus_send_string(&m_nus, data,length);

    if(err_code == BLE_ERROR_NO_TX_BUFFERS)
    {
        /* ble tx buffer full*/
        return false;
    }
    else if (err_code != NRF_ERROR_INVALID_STATE)
	{
        APP_ERROR_CHECK(err_code);
    }

    return true;

}

/**@brief  Application main function.
 */
int main(void)
{

    static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
    static uint8_t index = 0;
    uint8_t newbyte;

    // Initialize
    leds_init();
    timers_init();
    buttons_init();
    uart_init();
    ble_stack_init();
    gap_params_init();
    services_init();
    advertising_init();
    conn_params_init();
    sec_params_init();

    uart_putstring((const uint8_t *)START_STRING);

    advertising_start();

    // Enter main loop
    for (;;)
    {
        /*Stop reading new data if there are no ble buffers available */
        if(ble_buffer_available)
        {
            if(app_uart_get(&newbyte) == NRF_SUCCESS)
            {
                data_array[index++] =  newbyte;

                if (index >= (BLE_NUS_MAX_DATA_LEN))
				{
                    ble_buffer_available=ble_attempt_to_send(&data_array[0],index);
                 	if(ble_buffer_available) index=0;
				}
            }
        }
        /* Re-transmission if ble_buffer_available was set to false*/
        if(tx_complete)
        {
            tx_complete=false;

            ble_buffer_available=ble_attempt_to_send(&data_array[0],index);
            if(ble_buffer_available) index =0;
        }

        power_manage();
    }
}

/**
 * @}
 */


text:
class ThreadPoolManager {
    using Task = std::function<void()>;
public:
    //成员函数
    void close();
    // 停止任务提交
    void shutdown();
    // 重启任务提交
    void restart();
//        // 提交一个任务

    // 提交一个任务
    template<class Func, class... Args>
    auto commit(Func&& func, Args&&... args) ->std::future<decltype(func(args...))> {
        if(_stop.load()){    // stop == true ??
            throw std::runtime_error("task executor have closed commit.");
        }
        using ResType =  decltype(func(args...));    // typename std::result_of<Func(Args...)>::type, 函数 func 的返回值类型
        auto task = std::make_shared<std::packaged_task<ResType()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
        {    // 添加任务到队列
            std::lock_guard<std::mutex> lock {_task};
            _tasks.emplace([task](){ (*task)();}); // push(Task{...})
        }
        _cv_task.notify_one();    // 唤醒线程执行
        std::future<ResType> future = task->get_future();
        return future;
    }
private:
    //私有成员函数
    bool init();
    void initData();
    // 获取一个待执行的 task
    Task get_one_task();
    // 任务调度
    void schedual();

public:
    virtual ~ThreadPoolManager();

    static ThreadPoolManager* create(size_t size = 3);
    virtual const char* objectType() {return "ThreadPoolManager"; }

private:
    ThreadPoolManager(size_t size);

private:
    // 线程池
    std::vector<std::thread> _pool;
    // 任务队列
    std::queue<Task> _tasks;
    // 同步
    std::mutex _task;

    std::condition_variable _cv_task;
    // 是否关闭提交
    std::atomic<bool> _stop;
};

ThreadPoolManager* ThreadPoolManager::create(size_t size){
    ThreadPoolManager * instance = new ThreadPoolManager(size);

    if (instance->init())
    {
        return instance;
    }
    delete instance;
    return nullptr;

}

ThreadPoolManager::~ThreadPoolManager(){
    shutdown();

    for(std::thread& thread : _pool){
        thread.detach();    // 让线程"自生自灭"
        //thread.join();        // 等待任务结束, 前提:线程一定会执行完
    }
}

ThreadPoolManager::ThreadPoolManager(size_t size): _stop (false){
    size = size < 1 ? 1 : size;
    for(size_t i = 0; i< size; ++i){
        _pool.emplace_back(&ThreadPoolManager::schedual, this);    // push_back(std::thread{...})
    }
}

bool ThreadPoolManager::init(){
    initData();

    return true;
}

void ThreadPoolManager::initData(){

}

// 停止任务提交
void ThreadPoolManager::shutdown(){
    this->_stop.store(true);
}

// 重启任务提交
void ThreadPoolManager::restart(){
    this->_stop.store(false);
}

// 获取一个待执行的 task
ThreadPoolManager::Task ThreadPoolManager::get_one_task(){
    std::unique_lock<std::mutex> lock {_task};
    _cv_task.wait(lock, [this](){ return !_tasks.empty(); });     // wait 直到有 task
    Task task {std::move(_tasks.front())};    // 取一个 task
    _tasks.pop();
    return task;
}

// 任务调度
void ThreadPoolManager::schedual(){
    while(true){
        if(Task task = get_one_task()){
            task();    //
        }else{
            // return;    // done
        }
    }
}

int add(int x ,int y){
    return x + y;
}

int  main(){
    ThreadPoolManager* threadPool = ThreadPoolManager::create();

    std::function<int(int, int )> func = std::bind(add,std::placeholders::_1,std::placeholders::_2);
    std::future<int> fSum = threadPool->commit(func,1,3);
    printf("--->%d\n", fSum.get());

    delete threadPool;
    threadPool = nullptr;
}


text:
namespace {

void OnVideoFrameExtracted(
    std::unique_ptr<VideoThumbnailParser>,
    MediaParser::ExtractVideoFrameCallback video_frame_callback,
    bool success,
    chrome::mojom::VideoFrameDataPtr frame_data,
    const absl::optional<media::VideoDecoderConfig>& config) {
  std::move(video_frame_callback).Run(success, std::move(frame_data), config);
}

}  // namespace

MediaParserAndroid::MediaParserAndroid() = default;

MediaParserAndroid::~MediaParserAndroid() = default;

void MediaParserAndroid::ExtractVideoFrame(
    const std::string& mime_type,
    uint32_t total_size,
    mojo::PendingRemote<chrome::mojom::MediaDataSource> media_data_source,
    MediaParser::ExtractVideoFrameCallback video_frame_callback) {
  auto data_source = std::make_unique<IPCDataSource>(
      std::move(media_data_source), static_cast<int64_t>(total_size));

  // Leak |parser| on utility main thread, because |data_source| lives on main
  // thread and is used on another thread as raw pointer. Leaked |parser| will
  // be deleted when utility process dies or |OnVideoFrameExtracted| callback
  // is called.
  auto parser = std::make_unique<VideoThumbnailParser>(std::move(data_source));
  auto* const parser_ptr = parser.get();
  parser_ptr->Start(base::BindOnce(&OnVideoFrameExtracted, std::move(parser),
                                   std::move(video_frame_callback)));
}


text:
require 'rsolr'

class SolrController < ApplicationController

  def select
    # Direct connection

    solr = RSolr.connect :url => Blacklight.solr_yml[Rails.env]['url']

    response = solr.get 'select', :params => params.except(:action, :controller)

    render json: response
  end

end


text:
package org.apache.solr.common.cloud;

import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.solr.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A class that expects a {@link ZkCredentialsInjector} to create Zookeeper credentials using Digest
 * scheme
 */
public class DigestZkCredentialsProvider extends DefaultZkCredentialsProvider {

  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  /** Called by reflective instantiation */
  public DigestZkCredentialsProvider() {}

  public DigestZkCredentialsProvider(ZkCredentialsInjector zkCredentialsInjector) {
    super(zkCredentialsInjector);
  }

  @Override
  protected Collection<ZkCredentials> createCredentials() {
    List<ZkCredentials> result = new ArrayList<>(1);
    List<ZkCredentialsInjector.ZkCredential> zkCredentials =
        zkCredentialsInjector.getZkCredentials();
    log.debug("createCredentials using zkCredentials: {}", zkCredentials);
    for (ZkCredentialsInjector.ZkCredential zkCredential : zkCredentials) {
      if (zkCredential.isAll()) {
        // this is the "user" with all perms that SolrZooKeeper uses to connect to zookeeper
        if (!StringUtils.isEmpty(zkCredential.getUsername())
            && !StringUtils.isEmpty(zkCredential.getPassword())) {
          result.add(
              new ZkCredentials(
                  "digest",
                  (zkCredential.getUsername() + ":" + zkCredential.getPassword())
                      .getBytes(StandardCharsets.UTF_8)));
          break; // single credentials set
        }
      }
    }
    return result;
  }
}


text:
describe('prefixedCSS', function() {
  function gimmePrefix(prop, obj) {
    var prefixes = ['Moz', 'Khtml', 'Webkit', 'O', 'ms'],
      domPrefixes = ['moz', 'khtml', 'webkit', 'o', 'ms'],
      elem     = document.createElement('div'),
      upper    = prop.charAt(0).toUpperCase() + prop.slice(1),
      len;

    if (!obj) {
      if (prop in elem.style) {
        return prop;
      }

      for (len = prefixes.length; len--;) {
        if ((prefixes[len] + upper)  in elem.style) {
          return (prefixes[len] + upper);
        }
      }
    } else {
      if (prop in obj) {
        return prop;
      }

      for (len = domPrefixes.length; len--;) {
        if ((domPrefixes[len] + upper)  in obj) {
          return (domPrefixes[len] + upper);
        }
      }
    }

    return false;
  }

  function domToCSS (name) {
    return name.replace(/([A-Z])/g, function(str, m1) {
      return '-' + m1.toLowerCase();
    }).replace(/^ms-/, '-ms-');
  }

  function cssToDOM(name) {
    return name.replace(/([a-z])-([a-z])/g, function(str, m1, m2) {
      return m1 + m2.toUpperCase();
    }).replace(/^-/, '');
  }

  function testProp (prop) {
    var prefixed = gimmePrefix(cssToDOM(prop));
    if (prefixed) {
      it('results for ' + prop + ' match the homebaked prefix finder', function() {
        expect(Modernizr.prefixedCSS(prop)).to.be(domToCSS(prefixed));
      });
    } else {
      it('results for ' + prop + ' match the homebaked prefix finder', function() {
        expect(Modernizr.prefixedCSS(prop)).to.be(false);
      });
    }
  }

  testProp('animationProperty');
  testProp('fontFeatureSettings');
  testProp('flexWrap');
  testProp('boxSizing');
  testProp('textShadow');
  testProp('resize');
  testProp('animation-property');
  testProp('font-feature-settings');
  testProp('flex-wrap');
  testProp('box-sizing');
  testProp('text-shadow');
});