text:
using namespace Nan;
using namespace v8;

const int DEFAULT_TOP_CF_RECS_COUNT = 100;

string getStringParameter(int index, NAN_METHOD_ARGS_TYPE info) {
	v8::String::Utf8Value stringParam(info[index]->ToString());
	string parsedString(*stringParam);

	return parsedString;
}

Local<Array> convertArrayToV8Array(vector<string> arr, int length) {
	Local<Array> result = New<v8::Array>(length);

	for (int i = 0; i < length; i++) {
		Nan::Set(result, i, Nan::New<String>(arr[i].c_str()).ToLocalChecked());
	}

	return result;
}

vector<string> castV8ArrayToArray(int index, NAN_METHOD_ARGS_TYPE info) {
	vector<string> documents;
	Local<Array> inputDocuments = Local<Array>::Cast(info[index]);

	for (unsigned i = 0; i < inputDocuments->Length(); i++) {
		if (Nan::Has(inputDocuments, i).FromJust()) {
			v8::String::Utf8Value doc(Nan::Get(inputDocuments, i).ToLocalChecked()->ToString());
			string document(*doc);
			documents.push_back(document);
		}
	}

	return documents;
}

void callCallbackWithInt(int index, NAN_METHOD_ARGS_TYPE info, int result) {
	Callback *callback = new Callback(info[index].As<Function>());
	Local<Value> argv[] = { Nan::New(result) };
	callback->Call(1, argv);
}

void callCallbackWithEmptyArray(int index, NAN_METHOD_ARGS_TYPE info) {
	Callback *callback = new Callback(info[index].As<Function>());
	Local<Value> argv[] = { New<v8::Array>() };
	callback->Call(1, argv);
}

vector<vector<double>> getMatrixParameter(int index, NAN_METHOD_ARGS_TYPE info) {
	vector<vector<double>> matrix;
	Local<Array> array = Local<Array>::Cast(info[index]);

	for (unsigned i = 0; i < array->Length(); i++) {
		if (Nan::Has(array, i).FromJust()) {
			vector<double> row;
			Local<Array> inputRow = Local<Array>::Cast(Nan::Get(array, i).ToLocalChecked());
			for (unsigned j = 0; j < inputRow->Length(); j++) {
				if (Nan::Has(inputRow, j).FromJust()) {
					double value = Nan::Get(inputRow, j).ToLocalChecked()->NumberValue();
					row.push_back(value);
				}
			}
			matrix.push_back(row);
		}
	}

	return matrix;
}

map<string, int> getOptionsObjectParameter(int index, NAN_METHOD_ARGS_TYPE info) {
	map<string, int> opts;
	Local<Object> obj = Local<Object>::Cast(info[index]);
	Local<Array> propertyNames = obj->GetOwnPropertyNames();
	for (int i = 0; i < propertyNames->Length(); ++i) {
		Local<Value> keyObj = propertyNames->Get(i);
		v8::String::Utf8Value keyParam(keyObj->ToString());
		string key(*keyParam);
		Local<Value> value = obj->Get(keyObj);

		if (key == "limit") {
			opts["limit"] = value->NumberValue();
		}
		else if (key == "includeRatedItems") {
			opts["includeRatedItems"] = value->BooleanValue();
		}
	}

	if (opts.find("limit") == opts.end()) opts["limit"] = -1;
	if (opts.find("includeRatedItems") == opts.end()) opts["includeRatedItems"] = -1;
	else opts["includeRatedItems"] = 1;

	return opts;
}

bool isOutsideMatrix(vector<vector<double>> matrix, int rowIndex, int colIndex) {
	return rowIndex < 0 || rowIndex >= (int)matrix.size() ||
		colIndex < 0 || (matrix.size() > 0 && colIndex >= (int)matrix[0].size());
}

void tfidfFilePaths(Recommender r, NAN_METHOD_ARGS_TYPE info, bool useStopWords) {
	string documentFilePath = getStringParameter(0, info);
	string documentsFilePath = getStringParameter(1, info);

	if (info[2]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[2].As<Function>());
		AsyncQueueWorker(
			new TfIdfFilesWorker(callback, r, documentFilePath, documentsFilePath, useStopWords)
		);
	} else if (info[3]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[3].As<Function>());
		AsyncQueueWorker(new TfIdfFilesWorker(
			callback, r, documentFilePath, documentsFilePath, useStopWords)
		);
	} else {
		// Sync
		map<string, double> weights = r.tfidf(documentFilePath, documentsFilePath, useStopWords);
		vector<double> recs = r.recommend(weights);
		vector<string> sortedDocuments = r.getSortedDocuments(recs);
		Local<Array> result = convertArrayToV8Array(sortedDocuments, sortedDocuments.size());

		info.GetReturnValue().Set(result);
	}
}

void tfidfArrays(Recommender r, NAN_METHOD_ARGS_TYPE info, bool useStopWords) {
	string query = getStringParameter(0, info);
	vector<string> documents = castV8ArrayToArray(1, info);

	if (info[2]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[2].As<Function>());
		AsyncQueueWorker(new TfIdfArraysWorker(callback, r, query, documents, useStopWords));
	} else if (info[3]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[3].As<Function>());
		AsyncQueueWorker(new TfIdfArraysWorker(callback, r, query, documents, useStopWords));
	} else {
		// Sync
		r.tfidf(query, documents, useStopWords);
		vector<double> recs = r.recommend(r.weights);
		vector<string> sortedDocuments = r.getSortedDocuments(recs);
		Local<Array> result = convertArrayToV8Array(sortedDocuments, sortedDocuments.size());

		info.GetReturnValue().Set(result);
	}
}

Local<Array> convertVectorOfPairsToV8Array(vector<pair<int, double>>& recommendations) {
	Local<Array> result = New<v8::Array>();

	for (unsigned i = 0; i < recommendations.size(); i++) {
		Local<Object> obj = Nan::New<Object>();
		Local<String> itemIdProp = Nan::New<String>("itemId").ToLocalChecked();
		Local<String> ratingProp = Nan::New<String>("rating").ToLocalChecked();
		obj->Set(itemIdProp, Nan::New<Number>(recommendations[i].first));
		obj->Set(ratingProp, Nan::New<Number>(recommendations[i].second));

		Nan::Set(result, i, obj);
	}

	return result;
}

NAN_METHOD(TfIdf) {
	Recommender r;
	if (!info[0]->IsString() || info[0]->ToString().IsEmpty()) Nan::ThrowError("Invalid query passed");

	bool useStopWords = false;
	if (info[2]->IsBoolean() && info[2]->BooleanValue()) {
		useStopWords = info[2]->BooleanValue();
	}

	if (info[1]->IsString()) {
		tfidfFilePaths(r, info, useStopWords);
	} else if (info[1]->IsArray()) {
		tfidfArrays(r, info, useStopWords);
	} else {
		Nan::ThrowError("Invalid params");
	}
}

NAN_METHOD(GetRatingPrediction) {
	Recommender r;
	if (!info[0]->IsArray() || !info[1]->IsNumber() || !info[2]->IsNumber()) {
		if (info[3]->IsFunction()) return callCallbackWithInt(3, info, 0);
		else return info.GetReturnValue().Set(0);
	}

	vector<vector<double>> ratings = getMatrixParameter(0, info);
	int rowIndex = info[1]->IntegerValue();
	int colIndex = info[2]->IntegerValue();

	if (isOutsideMatrix(ratings, rowIndex, colIndex)) {
		if (info[3]->IsFunction()) return callCallbackWithInt(3, info, 0);
		else return info.GetReturnValue().Set(0);
	}

	if (info[3]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[3].As<Function>());
		AsyncQueueWorker(new CollaborativeFilteringWorker(callback, r, ratings, rowIndex, colIndex));
	} else {
		// Sync
		double predictedRating = r.getRatingPrediction(ratings, rowIndex, colIndex);
		Local<Number> result = Nan::New(predictedRating);

		info.GetReturnValue().Set(result);
	}
}

NAN_METHOD(GetGlobalBaselineRatingPrediction) {
	Recommender r;

	if (!info[0]->IsArray() || !info[1]->IsNumber() || !info[2]->IsNumber()) {
		if (info[3]->IsFunction()) return callCallbackWithInt(3, info, 0);
		else return info.GetReturnValue().Set(0);
	}

	vector<vector<double>> ratings = getMatrixParameter(0, info);
	int rowIndex = info[1]->IntegerValue();
	int colIndex = info[2]->IntegerValue();

	if (isOutsideMatrix(ratings, rowIndex, colIndex)) {
		if (info[3]->IsFunction()) return callCallbackWithInt(3, info, 0);
		else return info.GetReturnValue().Set(0);
	}

	if (info[3]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[3].As<Function>());
		AsyncQueueWorker(new GlobalBaselineWorker(callback, r, ratings, rowIndex, colIndex));
	} else {
		// Sync
		double predictedRating = r.getGlobalBaselineRatingPrediction(ratings, rowIndex, colIndex);
		Local<Number> result = Nan::New(predictedRating);

		info.GetReturnValue().Set(result);
	}
}

NAN_METHOD(GetTopCFRecommendations) {
	Recommender r;

	if (!info[0]->IsArray() || !info[1]->IsNumber()) {
		if (info[2]->IsFunction()) return callCallbackWithEmptyArray(2, info);
		else if (info[3]->IsFunction()) return callCallbackWithEmptyArray(3, info);
		else return info.GetReturnValue().Set(New<v8::Array>());
	}

	vector<vector<double>> ratings = getMatrixParameter(0, info);
	int rowIndex = info[1]->IntegerValue();

	if (rowIndex < 0 || rowIndex > (int)ratings.size()) {
		if (info[2]->IsFunction()) return callCallbackWithEmptyArray(2, info);
		else if (info[3]->IsFunction()) return callCallbackWithEmptyArray(3, info);
		else return info.GetReturnValue().Set(New<v8::Array>());
	}

	if (info[2]->IsFunction()) {
		// Async
		Callback *callback = new Callback(info[2].As<Function>());
		AsyncQueueWorker(new TopCFRecommendationsWorker(callback, r, ratings, rowIndex, -1, -1));
	} else if (info[3]->IsFunction()) {
		// Async
		map<string, int> opts = getOptionsObjectParameter(2, info);
		Callback *callback = new Callback(info[3].As<Function>());
		AsyncQueueWorker(new TopCFRecommendationsWorker(callback, r, ratings, rowIndex, opts["limit"], opts["includeRatedItems"]));
	} else {
		// Sync
		vector<pair<int, double>> recommendations;
		if (info[2]->IsObject()) {
			map<string, int> opts = getOptionsObjectParameter(2, info);
			recommendations = r.getTopCFRecommendations(ratings, rowIndex, opts["limit"], opts["includeRatedItems"]);
		} else {
			recommendations = r.getTopCFRecommendations(ratings, rowIndex, -1, -1);
		}
		Local<Array> result = convertVectorOfPairsToV8Array(recommendations);

		info.GetReturnValue().Set(result);
	}
}

NAN_MODULE_INIT(Init) {
	Nan::Set(target, New<String>("tfidf").ToLocalChecked(),
		GetFunction(New<FunctionTemplate>(TfIdf)).ToLocalChecked());
	Nan::Set(target, New<String>("getRatingPrediction").ToLocalChecked(),
		GetFunction(New<FunctionTemplate>(GetRatingPrediction)).ToLocalChecked());
	Nan::Set(target, New<String>("getGlobalBaselineRatingPrediction").ToLocalChecked(),
		GetFunction(New<FunctionTemplate>(GetGlobalBaselineRatingPrediction)).ToLocalChecked());
	Nan::Set(target, New<String>("getTopCFRecommendations").ToLocalChecked(),
		GetFunction(New<FunctionTemplate>(GetTopCFRecommendations)).ToLocalChecked());
}

NODE_MODULE(recommender_addon, Init)


text:
<?php

class TwitterAccountTest extends SapphireTest
{
    public function testSetAccessToken()
    {
        /**
         * Should serialize the token and set it on the TwitterAccount.
         */
        $token = ['token' => 'abc', 'secret' => '123'];

        $twitterAccount = new TwitterAccount();

        $this->assertEquals(null, $twitterAccount->getField('AccessToken'));

        $twitterAccount->setAccessToken($token);

        $this->assertInternalType('string', $twitterAccount->getField('AccessToken'));
    }

    public function testGetAccessToken()
    {
        /**
         * Should return the unserialized token on TwitterAccount.
         */
        $twitterAccount = new TwitterAccount([
            'AccessToken' => serialize(['token' => 'abc', 'secret' => '123']),
        ]);

        $this->assertInternalType('array', $twitterAccount->getAccessToken());
    }

    public function testIsAuthorised()
    {
        /**
         * Should fail if an access token is not set.
         */
        $twitterAccount = new TwitterAccount();

        $this->assertFalse($twitterAccount->isAuthorised());

        /**
         * Should pass if an access token is set.
         */
        $twitterAccount = new TwitterAccount([
            'AccessToken' => serialize(['token' => 'abc', 'secret' => '123']),
        ]);

        $this->assertTrue($twitterAccount->isAuthorised());
    }
}

redpajama_set_name: RedPajamaGithub


text:
from heat.engine import clients
from heat.engine import properties
from heat.engine import resource
from heat.engine.resources.neutron import neutron
from heat.openstack.common import log as logging

logger = logging.getLogger(__name__)

class NetworkInterface(resource.Resource):

    PROPERTIES = (
        DESCRIPTION, GROUP_SET, PRIVATE_IP_ADDRESS, SOURCE_DEST_CHECK,
        SUBNET_ID, TAGS,
    ) = (
        'Description', 'GroupSet', 'PrivateIpAddress', 'SourceDestCheck',
        'SubnetId', 'Tags',
    )

    _TAG_KEYS = (
        TAG_KEY, TAG_VALUE,
    ) = (
        'Key', 'Value',
    )

    properties_schema = {
        DESCRIPTION: properties.Schema(
            properties.Schema.STRING,
            _('Description for this interface.')
        ),
        GROUP_SET: properties.Schema(
            properties.Schema.LIST,
            _('List of security group IDs associated with this interface.'),
            default=[]
        ),
        PRIVATE_IP_ADDRESS: properties.Schema(
            properties.Schema.STRING
        ),
        SOURCE_DEST_CHECK: properties.Schema(
            properties.Schema.BOOLEAN,
            _('Flag indicating if traffic to or from instance is validated.'),
            implemented=False
        ),
        SUBNET_ID: properties.Schema(
            properties.Schema.STRING,
            _('Subnet ID to associate with this interface.'),
            required=True
        ),
        TAGS: properties.Schema(
            properties.Schema.LIST,
            schema=properties.Schema(
                properties.Schema.MAP,
                _('List of tags associated with this interface.'),
                schema={
                    TAG_KEY: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                    TAG_VALUE: properties.Schema(
                        properties.Schema.STRING,
                        required=True
                    ),
                },
                implemented=False,
            )
        ),
    }

    attributes_schema = {'PrivateIpAddress': _('Private IP address of the '
                                               'network interface.')}

    @staticmethod
    def network_id_from_subnet_id(neutronclient, subnet_id):
        subnet_info = neutronclient.show_subnet(subnet_id)
        return subnet_info['subnet']['network_id']

    def __init__(self, name, json_snippet, stack):
        super(NetworkInterface, self).__init__(name, json_snippet, stack)
        self.fixed_ip_address = None

    def handle_create(self):
        client = self.neutron()

        subnet_id = self.properties[self.SUBNET_ID]
        network_id = self.network_id_from_subnet_id(client, subnet_id)

        fixed_ip = {'subnet_id': subnet_id}
        if self.properties[self.PRIVATE_IP_ADDRESS]:
            fixed_ip['ip_address'] = self.properties[self.PRIVATE_IP_ADDRESS]

        props = {
            'name': self.physical_resource_name(),
            'admin_state_up': True,
            'network_id': network_id,
            'fixed_ips': [fixed_ip]
        }

        if self.properties[self.GROUP_SET]:
            sgs = neutron.NeutronResource.get_secgroup_uuids(
                self.properties.get(self.GROUP_SET), self.neutron())
            props['security_groups'] = sgs
        port = client.create_port({'port': props})['port']
        self.resource_id_set(port['id'])

    def handle_delete(self):
        from neutronclient.common.exceptions import NeutronClientException

        client = self.neutron()
        try:
            client.delete_port(self.resource_id)
        except NeutronClientException as ex:
            if ex.status_code != 404:
                raise ex

    def _get_fixed_ip_address(self, ):
        if self.fixed_ip_address is None:
            from neutronclient.common.exceptions import NeutronClientException

            client = self.neutron()
            try:
                port = client.show_port(self.resource_id)['port']
                if port['fixed_ips'] and len(port['fixed_ips']) > 0:
                    self.fixed_ip_address = port['fixed_ips'][0]['ip_address']
            except NeutronClientException as ex:
                if ex.status_code != 404:
                    raise ex

        return self.fixed_ip_address

    def _resolve_attribute(self, name):
        if name == 'PrivateIpAddress':
            return self._get_fixed_ip_address()

def resource_mapping():
    if clients.neutronclient is None:
        return {}

    return {
        'AWS::EC2::NetworkInterface': NetworkInterface,
    }


text:
/**
 * @authors ZiQiangWang
 * @email   814120507@qq.com
 * @date    2017-07-21 15:29:35
 */
import { loseAuth } from '../actions/auth';

class NetworkError extends Error {
  constructor(message, status) {
    super(message);
    this.status = status;
  }
}

let API_ROOT;
if (process.env.NODE_ENV === 'dev') {
  API_ROOT = 'http://127.0.0.1:5000/blog/api/v1/';
} else {
  API_ROOT = 'http://me.w-z-q.com/blog/api/v1/';
}

const callApi = (endpoint, mehtod, data) => {
  const fullUrl = API_ROOT + endpoint;

  return fetch(fullUrl, {
    method: mehtod,
    mode: 'cors',
    body: JSON.stringify(data),
  })
    .then((response) => {
      if (response.status >= 200 && response.status < 300) {
        return response;
      }
      throw new NetworkError(response.statusText, response.status);
    })
    .then(response => response.json());
};

export const CALL_API = 'Call API';

export default store => next => (action) => {
  const callAPI = action[CALL_API];

  if (callAPI === undefined) {
    return next(action);
  }

  const { endpoint, types, method, params } = callAPI;

  if (!Array.isArray(types) || types.length !== 3) {
    throw new Error('Expected an array of three action types');
  }

  if (!types.every(type => typeof type === 'string')) {
    throw new Error('Expected action types to be string');
  }

  // 删除action中辅助用的CALL
  const actionWith = (data) => {
    const newAction = { ...action, ...data };
    delete newAction[CALL_API];
    return newAction;
  };
  const [requestType, successType, failureType] = types;

  const { success, failure } = action;
  const { fetchState } = store.getState();

  if (fetchState.isFetching && fetchState.type === requestType) {
    return null;
  }

  next(actionWith({ type: requestType, isFetching: true }));
  return callApi(endpoint, method, params).then(
    (json) => {
      if (json.flag) {
        next(actionWith({
          response: json.content,
          type: successType,
          isFetching: false,
        }));
        success && next(success(json.content));
      } else {
        next(actionWith({
          error: json.msg,
          type: failureType,
          isFetching: false,
        }));
        failure && next(failure(json.msg));
      }
    },
  )
    .catch(
      (error) => {
        next(actionWith({
          error: error.message || 'Something bad happened',
          type: failureType,
          isFetching: false,
        }));
        failure && next(failure(error.message));
      },
    );
};


text:
import {
  GraphQLError,
  getNamedType,
  isCompositeType,
  GraphQLEnumType,
  GraphQLNonNull,
  GraphQLInputObjectType
} from "graphql";

import { isTypeProperSuperTypeOf } from "apollo-codegen-core/lib/utilities/graphql";

import { join } from "apollo-codegen-core/lib/utilities/printing";

import {
  packageDeclaration,
  objectDeclaration,
  caseClassDeclaration,
  escapeIdentifierIfNeeded,
  comment
} from "./language";

import {
  caseClassNameForPropertyName,
  caseClassNameForFragmentName,
  caseClassNameForInlineFragment,
  operationClassName,
  enumCaseName,
  propertyFromLegacyField,
  propertyFromInputField
} from "./naming";

import { multilineString } from "./values";

import { possibleTypesForType, typeNameFromGraphQLType } from "./types";

import CodeGenerator from "apollo-codegen-core/lib/utilities/CodeGenerator";
import {
  LegacyCompilerContext,
  LegacyOperation,
  LegacyFragment,
  LegacyField,
  LegacyInlineFragment
} from "apollo-codegen-core/lib/compiler/legacyIR";
import { GraphQLType } from "graphql";
import { Property } from "./language";
import { GraphQLCompositeType } from "graphql";

export function generateSource(context: LegacyCompilerContext) {
  const generator = new CodeGenerator(context);

  generator.printOnNewline(
    "//  This file was automatically generated and should not be edited."
  );
  generator.printNewline();

  if (context.options.namespace) {
    packageDeclaration(generator, context.options.namespace);
  }

  context.typesUsed.forEach(type => {
    typeDeclarationForGraphQLType(generator, type);
  });

  Object.values(context.operations).forEach(operation => {
    classDeclarationForOperation(generator, operation);
  });

  Object.values(context.fragments).forEach(fragment => {
    caseClassDeclarationForFragment(generator, fragment);
  });

  return generator.output;
}

export function classDeclarationForOperation(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  {
    operationName,
    operationType,
    rootType,
    variables,
    fields,
    inlineFragments,
    fragmentSpreads,
    fragmentsReferenced,
    source,
    operationId
  }: LegacyOperation
) {
  let objectName;
  let protocol;

  switch (operationType) {
    case "query":
      objectName = `${operationClassName(operationName)}Query`;
      protocol = "com.apollographql.scalajs.GraphQLQuery";
      break;
    case "mutation":
      objectName = `${operationClassName(operationName)}Mutation`;
      protocol = "com.apollographql.scalajs.GraphQLMutation";
      break;
    default:
      throw new GraphQLError(`Unsupported operation type "${operationType}"`);
  }

  objectDeclaration(
    generator,
    {
      objectName,
      superclass: protocol
    },
    () => {
      if (source) {
        generator.printOnNewline("val operationString =");
        generator.withIndent(() => {
          multilineString(generator, source);
        });
      }

      if (operationId) {
        operationIdentifier(generator, operationId);
      }

      if (fragmentsReferenced && fragmentsReferenced.length > 0) {
        generator.printNewlineIfNeeded();
        generator.printOnNewline(
          "val requestString: String = { operationString"
        );
        fragmentsReferenced.forEach(fragment => {
          generator.print(
            ` + ${caseClassNameForFragmentName(fragment)}.fragmentString`
          );
        });
        generator.print(" }");

        generator.printOnNewline(
          "val operation = com.apollographql.scalajs.gql(requestString)"
        );
      } else {
        generator.printOnNewline(
          "val operation = com.apollographql.scalajs.gql(operationString)"
        );
      }

      generator.printNewlineIfNeeded();

      if (variables && variables.length > 0) {
        const properties = variables.map(({ name, type }) => {
          const propertyName = escapeIdentifierIfNeeded(name);
          const typeName = typeNameFromGraphQLType(generator.context, type);
          const isOptional = !(
            type instanceof GraphQLNonNull || type instanceof GraphQLNonNull
          );
          return { name, propertyName, type, typeName, isOptional };
        });

        caseClassDeclaration(
          generator,
          {
            caseClassName: "Variables",
            description: "",
            params: properties.map(p => {
              return {
                name: p.propertyName,
                type: p.typeName
              };
            })
          },
          () => {}
        );
      } else {
        generator.printOnNewline("type Variables = Unit");
      }

      caseClassDeclarationForSelectionSet(generator, {
        caseClassName: "Data",
        parentType: rootType,
        fields,
        inlineFragments,
        fragmentSpreads
      });
    }
  );
}

export function caseClassDeclarationForFragment(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  {
    fragmentName,
    typeCondition,
    fields,
    inlineFragments,
    fragmentSpreads,
    source
  }: LegacyFragment
) {
  const caseClassName = caseClassNameForFragmentName(fragmentName);

  caseClassDeclarationForSelectionSet(
    generator,
    {
      caseClassName,
      parentType: typeCondition,
      fields,
      inlineFragments,
      fragmentSpreads
    },
    () => {
      if (source) {
        generator.printOnNewline("val fragmentString =");
        generator.withIndent(() => {
          multilineString(generator, source);
        });
      }
    }
  );
}

export function caseClassDeclarationForSelectionSet(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  {
    caseClassName,
    parentType,
    fields,
    inlineFragments,
    fragmentSpreads,
    viewableAs
  }: {
    caseClassName: string;
    parentType: GraphQLCompositeType;
    fields: LegacyField[];
    inlineFragments?: LegacyInlineFragment[];
    fragmentSpreads?: string[];
    viewableAs?: {
      caseClassName: string;
      properties: (LegacyField & Property)[];
    };
  },
  objectClosure?: () => void
) {
  const possibleTypes = parentType
    ? possibleTypesForType(generator.context, parentType)
    : null;

  if (!possibleTypes || possibleTypes.length == 1) {
    const properties = fields
      .map(field =>
        propertyFromLegacyField(generator.context, field, caseClassName)
      )
      .filter(field => field.propertyName != "__typename");

    caseClassDeclaration(
      generator,
      {
        caseClassName,
        params: properties.map(p => {
          return {
            name: p.responseName,
            type: p.typeName
          };
        })
      },
      () => {}
    );
  } else {
    generator.printNewlineIfNeeded();
    const properties = fields
      .map(field =>
        propertyFromLegacyField(generator.context, field, caseClassName)
      )
      .filter(field => field.propertyName != "__typename");

    caseClassDeclaration(
      generator,
      {
        caseClassName,
        params: properties.map(p => {
          return {
            name: p.responseName,
            type: p.typeName
          };
        }),
        superclass: "slinky.readwrite.WithRaw"
      },
      () => {
        if (inlineFragments && inlineFragments.length > 0) {
          inlineFragments.forEach(inlineFragment => {
            const fragClass = caseClassNameForInlineFragment(inlineFragment);
            generator.printOnNewline(`def as${inlineFragment.typeCondition}`);
            generator.print(`: Option[${fragClass}] =`);
            generator.withinBlock(() => {
              generator.printOnNewline(
                `if (${fragClass}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${fragClass}]].read(this.raw)) else None`
              );
            });
          });
        }

        if (fragmentSpreads) {
          fragmentSpreads.forEach(s => {
            const fragment = generator.context.fragments[s];
            const alwaysDefined = isTypeProperSuperTypeOf(
              generator.context.schema,
              fragment.typeCondition,
              parentType
            );
            if (!alwaysDefined) {
              generator.printOnNewline(`def as${s}`);
              generator.print(`: Option[${s}] =`);
              generator.withinBlock(() => {
                generator.printOnNewline(
                  `if (${s}.possibleTypes.contains(this.raw.__typename.asInstanceOf[String])) Some(implicitly[slinky.readwrite.Reader[${s}]].read(this.raw)) else None`
                );
              });
            }
          });
        }
      }
    );

    // add types and implicit conversions
    if (inlineFragments && inlineFragments.length > 0) {
      inlineFragments.forEach(inlineFragment => {
        caseClassDeclarationForSelectionSet(generator, {
          caseClassName: caseClassNameForInlineFragment(inlineFragment),
          parentType: inlineFragment.typeCondition,
          fields: inlineFragment.fields,
          // inlineFragments: inlineFragment.inlineFragments,
          fragmentSpreads: inlineFragment.fragmentSpreads,
          viewableAs: {
            caseClassName,
            properties
          }
        });
      });
    }
  }

  objectDeclaration(generator, { objectName: caseClassName }, () => {
    if (possibleTypes) {
      generator.printNewlineIfNeeded();
      generator.printOnNewline("val possibleTypes = scala.collection.Set(");
      generator.print(
        join(Array.from(possibleTypes).map(type => `"${String(type)}"`), ", ")
      );
      generator.print(")");
    }

    if (viewableAs) {
      generator.printOnNewline(
        `implicit def to${viewableAs.caseClassName}(a: ${caseClassName}): ${
          viewableAs.caseClassName
        } = ${viewableAs.caseClassName}(${viewableAs.properties
          .map(p => "a." + p.responseName)
          .join(", ")})`
      );
    }

    if (fragmentSpreads) {
      fragmentSpreads.forEach(s => {
        const fragment = generator.context.fragments[s];
        const alwaysDefined = isTypeProperSuperTypeOf(
          generator.context.schema,
          fragment.typeCondition,
          parentType
        );
        if (alwaysDefined) {
          generator.printOnNewline(
            `implicit def to${s}(a: ${caseClassName}): ${s} = ${s}(${(
              fragment.fields || []
            )
              .map(p => "a." + p.responseName)
              .join(", ")})`
          );
        }
      });
    }

    fields
      .filter(field => isCompositeType(getNamedType(field.type)))
      .forEach(field => {
        caseClassDeclarationForSelectionSet(generator, {
          caseClassName: caseClassNameForPropertyName(field.responseName),
          parentType: getNamedType(field.type) as GraphQLCompositeType,
          fields: field.fields || [],
          inlineFragments: field.inlineFragments,
          fragmentSpreads: field.fragmentSpreads
        });
      });

    if (objectClosure) {
      objectClosure();
    }
  });
}

function operationIdentifier(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  operationId: string
) {
  if (!generator.context.options.generateOperationIds) {
    return;
  }

  generator.printNewlineIfNeeded();
  generator.printOnNewline(
    `val operationIdentifier: String = "${operationId}"`
  );
}

export function typeDeclarationForGraphQLType(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  type: GraphQLType
) {
  if (type instanceof GraphQLEnumType) {
    enumerationDeclaration(generator, type);
  } else if (type instanceof GraphQLInputObjectType) {
    caseClassDeclarationForInputObjectType(generator, type);
  }
}

function enumerationDeclaration(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  type: GraphQLEnumType
) {
  const { name, description } = type;
  const values = type.getValues();

  generator.printNewlineIfNeeded();
  comment(generator, description || "");
  generator.printOnNewline(`object ${name}`);
  generator.withinBlock(() => {
    values.forEach(value => {
      comment(generator, value.description || "");
      generator.printOnNewline(
        `val ${escapeIdentifierIfNeeded(enumCaseName(value.name))} = "${
          value.value
        }"`
      );
    });
  });
  generator.printNewline();
}

function caseClassDeclarationForInputObjectType(
  generator: CodeGenerator<LegacyCompilerContext, any>,
  type: GraphQLInputObjectType
) {
  const { name: caseClassName, description } = type;
  const fields = Object.values(type.getFields());
  const properties = fields.map(field =>
    propertyFromInputField(
      generator.context,
      field,
      generator.context.options.namespace
    )
  );

  caseClassDeclaration(
    generator,
    {
      caseClassName,
      description: description || undefined,
      params: properties.map(p => {
        return {
          name: p.propertyName,
          type: p.typeName,
          defaultValue: p.isOptional ? "scala.scalajs.js.undefined" : ""
        };
      })
    },
    () => {}
  );
}


text: AngularJS directive for smart-table to allow row selction, including keyboard navigation


text:
struct simple_node
{
   simple_node *prev_;
   simple_node *next_;
};

//Define the node traits. A single node_traits will be enough.
struct simple_node_traits
{
   typedef simple_node                             node;
   typedef node *                                  node_ptr;
   typedef const node *                            const_node_ptr;
   static node *get_next(const node *n)            {  return n->next_;  }
   static void set_next(node *n, node *next)       {  n->next_ = next;  }
   static node *get_previous(const node *n)        {  return n->prev_;  }
   static void set_previous(node *n, node *prev)   {  n->prev_ = prev;  }
};

//[doc_advanced_value_traits2_value_traits
class base_1{};
class base_2{};

struct value_1 :  public base_1, public simple_node
{
   int   id_;
   simple_node node_;
};

struct value_2 :  public base_1, public base_2, public simple_node
{
   simple_node node_;
   float id_;
};

using namespace boost::intrusive;

typedef member_value_traits
   <value_1, simple_node_traits, &value_1::node_, normal_link> ValueTraits1;
typedef member_value_traits
<value_2, simple_node_traits, &value_2::node_, normal_link> ValueTraits2;

//Now define two intrusive lists. Both lists will use the same algorithms:
// circular_list_algorithms<simple_node_traits>
typedef list <value_1, value_traits<ValueTraits1> > Value1List;
typedef list <value_2, value_traits<ValueTraits2> > Value2List;
//]

//[doc_advanced_value_traits2_test
int main()
{
   typedef std::vector<value_1> Vect1;
   typedef std::vector<value_2> Vect2;

   //Create values, with a different internal number
   Vect1 values1;
   Vect2 values2;
   for(int i = 0; i < 100; ++i){
      value_1 v1;    v1.id_ = i;          values1.push_back(v1);
      value_2 v2;    v2.id_ = (float)i;   values2.push_back(v2);
   }

   //Create the lists with the objects
   Value1List list1(values1.begin(), values1.end());
   Value2List list2(values2.begin(), values2.end());

   //Now test both lists
   Value1List::const_iterator bit1(list1.begin()), bitend1(list1.end());
   Value2List::const_iterator bit2(list2.begin()), bitend2(list2.end());

   Vect1::const_iterator it1(values1.begin()), itend1(values1.end());
   Vect2::const_iterator it2(values2.begin()), itend2(values2.end());

   //Test the objects inserted in our lists
   for(; it1 != itend1; ++it1, ++bit1,  ++it2, ++bit2){
      if(&*bit1 != &*it1 || &*bit2 != &*it2) return false;
   }
   return 0;
}
//]


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.android.qachee</groupId>
  <artifactId>Qachee</artifactId>
  <version>1.0b</version>
  <versioning>
    <versions>
      <version>1.0b</version>
    </versions>
    <lastUpdated>20140217153737</lastUpdated>
  </versioning>
</metadata>


text:
using Spooker.Time;

namespace Spooker.Graphics.Particles
{
	/// <summary>
	/// Helper for objects that want to leave particles behind them as they
	/// move around the world. This emitter implementation solves two related
	/// problems:
	///
	/// If an object wants to create particles very slowly, less than once per
	/// frame, it can be a pain to keep track of which updates ought to create
	/// a new particle versus which should not.
	///
	/// If an object is moving quickly and is creating many particles per frame,
	/// it will look ugly if these particles are all bunched up together. Much
	/// better if they can be spread out along a line between where the object
	/// is now and where it was on the previous frame. This is particularly
	/// important for leaving trails behind fast moving objects such as rockets.
	///
	/// This emitter class keeps track of a moving object, remembering its
	/// previous position so it can calculate the velocity of the object. It
	/// works out the perfect locations for creating particles at any frequency
	/// you specify, regardless of whether this is faster or slower than the
	/// game update rate.
	/// </summary>
	public class ParticleEmitter
	{
		#region Fields
	    private readonly ParticleSystem _particleSystem;
        private readonly float _timeBetweenParticles;
        private Vector2 _position;
        private float _timeLeftOver;
		#endregion

		/// <summary>
		/// Gets the location of the emitter. To change locations, pass a new value
		/// in to Update.
		/// </summary>
		public Vector2 Position
		{
			get { return _position; }
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Spooker.Graphics.Particles.ParticleEmitter"/> class.
		/// </summary>
		/// <param name="particleSystem">Particle system.</param>
		/// <param name="particlesPerSecond">Particles per second.</param>
		/// <param name="initialPosition">Initial position.</param>
		public ParticleEmitter(
			ParticleSystem particleSystem,
			float particlesPerSecond,
			Vector2 initialPosition)
		{
			_particleSystem = particleSystem;
			_timeBetweenParticles = 1.0f / particlesPerSecond;
			_position = initialPosition;
		}

		/// <summary>
		/// Updates the emitter, creating the appropriate number of particles
		/// in the appropriate positions.
		/// </summary>
		/// <param name="gameTime">Game time.</param>
		/// <param name="newPosition">New position.</param>
		public void Update(GameTime gameTime, Vector2 newPosition)
		{
			Update (gameTime, newPosition, Matrix.Identity);
		}

		/// <summary>
		/// Updates the emitter, creating the appropriate number of particles
		/// in the appropriate positions.
		/// </summary>
		/// <param name="gameTime">Game time.</param>
		/// <param name="newPosition">New position.</param>
		/// <param name="transform">Transform.</param>
		public void Update(GameTime gameTime, Vector2 newPosition, Matrix transform)
		{
			// Work out how much time has passed since the previous update.
			var elapsedTime = (float)gameTime.ElapsedGameTime.Seconds;

			if (elapsedTime > 0)
			{
				var pos = transform.TransformPoint(_position);
				var newPos = transform.TransformPoint(newPosition);

				// Work out how fast we are moving.
				var velocity = (newPos - pos) / elapsedTime;

				// If we had any time left over that we didn't use during the
				// previous update, add that to the current elapsed time.
				float timeToSpend = _timeLeftOver + elapsedTime;

				// Counter for looping over the time interval.
				float currentTime = -_timeLeftOver;

				// Create particles as long as we have a big enough time interval.
				while (timeToSpend > _timeBetweenParticles)
				{
					currentTime += _timeBetweenParticles;
					timeToSpend -= _timeBetweenParticles;

					// Work out the optimal position for this particle. This will produce
					// evenly spaced particles regardless of the object speed, particle
					// creation frequency, or game update rate.
					float mu = currentTime / elapsedTime;

					var particlePosition = Vector2.Lerp(pos, newPos, mu);

					// Create the particle.
					_particleSystem.AddParticles(particlePosition, velocity);
				}

				// Store any time we didn't use, so it can be part of the next update.
				_timeLeftOver = timeToSpend;
			}

			_position = newPosition;
		}
	}
}


text:
python-lucky
============

Kanban API integration for Python.

Work in progress see leankit/scripts.py.


text:
package com.cloud.legacymodel.network.rules;

public class UdpAclRule extends AclRule {
    private final String type = "udp";
    private int firstPort;
    private int lastPort;

    public UdpAclRule() {
        // Empty contructor for (de)serialization
    }

    public UdpAclRule(final String cidr, final boolean allowed, final int firstPort, final int lastPort) {
        super(cidr, allowed);
        this.firstPort = firstPort;
        this.lastPort = lastPort;
    }

    public int getFirstPort() {
        return this.firstPort;
    }

    public void setFirstPort(final int firstPort) {
        this.firstPort = firstPort;
    }

    public int getLastPort() {
        return this.lastPort;
    }

    public void setLastPort(final int lastPort) {
        this.lastPort = lastPort;
    }
}


text:
title: Installation
layout: docs
---

# Installation

Before starting, you should install the Flynn command-line interface.

On OS X and Linux, run this command in a terminal:

```text
L=/usr/local/bin/flynn && curl -sSL -A "`uname -sp`" https://dl.flynn.io/cli | zcat >$L && chmod +x $L
```

On Windows, run this command in PowerShell:

```text
(New-Object Net.WebClient).DownloadString('https://dl.flynn.io/cli.ps1') | iex
```

If you want to run Flynn on your local machine, the easiest way is to install the
[Vagrant demo environment](#vagrant).

If you'd like to deploy Flynn to AWS, [you can use the CLI](#aws).

If you want to manually install Flynn, follow the [Ubuntu 14.04 amd64](#ubuntu-14.04-amd64) guide.
Currently only Ubuntu 14.04 amd64 is supported, but this is a temporary packaging limitation, we
have no actual dependency on Ubuntu.

## Vagrant

### Dependencies

Both Vagrant and VirtualBox need to be installed, so if you don't have them already you should
install them by following the directions on their respective web sites:

* [VirtualBox](https://www.virtualbox.org/)
* [Vagrant 1.6 or greater](http://www.vagrantup.com/)

### Installation

Clone the Flynn git repository:

```
$ git clone https://github.com/flynn/flynn
```

A Makefile is provided for convenience as a simple wrapper around common flynn
commands. For systems without `make` installed, manually run the `vagrant` commands.

Change to the `demo` directory and bring up the Vagrant box:

```
$ cd flynn/demo

# Provision the VM and bootstrap a flynn cluster
# Init should only be called once
$ make init
# Print login token and open dashboard in browser
$ make dashboard

# OR

$ vagrant up
# Follow the instructions output by vagrant up, then...
$ flynn key add
$ flynn -a dashboard env get LOGIN_TOKEN
# Copy the login token
# Open the dashboard in a browser
$ open http://dashboard.demo.localflynn.com
```

Additional make commands:

```
# Halt the VM
$ make down

# Bring up the VM and flynn
$ make up

# SSH into the VM
$ make ssh

# Destroy the VM
$ make destroy

# See Makefile for other useful commands
```

If the VM fails to boot for any reason, you can restart the process by running the following:

```
# Stop and restart the VM
$ make down
$ make up

# OR, destroy and rebuild the VM
$ make reset
```

With a successful installation, you will have a single node Flynn cluster running inside the VM.

Now you have Flynn installed and running, head over to the [Using Flynn](/docs)
page for guides on deploying your applications to Flynn.

## AWS

The [Flynn CLI](https://cli.flynn.io) includes an installer that will boot and
configure a Flynn cluster on Amazon Web Services using CloudFormation. It
automatically performs all of the steps required to install Flynn.

Just run `flynn install` to start the installation.

## Ubuntu 14.04 amd64

Before we get going with the installation, please note that if you plan on running a multi-node
cluster, you should boot at least 3 nodes to keep etcd efficient
(see [here](https://github.com/coreos/etcd/blob/v0.4.6/Documentation/optimal-cluster-size.md) for
an explanation).

*NOTE: If you are installing on Linode, you need to use native kernels (rather than
Linode kernels) for AUFS support, see [this guide](https://www.linode.com/docs/tools-reference/custom-kernels-distros/run-a-distributionsupplied-kernel-with-pvgrub)
for instructions on how to switch.*

### Installation

Download and run the Flynn installer script:

```
$ sudo bash < <(curl -fsSL https://dl.flynn.io/install-flynn)
```

If you would rather take a look at the contents of the script before running it as root, download and
run it in two separate steps:

```
$ curl -fsSL -o /tmp/install-flynn https://dl.flynn.io/install-flynn
... take a look at the contents of /tmp/install-flynn ...
$ sudo bash /tmp/install-flynn
```

Running the installer script will:

1. Install Flynn's runtime dependencies
2. Download, verify and install the `flynn-host` binary
3. Download and verify filesystem images for each of the Flynn components
4. Install an Upstart job for controlling the `flynn-host` daemon

Some of the filesystem images are quite large (hundreds of MB) so step 3 could take a while depending on
your internet connection.

### Rinse and repeat

You should install Flynn as above on every host that you want to be in the Flynn cluster.

### Start Flynn Layer 0

First, ensure that all network traffic is allowed between all nodes in the cluster (specifically
all UDP and TCP packets). The following ports should also be open externally on the firewalls
for all nodes in the cluster:

* 80 (HTTP)
* 443 (HTTPS)
* 2222 (Git over SSH)
* 3000 to 3500 (user defined TCP services)

**Note:** A firewall with this configuration is _required_ to prevent external
access to internal management APIs.

The next step is to configure a Layer 0 cluster by starting the flynn-host daemon on all
nodes. The daemon uses etcd for leader election, and etcd needs to be aware of all of the
other nodes for it to function correctly.

If you are starting more than one node, the etcd cluster should be configured
using a [discovery
token](https://coreos.com/docs/cluster-management/setup/etcd-cluster-discovery/).
`flynn-host init` is a tool that handles generating and configuring the token.

On the first node, create a new token with the `--init-discovery` flag. The
minimum multi-node cluster size is three, and this command does not need to be
run if you are only starting a single node.

```
$ sudo flynn-host init --init-discovery
https://discovery.flynn.io/clusters/53e8402e-030f-4861-95ba-d5b5a91b5902
```

On the rest of the nodes, configure the generated discovery token:

```
$ sudo flynn-host init --discovery https://discovery.flynn.io/clusters/53e8402e-030f-4861-95ba-d5b5a91b5902
```

Then, start the daemon by running:

```
$ sudo start flynn-host
```

You can check the status of the daemon by running:

```
$ sudo status flynn-host
flynn-host start/running, process 4090
```

If the status is `stop/waiting`, the daemon has failed to start for some reason. Check the
log file (`/var/log/upstart/flynn-host.log`) for any errors and try starting the daemon
again.

### Start Flynn Layer 1

After you have a running Layer 0 cluster, you can now bootstrap Layer 1 with
`flynn-host bootstrap`. You'll need a domain name with DNS A records pointing to
every node IP address and a second, wildcard domain CNAME to the cluster domain.

**Example**

```
demo.localflynn.com.    A      192.168.84.42
demo.localflynn.com.    A      192.168.84.43
demo.localflynn.com.    A      192.168.84.44
*.demo.localflynn.com.  CNAME  demo.localflynn.com.
```

*If you are just using a single node and don't want to initially setup DNS
records, you can use [xip.io](http://xip.io) which provides wildcard DNS for
any IP address.*

Set `CLUSTER_DOMAIN` to the main domain name and start the bootstrap process,
specifying the number of hosts that are expected to be present and the discovery
token if you created one.

```
$ sudo \
    CLUSTER_DOMAIN=demo.localflynn.com \
    flynn-host bootstrap \
    --min-hosts 3 \
    --discovery https://discovery.flynn.io/clusters/53e8402e-030f-4861-95ba-d5b5a91b5902
```

*Note: You only need to run this on a single node in the cluster. It will
schedule jobs on nodes across the cluster as required.*

The Layer 1 bootstrapper will get all necessary services running using the Layer
0 API. The final log line will contain configuration that may be used with the
[command-line interface](/docs/cli).

If you try these instructions and run into issues, please open an issue or pull
request.

Now you have Flynn installed and running, head over to the [Using Flynn](/docs)
page for guides on deploying your applications to Flynn.


text:
package de.flapdoodle.embed.process.config.process;

import org.immutables.value.Value.Immutable;

import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.Slf4jLevel;
import de.flapdoodle.embed.process.io.StreamProcessor;

@Immutable
public interface ProcessOutput {

	StreamProcessor output();

	StreamProcessor error();

	StreamProcessor commands();

	static ProcessOutput namedConsole(String label) {
		return builder()
				.output(Processors.namedConsole("["+label+" output]"))
				.error(Processors.namedConsole("["+label+" error]"))
				.commands(Processors.console())
				.build();
	}

	static ProcessOutput silent() {
		return builder()
				.output(Processors.silent())
				.error(Processors.silent())
				.commands(Processors.silent())
				.build();
	}

	static ProcessOutput named(String label, org.slf4j.Logger logger) {
		return builder()
				.output(Processors.named("["+label+" output]", Processors.logTo(logger, Slf4jLevel.INFO)))
				.error(Processors.named("["+label+" error]", Processors.logTo(logger, Slf4jLevel.ERROR)))
				.commands(Processors.logTo(logger, Slf4jLevel.DEBUG))
				.build();
	}

	static ImmutableProcessOutput.Builder builder() {
		return ImmutableProcessOutput.builder();
	}
}


text:
require "rvm/capistrano"  # Load RVM's capistrano plugin.
require "bundler/capistrano" # Bundler will be activated after each new deployment

default_run_options[:pty] = true # For sudo

set :use_sudo, false

set :application, "danthought.ideasbulb.com" # Set Application Name
set :repository,  "git://github.com/danjiang/ideasbulb.git" # Set Source Code Repository
set :scm, :git # Set SCM

set :deploy_to, "/var/www/danthought.ideasbulb.com" # Deployed Server Directory

role :app, application # Set Application Server Address
role :web, application # Set Web Server Address
role :db,  application, :primary => true # Set Database Server Address

set :rvm_type, :system  # Copy the exact line. I really mean :system here
set :rvm_ruby_string, 'ruby-1.9.2-p290@ideasbulb' # Set RVM Env You Want App To Run In

namespace :foreman do
  desc "Start the application services"
  task :start, :roles => :app do
    sudo "#{sudo} start #{application}"
  end

  desc "Stop the application services"
  task :stop, :roles => :app do
    sudo "#{sudo} stop #{application}"
  end

  desc "Restart the application services"
  task :restart, :roles => :app do
    run "#{sudo} start #{application} || #{sudo} restart #{application}"
  end

  desc "Display logs for a certain process - arg example: PROCESS=web-1"
  task :logs, :roles => :app do
    run "cd #{current_path}/log && cat #{ENV["PROCESS"]}.log"
  end

  desc "Export the Procfile to upstart scripts"
  task :export, :roles => :app do
    sudo "whoami"
    run "cd #{current_path} && rvmsudo bundle exec foreman export upstart /etc/init -a #{application} -l #{shared_path}/log -u root -f #{current_path}/Procfile.production -c worker=2"
  end
end

namespace :deploy do

  desc "Symlink extra configs and folders."
  task :symlink_extras do
    run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
    run "ln -nfs #{shared_path}/config/app_config.yml #{release_path}/config/app_config.yml"
  end

  desc "Setup shared directory."
  task :setup_shared do
    run "mkdir -p #{shared_path}/config"
    # Read Local File and Upload
    put File.read("config/examples/database.yml"), "#{shared_path}/config/database.yml"
    put File.read("config/examples/app_config.yml"), "#{shared_path}/config/app_config.yml"
  end

  desc "Restarts your application."
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
  end

end

# $ cap deploy:setup -S skip_setup_shared=true
after "deploy:setup", "deploy:setup_shared" unless fetch(:skip_setup_shared, false)
after "deploy:setup", "foreman:export"
before "deploy:assets:precompile", "deploy:symlink_extras"
after "deploy:update_code", "deploy:migrate"


text:
@implementation AKDelay
{
    AKParameter * _input;
    AKConstant * _delayTime;
}

- (instancetype)initWithInput:(AKParameter *)input
                    delayTime:(AKConstant *)delayTime
                     feedback:(AKParameter *)feedback
{
    self = [super initWithString:[self operationName]];
    if (self) {
        _input = input;
        _delayTime = delayTime;
        _feedback = feedback;
        [self setUpConnections];
}
    return self;
}

- (instancetype)initWithInput:(AKParameter *)input
                    delayTime:(AKConstant *)delayTime
{
    self = [super initWithString:[self operationName]];
    if (self) {
        _input = input;
        _delayTime = delayTime;
        // Default Values
        _feedback = akp(0.0);
        [self setUpConnections];
    }
    return self;
}

+ (instancetype)delayWithInput:(AKParameter *)input
                    delayTime:(AKConstant *)delayTime
{
    return [[AKDelay alloc] initWithInput:input
                    delayTime:delayTime];
}

- (void)setFeedback:(AKParameter *)feedback {
    _feedback = feedback;
    [self setUpConnections];
}

- (void)setOptionalFeedback:(AKParameter *)feedback {
    [self setFeedback:feedback];
}

- (void)setUpConnections
{
    self.state = @"connectable";
    self.dependencies = @[_input, _delayTime, _feedback];
}

- (NSString *)inlineStringForCSD
{
    NSMutableString *inlineCSDString = [[NSMutableString alloc] init];

    [inlineCSDString appendString:@"akdelay("];
    [inlineCSDString appendString:[self inputsString]];
    [inlineCSDString appendString:@")"];

    return inlineCSDString;
}

- (NSString *)stringForCSD
{
    NSMutableString *csdString = [[NSMutableString alloc] init];

    [csdString appendFormat:@"%@ akdelay ", self];
    [csdString appendString:[self inputsString]];
    return csdString;
}

- (NSString *)inputsString {
    NSMutableString *inputsString = [[NSMutableString alloc] init];

    if ([_input class] == [AKAudio class]) {
        [inputsString appendFormat:@"%@, ", _input];
    } else {
        [inputsString appendFormat:@"AKAudio(%@), ", _input];
    }

    if ([_feedback class] == [AKControl class]) {
        [inputsString appendFormat:@"%@, ", _feedback];
    } else {
        [inputsString appendFormat:@"AKControl(%@), ", _feedback];
    }

    [inputsString appendFormat:@"%@", _delayTime];
    return inputsString;
}

- (NSString *)udoString
{
    return @"\n"
    "opcode  akdelay, a, aki\n"
    "aIn, kFeedback, iTime xin\n"
    "aOut init 0\n"
    "aOut delay aIn + (aOut*kFeedback), iTime\n"
    "xout      aOut\n"
    "endop\n";
}

@end


text:
package com.alibaba.json.bvt.bug;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

import org.junit.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import junit.framework.TestCase;

public class CollectionEmptyMapTest extends TestCase {
    public void test_0() throws Exception {
        Map<String, Object> map = Collections.emptyMap();

        String text = JSON.toJSONString(map, SerializerFeature.WriteClassName);

        Assert.assertEquals("{\"@type\":\"java.util.Collections$EmptyMap\"}", text);

        Assert.assertSame(map, JSON.parse(text));
    }
}


text:
package com.infospace.sdk.cards.binders;

import android.view.*;

import com.infospace.sdk.Container;
import com.infospace.sdk.cards.*;
import com.infospace.sdk.models.*;

import java.util.List;

public class GroupCardBinder
	extends ViewBinder<ResultGroup> {

	private final ViewFactory viewFactory;
	private final CardBinderFactory binderFactory;

	public GroupCardBinder() {
		viewFactory = Container.resolve(ViewFactory.class);
		binderFactory = Container.resolve(CardBinderFactory.class);
	}

	@Override
	protected void onBind() {
		setupChildren(getModel().getChildren());
	}

	private void setupChildren(List<ResultNode> results) {
		ViewGroup container = findViewGroup(R.id.insp_card_results);

		if (container != null) {
			container.removeAllViews();

			for (ResultNode result : results) {
				// TODO: can we reuse existing child views?
				View view = viewFactory.getView(result, null, container);

				binderFactory.bind(result, view);

				container.addView(view);
			}
		}
	}
}


text:
<?php

namespace HWI\Bundle\OAuthBundle\Tests\OAuth\ResourceOwner;

use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\SensioConnectResourceOwner;

class SensioConnectResourceOwnerTest extends GenericOAuth2ResourceOwnerTest
{
    public function setUp()
    {
        parent::setUp();

        $this->userResponse = file_get_contents(__DIR__.'/../../Fixtures/sensioconnect_response.xml');
    }

    public function testGetUserInformation()
    {
        $class         = '\HWI\Bundle\OAuthBundle\OAuth\Response\SensioConnectUserResponse';
        $resourceOwner = $this->createResourceOwner($this->resourceOwnerName, array('user_response_class' => $class));

        $this->mockBuzz($this->userResponse);

        /**
         * @var $userResponse \HWI\Bundle\OAuthBundle\OAuth\Response\SensioConnectUserResponse
         */
        $userResponse = $resourceOwner->getUserInformation(array('access_token' => 'token'));

        $this->assertInstanceOf($class, $userResponse);
        $this->assertEquals('aa5e22b0-6189-4113-9c68-91d4a3c32b7c', $userResponse->getUsername());
        $this->assertEquals('bar', $userResponse->getNickname());
        $this->assertEquals('Fake Guy', $userResponse->getRealName());
        $this->assertEquals('fake@email.com', $userResponse->getEmail());
        $this->assertEquals('token', $userResponse->getAccessToken());
    }

    protected function setUpResourceOwner($name, $httpUtils, array $options)
    {
        return new SensioConnectResourceOwner($this->buzzClient, $httpUtils, $options, $name, $this->storage);
    }
}


text:
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>

<?php echo $title?>

	<?php if ($date_time) {
    ?>

<?php echo Core::make('helper/date')->formatDateTime($date_time, true)?>

	<?php
} ?>
	<?php if ($description) {
    ?>

<?php echo $description?>

	<?php
} ?>


text:
<?php

namespace Socloz\FeatureFlagBundle\ABTesting\Transaction;

/**
 * Interface for transaction management
 * @author jfb
 */
interface TransactionInterface
{

    /**
     * Starts a transaction
     *
     * @param string $feature
     */
    public function begin($feature);

    /**
     * Ends a successful transaction
     *
     * @param string $feature
     */
    public function success($feature);

    /**
     * Ends a failed transaction
     *
     * @param string $feature
     */
    public function failure($feature);

    /**
     * Returns the counts
     * @return array
     */
    public function getCounts();
}


text:
FactoryGirl.define do
  factory :shared_project do
    project_json "{}"
    compiled_components "{}"
  end
end


text:
package org.sleuthkit.autopsy.datamodel;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.Sheet;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.lookup.Lookups;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.directorytree.ExternalViewerAction;
import org.sleuthkit.datamodel.Report;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * Implements the Reports subtree of the Autopsy tree.
 */
public final class Reports implements AutopsyVisitableItem {

    private static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");

    @Override
    public <T> T accept(AutopsyItemVisitor<T> visitor) {
        // CreateAutopsyNodeVisitor.visit() constructs a ReportsListNode.
        return visitor.visit(this);
    }

    /**
     * The root node of the Reports subtree of the Autopsy tree.
     */
    public static final class ReportsListNode extends DisplayableItemNode {

        private static final long serialVersionUID = 1L;
        private static final String DISPLAY_NAME = NbBundle.getMessage(ReportsListNode.class, "ReportsListNode.displayName");
        private static final String ICON_PATH = "org/sleuthkit/autopsy/images/report_16.png"; //NON-NLS

        public ReportsListNode() {
            super(Children.create(new ReportNodeFactory(), true));
            setName(DISPLAY_NAME);
            setDisplayName(DISPLAY_NAME);
            this.setIconBaseWithExtension(ICON_PATH);
        }

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

        @Override
        public <T> T accept(DisplayableItemNodeVisitor<T> visitor) {
            // - GetPopupActionsDisplayableItemNodeVisitor.visit() returns null.
            // - GetPreferredActionsDisplayableItemNodeVisitor.visit() returns null.
            // - IsLeafItemVisitor.visit() returns false.
            // - ShowItemVisitor.visit() returns true.
            return visitor.visit(this);
        }

        @Override
        public String getItemType() {
            return getClass().getName();
        }
    }

    /**
     * The child node factory that creates ReportNode children for a
     * ReportsListNode.
     */
    private static final class ReportNodeFactory extends ChildFactory<Report> {

        ReportNodeFactory() {
            Case.addPropertyChangeListener((PropertyChangeEvent evt) -> {
                String eventType = evt.getPropertyName();
                if (eventType.equals(Case.Events.REPORT_ADDED.toString()) || eventType.equals(Case.Events.REPORT_DELETED.toString())) {
                    /**
                     * Checking for a current case is a stop gap measure until a
                     * different way of handling the closing of cases is worked
                     * out. Currently, remote events may be received for a case
                     * that is already closed.
                     */
                    try {
                        Case.getCurrentCase();
                        ReportNodeFactory.this.refresh(true);
                    } catch (IllegalStateException notUsed) {
                        /**
                         * Case is closed, do nothing.
                         */
                    }
                }
            });
        }

        @Override
        protected boolean createKeys(List<Report> keys) {
            try {
                keys.addAll(Case.getCurrentCase().getAllReports());
            } catch (TskCoreException ex) {
                Logger.getLogger(Reports.ReportNodeFactory.class.getName()).log(Level.SEVERE, "Failed to get reports", ex); //NON-NLS
            }
            return true;
        }

        @Override
        protected Node createNodeForKey(Report key) {
            return new ReportNode(key);
        }
    }

    /**
     * A leaf node in the Reports subtree of the Autopsy tree, wraps a Report
     * object.
     */
    public static final class ReportNode extends DisplayableItemNode {

        private static final long serialVersionUID = 1L;
        private static final String ICON_PATH = "org/sleuthkit/autopsy/images/report_16.png"; //NON-NLS
        private final Report report;

        ReportNode(Report report) {
            super(Children.LEAF, Lookups.fixed(report));
            this.report = report;
            super.setName(this.report.getSourceModuleName());
            super.setDisplayName(this.report.getSourceModuleName());
            this.setIconBaseWithExtension(ICON_PATH);
        }

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

        @Override
        public <T> T accept(DisplayableItemNodeVisitor<T> visitor) {
            // - GetPopupActionsDisplayableItemNodeVisitor.visit() calls getActions().
            // - GetPreferredActionsDisplayableItemNodeVisitor.visit() calls getPreferredAction().
            // - IsLeafItemVisitor.visit() returns true.
            // - ShowItemVisitor.visit() returns true.
            return visitor.visit(this);
        }

        @Override
        protected Sheet createSheet() {
            Sheet sheet = super.createSheet();
            Sheet.Set propertiesSet = sheet.get(Sheet.PROPERTIES);
            if (propertiesSet == null) {
                propertiesSet = Sheet.createPropertiesSet();
                sheet.put(propertiesSet);
            }
            propertiesSet.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "ReportNode.sourceModuleNameProperty.name"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.sourceModuleNameProperty.displayName"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.sourceModuleNameProperty.desc"),
                    this.report.getSourceModuleName()));
            propertiesSet.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "ReportNode.reportNameProperty.name"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.reportNameProperty.displayName"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.reportNameProperty.desc"),
                    this.report.getReportName()));
            propertiesSet.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "ReportNode.createdTimeProperty.name"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.createdTimeProperty.displayName"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.createdTimeProperty.desc"),
                    dateFormatter.format(new java.util.Date(this.report.getCreatedTime() * 1000))));
            propertiesSet.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "ReportNode.pathProperty.name"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.pathProperty.displayName"),
                    NbBundle.getMessage(this.getClass(), "ReportNode.pathProperty.desc"),
                    this.report.getPath()));
            return sheet;
        }

        @Override
        public Action[] getActions(boolean popup) {
            List<Action> actions = new ArrayList<>();
            actions.addAll(Arrays.asList(super.getActions(true)));
            actions.add(new OpenReportAction());
            actions.add(DeleteReportAction.getInstance());
            return actions.toArray(new Action[actions.size()]);
        }

        @Override
        public AbstractAction getPreferredAction() {
            return new OpenReportAction();
        }

        @Override
        public String getItemType() {
            return getClass().getName();
        }

        private static class DeleteReportAction extends AbstractAction {

            private static final long serialVersionUID = 1L;
            private static DeleteReportAction instance;

            // This class is a singleton to support multi-selection of nodes,
            // since org.openide.nodes.NodeOp.findActions(Node[] nodes) will
            // only pick up an Action if every node in the array returns a
            // reference to the same action object from Node.getActions(boolean).
            private static DeleteReportAction getInstance() {
                if (instance == null) {
                    instance = new DeleteReportAction();
                }
                if (Utilities.actionsGlobalContext().lookupAll(Report.class).size() == 1) {
                    instance.putValue(Action.NAME, NbBundle.getMessage(Reports.class, "DeleteReportAction.actionDisplayName.singleReport"));
                } else {
                    instance.putValue(Action.NAME, NbBundle.getMessage(Reports.class, "DeleteReportAction.actionDisplayName.multipleReports"));
                }
                return instance;
            }

            /**
             * Do not instantiate directly. Use
             * DeleteReportAction.getInstance(), instead.
             */
            private DeleteReportAction() {
            }

            @NbBundle.Messages({
                "DeleteReportAction.showConfirmDialog.single.explanation=The report will remain on disk.",
                "DeleteReportAction.showConfirmDialog.multiple.explanation=The reports will remain on disk.",
                "DeleteReportAction.showConfirmDialog.errorMsg=An error occurred while deleting the reports."})
            @Override
            public void actionPerformed(ActionEvent e) {
                Collection<? extends Report> selectedReportsCollection = Utilities.actionsGlobalContext().lookupAll(Report.class);
                String message = selectedReportsCollection.size() > 1
                        ? NbBundle.getMessage(Reports.class, "DeleteReportAction.actionPerformed.showConfirmDialog.multiple.msg", selectedReportsCollection.size())
                        : NbBundle.getMessage(Reports.class, "DeleteReportAction.actionPerformed.showConfirmDialog.single.msg");
                String explanation = selectedReportsCollection.size() > 1
                        ? Bundle.DeleteReportAction_showConfirmDialog_multiple_explanation()
                        : Bundle.DeleteReportAction_showConfirmDialog_single_explanation();
                Object[] jOptionPaneContent = {message, explanation};
                if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, jOptionPaneContent,
                        NbBundle.getMessage(Reports.class, "DeleteReportAction.actionPerformed.showConfirmDialog.title"),
                        JOptionPane.YES_NO_OPTION)) {
                    try {
                        Case.getCurrentCase().deleteReports(selectedReportsCollection);
                    } catch (TskCoreException | IllegalStateException ex) {
                        Logger.getLogger(DeleteReportAction.class.getName()).log(Level.SEVERE, "Error deleting reports", ex); // NON-NLS
                        MessageNotifyUtil.Message.error(Bundle.DeleteReportAction_showConfirmDialog_errorMsg());
                    }
                }
            }
        }

        private final class OpenReportAction extends AbstractAction {

            private static final long serialVersionUID = 1L;

            private OpenReportAction() {
                super(NbBundle.getMessage(OpenReportAction.class, "OpenReportAction.actionDisplayName"));
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                String reportPath = ReportNode.this.report.getPath();
                String extension = "";
                int extPosition = reportPath.lastIndexOf('.');

                if (extPosition != -1) {
                    extension = reportPath.substring(extPosition, reportPath.length()).toLowerCase();
                }

                File file = new File(reportPath);
                ExternalViewerAction.openFile("", extension, file);
            }
        }
    }
}


text:
package medium;

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

public class Binary_Tree_Preorder_Traversal {

	public class TreeNode {
	    int val;
	    TreeNode left;
	    TreeNode right;
	    TreeNode(int x) { val = x; }
	}

	class Solution {
		List<Integer> result = new ArrayList<>();

		public void preOrder(TreeNode root) {
			if (root == null) {
				return;
			}
			result.add(root.val);
			preOrder(root.left);
			preOrder(root.right);
		}

	    public List<Integer> preorderTraversal(TreeNode root) {
	    	preOrder(root);
			return result;
	    }
	}

}


text:
//
// This code was auto-generated by AFNOR StoredProcedureSystem, version 1.0
//

using Bivi.Data.Context;
using Bivi.Domaine;
using Bivi.Business.Depots;
using System.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

namespace Bivi.Data.Depots
{
    public partial class DepotVariante : Depot<Variante>, IDepotVariante
    {
        public IEnumerable<VarianteResult> GetVarianteToIndex()
        {
            var Parameters = new List<SqlParameter>();

            return DbContext.ExecuteStoredProcedure<VarianteResult>("sp_GetVarianteToIndex", Parameters);
        }
    }
}


text:
package easy;

import java.util.HashSet;
import java.util.Set;

/*
 * Problem: AlienAndPassword
 * Used In: SRM 605
 * Division: 2
 * Level:1
 * Points: 250
 * Description: https://community.topcoder.com/stat?c=problem_statement&pm=12950
 */
public class AlienAndPassword {

    public int getNumber(String S) {
        Set<String> passwords = new HashSet<>();

        for (int i = 0; i < S.length(); i++) {
            String password = S.substring(0, i) + S.substring(i + 1);
            passwords.add(password);
        }

        return passwords.size();
    }
}


text:
using GSDRequirementsCSharp.Domain.Commands;
using GSDRequirementsCSharp.Infrastructure.Converter;
using System.Collections.Generic;

namespace GSDRequirementsCSharp.Domain.Converter
{
    class RequirementToNewVersionCommandConverter : IConverter<Requirement, CreateRequirementVersionCommand>
    {
        public CreateRequirementVersionCommand Convert(Requirement input)
        {
            var result = new CreateRequirementVersionCommand();
            result.Difficulty = input.Difficulty;
            result.Id = input.Id;

            var contents = new List<RequirementContentItem>();

            foreach(var content in input.RequirementContents)
            {
                contents.Add(new RequirementContentItem
                {
                    Action = content.Action,
                    Condition = content.Condition,
                    Locale = content.Locale,
                    Subject = content.Subject
                });
            }

            result.Items = contents;
            result.PackageId = input.SpecificationItem.PackageId;
            result.Rank = input.Rank;
            result.RequirementType = input.Type;

            return result;
        }
    }
}


text:
<resources>
    <string name="app_name">QMBForm</string>
    <string name="title_no_entries">Keine Einträge</string>
    <string name="msg_no_entries">Zur Zeit liegen keine Einträge vor</string>
    <string name="msg_check_form">Bitte überprüfen Sie Ihre Eingaben</string>
    <string name="msg_x_is_required">ist ein erforderliches Feld</string>
</resources>


text:
module Mongo
  module CRUD
    class Verifier
      include RSpec::Matchers

      def initialize(test_instance)
        @test_instance = test_instance
      end

      attr_reader :test_instance

      # Compare the existing collection data and the expected collection data.
      #
      # Uses RSpec matchers and raises expectation failures if there is a
      # mismatch.
      def verify_collection_data(actual_collection_data)
        expected_collection_data = test_instance.outcome_collection_data
        if expected_collection_data.nil?
          expect(actual_collection_data).to be nil
        elsif expected_collection_data.empty?
          expect(actual_collection_data).to be_empty
        else
          expect(actual_collection_data).not_to be nil
          expected_collection_data.each do |doc|
            expect(actual_collection_data).to include(doc)
          end
          actual_collection_data.each do |doc|
            expect(expected_collection_data).to include(doc)
          end
        end
      end

      # Compare the actual operation result to the expected operation result.
      #
      # Uses RSpec matchers and raises expectation failures if there is a
      # mismatch.
      def verify_operation_result(actual)
        expected = test_instance.outcome['result']
        if expected.is_a?(Array)
          if expected.empty?
            expect(actual).to be_empty
          else
            expected.each_with_index do |expected_elt, i|
              verify_result(expected_elt, actual[i])
            end
          end
        else
          verify_result(expected, actual)
        end
      end

      private

      def verify_result(expected, actual)
        case expected
        when nil
          expect(actual).to be nil
        when Hash
          actual.each do |k, v|
            ok = expected[k] == v || handle_upserted_id(k, expected[k], v) || handle_inserted_ids(k, expected[k], v)
            expect(ok).to be true
          end
        when Integer
          expect(actual).to eq(expected)
        end
      end

      def handle_upserted_id(field, expected_id, actual_id)
        return true if expected_id.nil?
        if field == 'upsertedId'
          if expected_id.is_a?(Integer)
            actual_id.is_a?(BSON::ObjectId) || actual_id.nil?
          end
        end
      end

      def handle_inserted_ids(field, expected, actual)
        if field == 'insertedIds'
          expected.values == actual
        end
      end
    end
  end
end


text:
using System;
using System.Drawing;

namespace Twipe.Core.Internals
{
    public sealed class LuminosityConverter : BlackWhiteConverterBase
    {
        private readonly float RedCoefficient = 0.21F;
        private readonly float GreenCoefficient = 0.72F;
        private readonly float BlueCoefficient = 0.07F;

        public LuminosityConverter(Bitmap inputImage) : base(inputImage)
        {
            // do nothing!
        }

        protected override int GetAverageValue(Color pixel)
        {
            return (int)(pixel.R * RedCoefficient + pixel.G * GreenCoefficient + pixel.B * BlueCoefficient) / 3;
        }

        protected override int GetAverageValue(int red, int green, int blue)
        {
            return (int)(red * RedCoefficient + green * GreenCoefficient + blue * BlueCoefficient) / 3;
        }
    }
}


text:
//====================================================================
// simulation.cpp
// Programming Assignment 1 : Sensor Simulation
// Author: Samuel Sikes
// Date: June 2016
// This program is entirely my own work
//====================================================================
#include "simulation.h"

//---------------------------------
//---------------------------------
//--------PRIVATE METHODS----------
//---------------------------------
//---------------------------------

//---------------------------------
//function: simulationDescription()
//Displays a description of the
//program.
//---------------------------------
void simulation::simulationDescription(){

    for (int i = 0; i < 60; i++)
        std::cout << "=";

    std::cout <<  "\n" << "|" << std::setw(52) <<
    "ENVIRONMENTAL SENSORS SIMULATION DEMONSTRATION" <<
    std::setw(7) << "|" << "\n" <<
    "|" << std::setw(46) <<
    "CS 307 -- Programming Assignment 1" <<
    std::setw(13) << "|" << "\n";

    for (int i = 0; i < 60; i++)
        std::cout << "=";
    std::cout << "\n\n";
};

//---------------------------------
//function: getFile()
//Prompts user to enter the name
//of the file that they want parsed.
//---------------------------------
void simulation::getFile(){

    char fileName[64];
    std::cout << "Please enter the name of the simulation data file then press Enter: ";
    std::cin >> fileName;
    dataParserPtr = new EnviroSimDataParser(fileName);
};

//---------------------------------
//function: buildDevices()
//Gets the number of sensor and
//display devices to create and
//passes those counts to the create
//functions for both displays and
//sensors. Then, deletes instance of
//data parser.
//---------------------------------
void simulation::buildDevices(){

    int sensorCount = dataParserPtr->getSensorCount();
    int displayCount = dataParserPtr->getDisplayCount();
    this->createDisplays(displayCount);
    this->createSensors(sensorCount);

    delete dataParserPtr; dataParserPtr = NULL;
};

//---------------------------------
//function: createDisplays()
//Creates the appropriate number of
//displays and passes each display
//to display's getDisplay() method
//---------------------------------
void simulation::createDisplays(int& count){

    for(int i=0; i < count; i++){
        displayNode* displayNodePtr = new displayNode;
        if(!dataParserPtr->getDisplayData(displayNodePtr->type,displayNodePtr->IDs,&displayNodePtr->IDCount))
            cout << "\n" << "Parsing for Display " << i << " failed" << "\n";
        displayPtr->getDisplay(displayNodePtr);
    }
};

//---------------------------------
//function: createSensors()
//Creates the appropriate number of
//sensors and passes each sensor
//to sensor's getSensor() method
//---------------------------------
void simulation::createSensors(int& count){

    for(int i=0; i < count; i++){
        sensorNode* sensorNodePtr = new sensorNode;
        if(!dataParserPtr->getSensorData(sensorNodePtr->type,sensorNodePtr->material,&sensorNodePtr->ID,
                                         sensorNodePtr->units,&sensorNodePtr->minVal,&sensorNodePtr->maxVal))
            cout << "\n" << "Parsing for Sensor " << i << " failed" << "\n";
        sensorNodePtr->sensorData = 0;
        sensorPtr->getSensor(sensorNodePtr);
    }
};

//---------------------------------
//function: attachDevices()
//Attaches all sensors and display
//devices to sensor mount. Then,
//calls sensor mount funciton to
//link all sensors to the appropriate
//display devices.
//---------------------------------
void simulation::attachDevices(){

    sensorMountPtr->attachDisplays(displayPtr->relayDisplayData());
    sensorMountPtr->attachSensors(sensorPtr->relaySensorData());
    if(!sensorMountPtr->linkSensorsToDisplays())
        std::cout << "\n" << "Linking Sensors To Displays FAILED" << "\n";
};

//---------------------------------
//---------------------------------
//--------PUBLIC METHODS-----------
//---------------------------------
//---------------------------------

//---------------------------------
//function: simulation()
//dynamically creates instances of
//sensor, display, and sensor mount
//---------------------------------
simulation::simulation(){

    sensorPtr = new sensor;
    displayPtr = new display;
    sensorMountPtr = new sensorMount;
};

//---------------------------------
//function: ~simulation()
//deallocates memory for: display,
//sensor, and sensor mount
//sets all private pointers to NULL
//---------------------------------
simulation::~simulation(){

    delete sensorPtr; sensorPtr = NULL;
    delete displayPtr; displayPtr = NULL;
    delete sensorMountPtr; sensorMountPtr = NULL;
};

//---------------------------------
//function: runSimulation()
//calls appropriate simulation
//methods. Then, generates sensor
//data and displays it every 5
//seconds
//---------------------------------
void simulation::runSimulation() {

    this->simulationDescription();
    this->getFile();
    this->buildDevices();
    this->attachDevices();
    sensorMountPtr->displayConnectedDevices();
    /*- - - - - - - - - - - - -*/
    std::cout << "\n\n\n" << "Beginning simulation run..." << "\n\n";
    for (int i = 0; i < 20; i++)
        std::cout << "=";
    std::cout << " Running simulation ";
    for (int i = 0; i < 20; i++)
        std::cout << "=";
    std::cout << "\n\n" << "Press Ctrl-c to terminate the simulation" << "\n\n";
    /*- - - - - - - - - - - - -*/
    while(true){
        usleep(5000000);
        /*- - - - - - - - - - - - -*/
        for (int i = 0; i < 60; i++)
            std::cout << "=";
        std::cout << "\n\n";
        /*- - - - - - - - - - - - -*/
        sensorPtr->updateSensors();
        displayPtr->displayData();
        /*- - - - - - - - - - - - -*/
        std::cout << "\n\n\n";
        /*- - - - - - - - - - - - -*/
    }
};


text:
#ifndef RTAUDIOWRAPPER_H
#define	RTAUDIOWRAPPER_H

#include "AudioInterface.h"
#include "RtAudio.h"

/*!
 * Implementation of concrete AudioInterface (Wrapper class of RtAudio)
 */
class RtAudioWrapper : public AudioInterface
{
public:
    RtAudioWrapper();
    ~RtAudioWrapper();

    /* Callbacks */
    auto callback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) -> int;
    static auto callbackHelper(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *rtAudioWrapperObject) -> int;

protected:
    RtAudio rtaudio;
    RtAudio::StreamParameters inputConfig, outputConfig;
	unsigned int bufferSizeInNumberOfSamples, inputBufferSizeInBytes, outputBufferSizeInBytes;

	auto getRtAudioFormat(const AudioConfiguration &audioConfig) -> RtAudioFormat;
	auto setActualBufferSizes() -> void;
	auto initializeRtAudioStreamParameters() -> void;

	auto vStartRecordingMode() -> void;
	auto vStartPlaybackMode() -> void;
	auto vStartDuplexMode() -> void;
	auto vSetConfiguration(AudioConfiguration audioConfiguration) -> void;
	auto vSuspend() -> void;
	auto vResume() -> void;
	auto vStop() -> void;
	auto vReset() -> void;
	auto vSetDefaultAudioConfig() -> void;
	auto vPrepareForExecution() -> bool;
	auto vGetBufferSize() -> unsigned int;
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_topics"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="edu.illinois.g31.worldview.Topics">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:theme="?attr/actionBarTheme"
        android:minHeight="?attr/actionBarSize"
        android:id="@+id/toolbar" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar"
        android:orientation="vertical">

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"/>

        <Button
            android:text="@string/goto_sources_list_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="@dimen/menu_button_min_height"
            android:id="@+id/button"
            android:layout_weight="1"/>

    </LinearLayout>

</RelativeLayout>


text:
struct EntityActivatedEvent
{
    EntityActivatedEvent(const Entity& entity)
        :entity(entity) {}

    Entity entity;
};


text:
package benchmark

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

var (
	// GlobalCounters is a singleton set of performance counters.
	GlobalCounters = NewCounters()

	counterFactories = map[string]func() Counter{}
)

func init() {
	register := func(f func() Counter) {
		counterFactories[f().TypeName()] = f
	}
	register(newDurationCounter)
	register(newIntegerCounter)
	register(newStringHolder)
}

// Counters represents a collection of named performance counters.
//
// Individual counters are created on retrieve if they do not exist.
// Counters of different types with the same name are disallowed.
// Users are encouraged to hang on to retrieved counters rather than
// calling these methods repeatedly, for performance reasons.
type Counters struct {
	counters map[string]Counter
	mutex    sync.Mutex
}

type Counter interface {
	// Get retrieves the current value of the counter.
	Get() interface{}

	// Reset resets the counter to its initial value.
	Reset()

	// TypeName retrieves a string that uniquely identifies the
	// type of counter.
	TypeName() string
}

// NewCounters allocates a new set of counters.
func NewCounters() *Counters {
	return &Counters{counters: make(map[string]Counter)}
}

func (m *Counters) getOrAllocate(name string, f func() Counter) Counter {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	counter, found := m.counters[name]
	if !found {
		counter = f()
		m.counters[name] = counter
	}
	return counter
}

// Integer returns the IntegerCounter with the given name,
// instantiating a new one if necessary.
func (m *Counters) Integer(name string) *IntegerCounter {
	return m.getOrAllocate(name, newIntegerCounter).(*IntegerCounter)
}

// Duration returns the DurationCounter with the given name,
// instantiating a new one if necessary.
func (m *Counters) Duration(name string) *DurationCounter {
	return m.getOrAllocate(name, newDurationCounter).(*DurationCounter)
}

// String returns the StringHolder with the given name,
// instantiating a new one if necessary.
func (m *Counters) String(name string) *StringHolder {
	return m.getOrAllocate(name, newStringHolder).(*StringHolder)
}

// Lazy returns the LazyCounter with the given name,
// instantiating a new one if necessary.
func (m *Counters) Lazy(name string) *LazyCounter {
	return m.getOrAllocate(name, func() Counter { return &LazyCounter{} }).(*LazyCounter)
}

// LazyWithFunction returns the LazyCounter with the given name,
// atomically instantiating a new one with the given
// function if necessary.
func (m *Counters) LazyWithFunction(name string, f func() Counter) *LazyCounter {
	return m.getOrAllocate(name, func() Counter {
		l := &LazyCounter{}
		l.SetFunction(f)
		return l
	}).(*LazyCounter)
}

// LazyWithCaching returns the LazyCounter with the given name,
// atomically instantiating a new one with the given
// caching function if necessary.
func (m *Counters) LazyWithCaching(name string, f func() Counter) *LazyCounter {
	return m.getOrAllocate(name, func() Counter {
		l := &LazyCounter{}
		l.SetCaching(f)
		return l
	}).(*LazyCounter)
}

// MarshalJSON implements json.Marshaler.
func (m *Counters) MarshalJSON() ([]byte, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	res := map[string]interface{}{}
	for name, counter := range m.counters {
		res[name] = struct {
			Type  string
			Value Counter
		}{
			Type:  counter.TypeName(),
			Value: counter,
		}
	}
	return json.Marshal(res)
}

// AllCounters retrieves a copy of the counter map,
// keyed by name.
func (m *Counters) AllCounters() map[string]Counter {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	res := make(map[string]Counter)
	for name, counter := range m.counters {
		res[name] = counter
	}
	return res
}

// UnmarshalJSON implements json.Unmarshaler.
func (m *Counters) UnmarshalJSON(data []byte) error {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	rawCounters := map[string]struct {
		Type  string
		Value json.RawMessage
	}{}
	if err := json.Unmarshal(data, &rawCounters); err != nil {
		return err
	}

	m.counters = make(map[string]Counter)
	for name, c := range rawCounters {
		factory := counterFactories[c.Type]
		if factory != nil {
			cnt := factory()
			if err := json.Unmarshal(c.Value, cnt); err != nil {
				return err
			}
			m.counters[name] = cnt
		}
	}
	return nil
}

// IntegerCounter is a Counter that holds an int64 value.
type IntegerCounter int64

func newIntegerCounter() Counter {
	return IntegerCounterOf(0)
}

// IntegerCounterOf creates a new IntegerCounter with the given duration.
func IntegerCounterOf(i int64) *IntegerCounter {
	c := new(IntegerCounter)
	*c = IntegerCounter(i)
	return c
}

// Reset implements Counter.
func (c *IntegerCounter) Reset() {
	atomic.StoreInt64((*int64)(c), 0)
}

// Get implements Counter.
func (c *IntegerCounter) Get() interface{} {
	return atomic.LoadInt64((*int64)(c))
}

// TypeName implements Counter.
func (c *IntegerCounter) TypeName() string {
	return "int"
}

// AddInt64 adds the given value to the value of this counter.
func (c *IntegerCounter) AddInt64(i int64) {
	atomic.AddInt64((*int64)(c), i)
}

// AddInt64 adds 1 to the value of this counter.
func (c *IntegerCounter) Increment() {
	atomic.AddInt64((*int64)(c), 1)
}

// GetInt64 retrieves the value of this counter as an int64.
func (c *IntegerCounter) GetInt64() int64 {
	return atomic.LoadInt64((*int64)(c))
}

func (c *IntegerCounter) SetInt64(val int64) {
	atomic.StoreInt64((*int64)(c), val)
}

// MarshalJSON implements json.Marshaller.
func (c *IntegerCounter) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("%d", c.GetInt64())), nil
}

// UnmarshalJSON implements json.Unmarshaler.
func (c *IntegerCounter) UnmarshalJSON(data []byte) error {
	var val int64
	if err := json.Unmarshal(data, &val); err != nil {
		return err
	}
	c.SetInt64(val)
	return nil
}

// DurationCounter is a Counter that holds an int64, exposed as a time.Duration.
type DurationCounter int64

func newDurationCounter() Counter {
	return DurationCounterOf(0)
}

// DurationCounterOf creates a new DurationCounter with the given duration.
func DurationCounterOf(t time.Duration) *DurationCounter {
	d := new(DurationCounter)
	*d = DurationCounter(t)
	return d
}

// AddDuration adds the given duration to the value of this counter.
func (c *DurationCounter) AddDuration(t time.Duration) {
	atomic.AddInt64((*int64)(c), int64(t))
}

// GetDuration retrieves the value of this counter as a time.Duration.
func (c *DurationCounter) GetDuration() time.Duration {
	return time.Duration(atomic.LoadInt64((*int64)(c)))
}

// Reset implements Counter.
func (c *DurationCounter) Reset() {
	atomic.StoreInt64((*int64)(c), 0)
}

// Get implements Counter.
func (c *DurationCounter) Get() interface{} {
	return c.GetDuration()
}

// TypeName implements Counter.
func (c *DurationCounter) TypeName() string {
	return "duration"
}

func (c *DurationCounter) SetDuration(t time.Duration) {
	atomic.StoreInt64((*int64)(c), int64(t))
}

// Start returns the current time. It's meant to be used with Stop()
// as a way to time blocks of code and add their durations to the counter.
func (c *DurationCounter) Start() time.Time {
	return time.Now()
}

// Stop adds to the value of this counter the Duration elapsed
// since the time.Time received as argument.
func (c *DurationCounter) Stop(startTime time.Time) {
	c.AddDuration(time.Since(startTime))
}

// MarshalJSON implements json.Marshaler.
func (c *DurationCounter) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%v"`, c.GetDuration())), nil
}

// UnmarshalJSON implements json.Unmarshaler.
func (c *DurationCounter) UnmarshalJSON(data []byte) error {
	var durationString string
	if err := json.Unmarshal(data, &durationString); err != nil {
		return err
	}
	dur, err := time.ParseDuration(durationString)
	if err == nil {
		c.SetDuration(dur)
	}
	return err
}

// Holder is a Counter that holds a String.
type StringHolder struct {
	val atomic.Value
}

func newStringHolder() Counter {
	return StringHolderOf("")
}

// StringHolderOf creates a new StringHolder with the given value.
func StringHolderOf(s string) *StringHolder {
	sh := new(StringHolder)
	sh.SetString(s)
	return sh
}

// Reset implements Counter.
func (c *StringHolder) Reset() {
	c.SetString("")
}

// Get implements Counter.
func (c *StringHolder) Get() interface{} {
	return c.val.Load()
}

// GetString returns the string.
func (c *StringHolder) GetString() string {
	return c.Get().(string)
}

func (c *StringHolder) TypeName() string {
	return "string"
}

// SetString sets the string in the holder.
func (c *StringHolder) SetString(s string) {
	c.val.Store(s)
}

// MarshalJSON implements json.Marshaler.
func (c *StringHolder) MarshalJSON() ([]byte, error) {
	return json.Marshal(c.GetString())
}

func (c *StringHolder) UnmarshalJSON(data []byte) error {
	var val string
	if err := json.Unmarshal(data, &val); err != nil {
		return err
	}
	c.SetString(val)
	return nil
}

// LazyCounter is a Counter that delegates Counter method calls to
// a Counter retrieved by calling a function.
type LazyCounter struct {
	fun atomic.Value
}

// Counter retrieves the Underlying counter.
func (c *LazyCounter) Counter() Counter {
	return c.fun.Load().(func() Counter)()
}

// SetFunction sets the function to retrieve the underlying counter.
// This function will be called every time one of the Counter methods
// is called.
func (c *LazyCounter) SetFunction(f func() Counter) {
	c.fun.Store(f)
}

// SetCaching sets a function to be called to retrieve the underlying
// counter. This function will be called once, the first time one of
// the Counter methods is called.
func (c *LazyCounter) SetCaching(f func() Counter) {
	var counter Counter
	c.SetFunction(func() Counter {
		if counter == nil {
			counter = f()
		}
		return counter
	})
}

// Reset implements Counter.
func (c *LazyCounter) Reset() {
	c.Counter().Reset()
}

// Get implements Counter.
func (c *LazyCounter) Get() interface{} {
	return c.Counter().Get()
}

// TypeName implements Counter.
func (c *LazyCounter) TypeName() string {
	return c.Counter().TypeName()
}

// MarshalJSON implements json.Marshaler.
func (c *LazyCounter) MarshalJSON() ([]byte, error) {
	return json.Marshal(c.Counter())
}