text:
package bio.terra.service.dataset;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import bio.terra.common.auth.AuthService;
import bio.terra.common.category.Integration;
import bio.terra.common.configuration.TestConfiguration;
import bio.terra.common.fixtures.JsonLoader;
import bio.terra.integration.BigQueryFixtures;
import bio.terra.integration.DataRepoFixtures;
import bio.terra.integration.TestJobWatcher;
import bio.terra.integration.UsersBase;
import bio.terra.model.DataDeletionRequest;
import bio.terra.model.DataDeletionTableModel;
import bio.terra.model.DatasetModel;
import bio.terra.model.DatasetSummaryModel;
import bio.terra.model.IngestRequestModel;
import bio.terra.model.IngestResponseModel;
import bio.terra.model.SnapshotModel;
import bio.terra.model.SnapshotRequestModel;
import bio.terra.model.SnapshotSummaryModel;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.TableResult;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

// TODO move me to integration dir
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"google", "integrationtest"})
@AutoConfigureMockMvc
@Category(Integration.class)
public class DatasetSoftDeletesTest extends UsersBase {

  @Autowired private JsonLoader jsonLoader;
  @Autowired private DataRepoFixtures dataRepoFixtures;
  @Autowired private AuthService authService;
  @Autowired private TestConfiguration testConfiguration;
  @Rule @Autowired public TestJobWatcher testWatcher;

  private String stewardToken;
  private UUID datasetId;
  private UUID profileId;
  private List<UUID> snapshotIds;

  @Before
  public void setup() throws Exception {
    super.setup();
    stewardToken = authService.getDirectAccessAuthToken(steward().getEmail());
    dataRepoFixtures.resetConfig(steward());
    profileId = dataRepoFixtures.createBillingProfile(steward()).getId();
    datasetId = null;
    snapshotIds = new LinkedList<>();
  }

  @After
  public void teardown() throws Exception {
    dataRepoFixtures.resetConfig(steward());
    for (UUID snapshotId : snapshotIds) {
      dataRepoFixtures.deleteSnapshotLog(steward(), snapshotId);
    }

    if (datasetId != null) {
      dataRepoFixtures.deleteDatasetLog(steward(), datasetId);
    }

    if (profileId != null) {
      dataRepoFixtures.deleteProfileLog(steward(), profileId);
    }
  }

  @Test
  public void testSoftDeleteHappyPath() throws Exception {
    datasetId = ingestedDataset();

    // get row ids
    DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId);
    BigQuery bigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), stewardToken);
    List<String> participantRowIds =
        DatasetIntegrationTest.getRowIds(bigQuery, dataset, "participant", 3L);
    List<String> sampleRowIds = DatasetIntegrationTest.getRowIds(bigQuery, dataset, "sample", 2L);

    // write them to GCS
    String participantPath =
        DatasetIntegrationTest.writeListToScratch(
            testConfiguration.getIngestbucket(), "softDel", participantRowIds);
    String samplePath =
        DatasetIntegrationTest.writeListToScratch(
            testConfiguration.getIngestbucket(), "softDel", sampleRowIds);

    // build the deletion request with pointers to the two files with row ids to soft delete
    List<DataDeletionTableModel> dataDeletionTableModels =
        Arrays.asList(
            DatasetIntegrationTest.deletionTableFile("participant", participantPath),
            DatasetIntegrationTest.deletionTableFile("sample", samplePath));
    DataDeletionRequest request =
        DatasetIntegrationTest.dataDeletionRequest().tables(dataDeletionTableModels);

    // send off the soft delete request
    dataRepoFixtures.deleteData(steward(), datasetId, request);

    // make sure the new counts make sense
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "participant", 2L);
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "sample", 5L);
  }

  @Test
  public void testSoftDeleteJsonArrayHappyPath() throws Exception {
    datasetId = ingestedDataset();

    // get row ids
    DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId);
    BigQuery bigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), stewardToken);
    List<UUID> participantRowIds =
        DatasetIntegrationTest.getRowIds(bigQuery, dataset, "participant", 3L).stream()
            .map(UUID::fromString)
            .collect(Collectors.toList());
    List<UUID> sampleRowIds =
        DatasetIntegrationTest.getRowIds(bigQuery, dataset, "sample", 2L).stream()
            .map(UUID::fromString)
            .collect(Collectors.toList());

    // build the deletion request with pointers to the two files with row ids to soft delete
    List<DataDeletionTableModel> dataDeletionTableModels =
        Arrays.asList(
            DatasetIntegrationTest.deletionTableJson("participant", participantRowIds),
            DatasetIntegrationTest.deletionTableJson("sample", sampleRowIds));
    DataDeletionRequest request =
        DatasetIntegrationTest.dataDeletionRequest()
            .specType(DataDeletionRequest.SpecTypeEnum.JSONARRAY)
            .tables(dataDeletionTableModels);

    // send off the soft delete request
    dataRepoFixtures.deleteData(steward(), datasetId, request);

    // make sure the new counts make sense
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "participant", 2L);
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "sample", 5L);
  }

  @Test
  public void wildcardSoftDelete() throws Exception {
    datasetId = ingestedDataset();
    String pathPrefix = "softDelWildcard" + UUID.randomUUID();

    // get 5 row ids, we'll write them out to 5 separate files
    DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId);
    BigQuery bigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), stewardToken);
    List<String> sampleRowIds = DatasetIntegrationTest.getRowIds(bigQuery, dataset, "sample", 5L);
    for (String rowId : sampleRowIds) {
      DatasetIntegrationTest.writeListToScratch(
          testConfiguration.getIngestbucket(), pathPrefix, Collections.singletonList(rowId));
    }

    // make a wildcard path 'gs://ingestbucket/softDelWildcard/*'
    String wildcardPath =
        String.format("gs://%s/scratch/%s/*", testConfiguration.getIngestbucket(), pathPrefix);

    // build a request and send it off
    DataDeletionRequest request =
        DatasetIntegrationTest.dataDeletionRequest()
            .tables(
                Collections.singletonList(
                    DatasetIntegrationTest.deletionTableFile("sample", wildcardPath)));
    dataRepoFixtures.deleteData(steward(), datasetId, request);

    // there should be (7 - 5) = 2 rows "visible" in the sample table
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "sample", 2L);
  }

  @Test
  public void testSoftDeleteNotInFullView() throws Exception {
    datasetId = ingestedDataset();

    // get row ids
    DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId);
    BigQuery bigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), stewardToken);
    List<String> participantRowIds =
        DatasetIntegrationTest.getRowIds(bigQuery, dataset, "participant", 3L);
    List<String> sampleRowIds = DatasetIntegrationTest.getRowIds(bigQuery, dataset, "sample", 2L);

    // swap in these row ids in the request
    SnapshotRequestModel requestModelAll =
        jsonLoader.loadObject("ingest-test-snapshot-fullviews.json", SnapshotRequestModel.class);
    requestModelAll.getContents().get(0).datasetName(dataset.getName());

    SnapshotSummaryModel snapshotSummaryAll =
        dataRepoFixtures.createSnapshotWithRequest(
            steward(), dataset.getName(), profileId, requestModelAll);
    snapshotIds.add(snapshotSummaryAll.getId());
    SnapshotModel snapshotAll =
        dataRepoFixtures.getSnapshot(steward(), snapshotSummaryAll.getId(), null);
    // The steward is the custodian in this case, so is a reader in big query.
    BigQuery bigQueryAll = BigQueryFixtures.getBigQuery(snapshotAll.getDataProject(), stewardToken);

    assertSnapshotTableCount(bigQueryAll, snapshotAll, "participant", 5L);
    assertSnapshotTableCount(bigQueryAll, snapshotAll, "sample", 7L);

    // write them to GCS
    String participantPath =
        DatasetIntegrationTest.writeListToScratch(
            testConfiguration.getIngestbucket(), "softDel", participantRowIds);
    String samplePath =
        DatasetIntegrationTest.writeListToScratch(
            testConfiguration.getIngestbucket(), "softDel", sampleRowIds);

    // build the deletion request with pointers to the two files with row ids to soft delete
    List<DataDeletionTableModel> dataDeletionTableModels =
        Arrays.asList(
            DatasetIntegrationTest.deletionTableFile("participant", participantPath),
            DatasetIntegrationTest.deletionTableFile("sample", samplePath));
    DataDeletionRequest request =
        DatasetIntegrationTest.dataDeletionRequest().tables(dataDeletionTableModels);

    // send off the soft delete request
    dataRepoFixtures.deleteData(steward(), datasetId, request);

    // make sure the new counts make sense
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "participant", 2L);
    DatasetIntegrationTest.assertTableCount(bigQuery, dataset, "sample", 5L);

    // make full views snapshot
    SnapshotRequestModel requestModelLess =
        jsonLoader.loadObject("ingest-test-snapshot-fullviews.json", SnapshotRequestModel.class);
    requestModelLess.getContents().get(0).datasetName(dataset.getName());

    SnapshotSummaryModel snapshotSummaryLess =
        dataRepoFixtures.createSnapshotWithRequest(
            steward(), dataset.getName(), profileId, requestModelLess);
    snapshotIds.add(snapshotSummaryLess.getId());

    SnapshotModel snapshotLess =
        dataRepoFixtures.getSnapshot(steward(), snapshotSummaryLess.getId(), null);
    BigQuery bigQueryLess =
        BigQueryFixtures.getBigQuery(snapshotLess.getDataProject(), stewardToken);

    // make sure the old counts stayed the same
    assertSnapshotTableCount(bigQueryAll, snapshotAll, "participant", 5L);
    assertSnapshotTableCount(bigQueryAll, snapshotAll, "sample", 7L);

    // make sure the new counts make sense
    assertSnapshotTableCount(bigQueryLess, snapshotLess, "participant", 2L);
    assertSnapshotTableCount(bigQueryLess, snapshotLess, "sample", 5L);
  }

  private void assertSnapshotTableCount(
      BigQuery bigQuery, SnapshotModel snapshot, String tableName, Long n)
      throws InterruptedException {

    String sql = "SELECT count(*) FROM " + BigQueryFixtures.makeTableRef(snapshot, tableName);
    TableResult result = BigQueryFixtures.queryWithRetry(sql, bigQuery);
    assertThat(
        "count matches", result.getValues().iterator().next().get(0).getLongValue(), equalTo(n));
  }

  private UUID ingestedDataset() throws Exception {
    DatasetSummaryModel datasetSummaryModel =
        dataRepoFixtures.createDataset(steward(), profileId, "ingest-test-dataset.json");
    UUID datasetId = datasetSummaryModel.getId();
    IngestRequestModel ingestRequest =
        dataRepoFixtures.buildSimpleIngest(
            "participant", "ingest-test/ingest-test-participant.json");
    IngestResponseModel ingestResponse =
        dataRepoFixtures.ingestJsonData(steward(), datasetId, ingestRequest);
    assertThat("correct participant row count", ingestResponse.getRowCount(), equalTo(5L));

    ingestRequest =
        dataRepoFixtures.buildSimpleIngest("sample", "ingest-test/ingest-test-sample.json");
    ingestResponse = dataRepoFixtures.ingestJsonData(steward(), datasetId, ingestRequest);
    assertThat("correct sample row count", ingestResponse.getRowCount(), equalTo(7L));
    return datasetId;
  }
}


text:
import { Class, Primitive } from "@entity-space/utils";
import { Metadata, MetadataReference } from "./blueprint-instance";

export type Discriminant = string | number;
export type MetadataToken = Class | Metadata | MetadataReference;
// [todo] should we add "Primitive[]", so we support arrays of mixed primitive types?
// that would also let us get rid of "nullable" attribute, as user could do define([Number, Null]) (where "Null" is not standard, but provided by entity-space)
export type BlueprintPropertyValue = Primitive | Discriminant | MetadataToken | MetadataToken[];
// export type PropertyValueType = Primitive | Discriminant | Class | Class[] | Metadata | Metadata[] | MetadataReference | MetadataReference[];

export interface BlueprintProperty<V extends BlueprintPropertyValue = BlueprintPropertyValue> {
    valueType: V;
}

export interface ArrayAttribute {
    array: true;
}

export interface DiscriminatorAttribute {
    discriminator: true;
}

export interface IdAttribute {
    id: true;
}

export interface IndexAttribute {
    index: true;
}

export interface NullableAttribute {
    nullable: true;
}

export interface ReadOnlyAttribute {
    readOnly: true;
}

export interface RelationAttribute {
    relation: true;
    from: string; // [todo] support string[]
    to: string; // [todo] support string[]
}

export interface RequiredAttribute {
    required: true;
}

// [todo] sadly, we can't support writeOnly yet, as otherwise intellisense for Expansion<Instance<MyModel>> won't work :(
// reason being that we would have to filter out properties that are write only, so we need a { [K in keyof T] } mapping,
// which just kills intellisense. not sure why, probably a limitation of typescript?
// [update] actually, we could support it - expand will just have a nonsensical suggestion. in addition, writeOnly would then
// always have to be optional though?
// export interface WriteOnlyAttribute {
//     writeOnly: true;
// }

export type AllAttributes =
    | ArrayAttribute
    | DiscriminatorAttribute
    | IdAttribute
    | IndexAttribute
    | NullableAttribute
    | ReadOnlyAttribute
    | RelationAttribute
    | RequiredAttribute;

// [todo] user can put anything as O & "find references" doesn't work
export function define<V extends BlueprintPropertyValue, O extends Partial<AllAttributes>>(
    valueType: V,
    options?: O
): BlueprintProperty<V> & O {
    return { valueType, ...(options ?? {}) } as BlueprintProperty<V> & O;
}

export function isProperty(value: unknown): value is BlueprintProperty {
    return (value as BlueprintProperty | undefined | null)?.valueType != null;
}

type DistributedKeyOf<T> = T extends any ? keyof T : never;

export function hasAttribute<P extends BlueprintProperty, K extends DistributedKeyOf<AllAttributes>>(
    attribute: K,
    property: P
): property is P & Extract<AllAttributes, Record<K, true>>;
// currying signature
export function hasAttribute<K extends DistributedKeyOf<AllAttributes>>(
    attribute: K
): <P extends BlueprintProperty>(property: P) => property is P & Extract<AllAttributes, Record<K, true>>;
export function hasAttribute(attribute: string, property?: Record<string, any>): any {
    if (property === void 0) {
        return (property: Record<string, any>) => property[attribute] === true;
    }

    return property[attribute] === true;
}

redpajama_set_name: RedPajamaGithub


text:
var idle = false;
var game_level = 0;
var level_timer = 0;
var in_game = false;

/* ==========================================================================
   Initialize functions.
   ========================================================================== */

$(document).ready(function(){
    $('body').bind('mousedown', function(event) {
      if(idle) {
        switch (event.which) {
          case 1:
              idle=false;
        }
      }
    });

    $('.play_again').on('click', function(){
      start_game();
    });

    $('.toolbar__exit').on('click', function(){
      game_over();
    });

    $('.back').on('click', function(){
      window.history.back();
    });
});

function start_game() {
  reset_toolbar();
	hide_overlays();
	initialize_game(1);
  score = 0;
  insert_score_html(score);
}

function hide_overlays() {
    $('.instruction-overlay').hide();
    $('.result-overlay').hide();
}

/* ==========================================================================
   In game instruction
   ========================================================================== */

function check_inactivity() {
  cancel_instruction_timer =
    setInterval(function(){
      show_instruction();
    }, 500);
}

function display_instruction(timeout) {
    idle = true;
    setTimeout(function(){
        check_inactivity()
    }, timeout);
}

function show_instruction() {
  if(idle) {
    $('.in-game-instruction').show();
  }
  else {
    $('.in-game-instruction').hide();
    clearInterval(cancel_instruction_timer);
  }
}

/* ==========================================================================
   Initialize Game Level
   ========================================================================== */

function initialize_game(level) {
    game_level = level;
    if(level < 4) {
        in_game = true;
        play_level(level);
    }
    else {
      game_winner();
    }
}

function play_level(level) {
    clean_slate();
    reset_timer();
    set_game_level();
    setup_level(level);
}

/* ==========================================================================
   Toolbar Functions.
   ========================================================================== */

function reset_toolbar() {
	$('.toolbar').show();
    $('.toolbar__exit').show();
    $('.toolbar__score').find('.toolbar__value__score').text(0);
}

function set_toolbar_timer(time) {
    $('.toolbar__timer').find('.toolbar__value').text(get_timer_value(time));
}

function set_game_level() {
  $('.game_level').text(game_level+" ");
}

function set_game_level_score(points) {
  $('.toolbar__value__game-score').text(points);
}

function update_score_html(points) {
  current_score = parseInt($('.toolbar__score').find('.toolbar__value').text());
  new_score = current_score + points;
  $('.toolbar__score').find('.toolbar__value').text(new_score);
}

function insert_score_html(points) {
  $('.toolbar__score__value').text(points);
}

function remove_toolbar_exit() {
    $('.toolbar__exit').hide();
}

/* ==========================================================================
   Timer functions
   ========================================================================== */

function reset_timer() {
  clearInterval(timer_id);
  level_timer = game_level_timer;
  start_timer();
}

function start_timer() {
  timer_id = setInterval(function(){
                if(level_timer > 0) {
                  level_timer = level_timer - 1;
                  set_toolbar_timer(level_timer);
                } else {
                  game_over();
                  clean_slate();
                  clearInterval(timer_id);
                }
              }, 1000);
}

function get_timer_value(time) {
  if(time < 10) {
    return "0 : 0"+time.toString();
  }
  else {
    return "0 : "+time.toString();
  }
}

/* ==========================================================================
    Utility Functions
   ========================================================================== */

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

/* ==========================================================================
    Results Overlay
   ========================================================================== */

function update_result_message(message) {
    $('.result-overlay').find('.result').text(message);
}

function show_winner() {
    $('.result-overlay').find('.loser').hide();
    $('.result-overlay').find('.winner').show();
}

function show_loser() {
    $('.result-overlay').find('.winner').hide();
    $('.result-overlay').find('.loser').show();
}

function game_winner() {
  update_result_message("Congratulations!");
  show_winner();
  show_results();
}

function game_over() {
  in_game = false;
  update_result_message("Game Over");
  show_loser();
  show_results();
  clean_slate();
}

/* ==========================================================================
    Level Up Overlay
   ========================================================================== */

var announce_messages = ["Good Job!", "Keep Going!", "Awesome!", "Almost there!"]
function announce_level_up(level) {
    if(level < 4) {
      $('.level-overlay').addClass('level-overlay--open').removeClass('level-overlay--close');
       setTimeout(function(){
         $('.level-overlay__message .title').text("Level "+level);
         $('.level-overlay__message .message').text(random_announce(announce_messages));
         $('.level-overlay__message').show();
       }, 300);

      setTimeout(function(){
        initialize_game(game_level + 1);
        $('.level-overlay').addClass('level-overlay--close').removeClass('level-overlay--open');
        setTimeout(function(){
         $('.level-overlay__message').hide();
        }, 400);
      }, 1800);
    }
    else {
      initialize_game(game_level + 1);
    }
}

function random_announce(messages) {
  shuffled = shuffle(messages);
  return shuffled[0];
}


text:
class LinkedListNode:

    def __init__(self, value):
        self.value = value
        self.next  = None

def kth_to_last_node(fromLast, rootNode):
    node = rootNode
    totalNodes = 0

    while node != None:
        totalNodes += 1
        node = node.next

    #initially forgot this error case
    if fromLast > totalNodes:
        raise ValueError('node needed is larger than the length of the linked list: %s' % fromLast)

    node = rootNode
    for i in range(totalNodes-fromLast):
        node = node.next

    return node

a = LinkedListNode("Angel Food")
b = LinkedListNode("Bundt")
c = LinkedListNode("Cheese")
d = LinkedListNode("Devil's Food")
e = LinkedListNode("Eccles")

a.next = b
b.next = c
c.next = d
d.next = e

print(kth_to_last_node(2, a).value)
# returns the node with value "Devil's Food" (the 2nd to last node)


text:
extern uint128_t rtl_uint128_div(uint128_t value1, uint128_t value2)
{
    uint128_t result;
    result.value = value1.value / value2.value;
    return result;
}

extern uint128_t rtl_uint128_shr(uint128_t value, int bits)
{
    uint128_t result;
    result.value = value.value >> bits;
    return result;
}

extern uint128_t rtl_uint128_shl(uint128_t value, int bits)
{
    uint128_t result;
    result.value = value.value << bits;
    return result;
}

extern uint128_t rtl_uint128_ror(uint128_t value, int bits)
{
    uint128_t result;
    result.value = (value.value >> bits) | (value.value << (128 - bits));
    return result;
}

extern uint128_t rtl_uint128_rol(uint128_t value, int bits)
{
    uint128_t result;
    result.value = (value.value << bits) | (value.value >> (128 - bits));
    return result;
}

#endif


text:
namespace extensions {
namespace declarative_webrequest_constants {

// Signals to which WebRequestRulesRegistries are registered.
const char kOnRequest[] = "declarativeWebRequest.onRequest";
const char kOnMessage[] = "declarativeWebRequest.onMessage";

// Keys of dictionaries.
const char kAgeLowerBoundKey[] = "ageLowerBound";
const char kAgeUpperBoundKey[] = "ageUpperBound";
const char kCookieKey[] = "cookie";
const char kContentTypeKey[] = "contentType";
const char kDomainKey[] = "domain";
const char kExcludeContentTypeKey[] = "excludeContentType";
const char kExcludeRequestHeadersKey[] = "excludeRequestHeaders";
const char kExcludeResponseHeadersKey[] = "excludeResponseHeaders";
const char kExpiresKey[] = "expires";
const char kFilterKey[] ="filter";
const char kFirstPartyForCookiesUrlKey[] = "firstPartyForCookiesUrl";
const char kFromKey[] = "from";
const char kHttpOnlyKey[] = "httpOnly";
const char kHasTagKey[] = "hasTag";
const char kInstanceTypeKey[] = "instanceType";
const char kLowerPriorityThanKey[] = "lowerPriorityThan";
const char kMaxAgeKey[] = "maxAge";
const char kMessageKey[] = "message";
const char kModificationKey[] = "modification";
const char kNameContainsKey[] = "nameContains";
const char kNameEqualsKey[] = "nameEquals";
const char kNameKey[] = "name";
const char kNamePrefixKey[] = "namePrefix";
const char kNameSuffixKey[] = "nameSuffix";
const char kPathKey[] = "path";
const char kRedirectUrlKey[] = "redirectUrl";
const char kRequestHeadersKey[] = "requestHeaders";
const char kResourceTypeKey[] = "resourceType";
const char kResponseHeadersKey[] = "responseHeaders";
const char kSecureKey[] = "secure";
const char kSessionCookieKey[] = "sessionCookie";
const char kStagesKey[] = "stages";
const char kThirdPartyKey[] = "thirdPartyForCookies";
const char kToKey[] = "to";
const char kUrlKey[] = "url";
const char kValueContainsKey[] = "valueContains";
const char kValueEqualsKey[] = "valueEquals";
const char kValueKey[] = "value";
const char kValuePrefixKey[] = "valuePrefix";
const char kValueSuffixKey[] = "valueSuffix";

// Enum string values
const char kOnBeforeRequestEnum[] = "onBeforeRequest";
const char kOnBeforeSendHeadersEnum[] = "onBeforeSendHeaders";
const char kOnHeadersReceivedEnum[] = "onHeadersReceived";
const char kOnAuthRequiredEnum[] = "onAuthRequired";

// Values of dictionaries, in particular instance types
const char kAddRequestCookieType[] = "declarativeWebRequest.AddRequestCookie";
const char kAddResponseCookieType[] = "declarativeWebRequest.AddResponseCookie";
const char kAddResponseHeaderType[] = "declarativeWebRequest.AddResponseHeader";
const char kCancelRequestType[] = "declarativeWebRequest.CancelRequest";
const char kEditRequestCookieType[] = "declarativeWebRequest.EditRequestCookie";
const char kEditResponseCookieType[] =
    "declarativeWebRequest.EditResponseCookie";
const char kIgnoreRulesType[] = "declarativeWebRequest.IgnoreRules";
const char kRedirectRequestType[] = "declarativeWebRequest.RedirectRequest";
const char kRedirectByRegExType[] =
    "declarativeWebRequest.RedirectByRegEx";
const char kRedirectToEmptyDocumentType[] =
    "declarativeWebRequest.RedirectToEmptyDocument";
const char kRedirectToTransparentImageType[] =
    "declarativeWebRequest.RedirectToTransparentImage";
const char kRemoveRequestCookieType[] =
    "declarativeWebRequest.RemoveRequestCookie";
const char kRemoveRequestHeaderType[] =
    "declarativeWebRequest.RemoveRequestHeader";
const char kRemoveResponseCookieType[] =
    "declarativeWebRequest.RemoveResponseCookie";
const char kRemoveResponseHeaderType[] =
    "declarativeWebRequest.RemoveResponseHeader";
const char kRequestMatcherType[] = "declarativeWebRequest.RequestMatcher";
const char kSendMessageToExtensionType[] =
    "declarativeWebRequest.SendMessageToExtension";
const char kSetRequestHeaderType[] = "declarativeWebRequest.SetRequestHeader";

}  // namespace declarative_webrequest_constants
}  // namespace extensions


text:
const quilt = require('@quilt/quilt');
let spark = require('@quilt/spark');
let infrastructure = require('../../config/infrastructure.js');

let deployment = quilt.createDeployment();
deployment.deploy(infrastructure);

let sprk = new spark.Spark(1, 3);

deployment.deploy(sprk);


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace NinjaHive.WebApp.Helpers
{
    public static class UrlProvider<TController> where TController : Controller
    {
        private static string controllerAreaName;

        public static string GetParameterlessUrl(Expression<Action<TController>> actionSelector)
        {
            return GetVirtualPathData(actionSelector, false).VirtualPath;
        }

        public static string GetUrl(Expression<Action<TController>> action)
        {
            return GetVirtualPathData(action, true).VirtualPath;
        }

        public static VirtualPathData GetVirtualPathData(Expression<Action<TController>> actionSelector,
            bool includeParams = false)
        {
            if (actionSelector.Body is MethodCallExpression)
            {
                return GetVirtualPathData((MethodCallExpression)actionSelector.Body, includeParams);
            }

            throw new ArgumentException(string.Format(
                "Expression {0} has body of type {1}, which is not supported.", actionSelector, actionSelector.Body.GetType().Name));
        }

        private static VirtualPathData GetVirtualPathData(MethodCallExpression expression, bool includeParams)
        {
            var method = expression.Method;

            if (!method.IsConstructor && method.IsPublic)
            {
                var routes = new RouteValueDictionary(new
                {
                    Controller = typeof(TController).Name.Replace(nameof(Controller), ""),
                    Action = method.Name,
                    Area = GetAreaName()
                });

                if (includeParams)
                {
                    IncludeParameters(expression, routes);
                }

                return RouteTable.Routes.GetVirtualPathForArea(HttpContext.Current.Request.RequestContext, routes);
            }

            throw new ArgumentException(string.Format("The expression '{0}' is not supported. ", expression));
        }

        public static RouteValueDictionary GetRouteValues(Expression<Action<TController>> actionSelector)
        {
            var expression = (MethodCallExpression)actionSelector.Body;
            var method = expression.Method;

            if (!method.IsConstructor && method.IsPublic)
            {
                var routes = new RouteValueDictionary(new
                {
                    Controller = typeof(TController).Name.Replace(nameof(Controller), ""),
                    Action = method.Name,
                    Area = GetAreaName()
                });

                IncludeParameters(expression, routes);

                return routes;
            }

            throw new ArgumentException(string.Format("The expression '{0}' is not supported. ", expression));
        }

        private static void IncludeParameters(MethodCallExpression expression, RouteValueDictionary routes)
        {
            var methodParameters = expression.Method.GetParameters();

            for (var argumentIndex = 0; argumentIndex < expression.Arguments.Count; argumentIndex++)
            {
                var argumentExpression = expression.Arguments[argumentIndex];

                var methodParameter = methodParameters[argumentIndex];

                IncludeParameter(argumentExpression, methodParameter, routes);
            }
        }

        private static void IncludeParameter(Expression argumentExpression,
            ParameterInfo methodParameter, RouteValueDictionary routes)
        {
            if (methodParameter.ParameterType == typeof(string) || methodParameter.ParameterType.IsValueType)
            {
                var value = GetValue(argumentExpression);

                routes.Add(methodParameter.Name, value);
            }
        }

        private static object GetValue(Expression argumentExpression)
        {
            // Optimization: in some cases we don't need to compile the expression and invoke it.
            var constantExpression = argumentExpression as ConstantExpression;

            if (constantExpression != null)
            {
                return constantExpression.Value;
            }

            // This is the fallback case: now we need to compile it.
            var valueRetriever = Expression.Lambda(argumentExpression).Compile();

            return valueRetriever.DynamicInvoke();
        }

        private static string GetAreaName()
        {
            return controllerAreaName ?? (controllerAreaName = FindAreaName());
        }

        private static string FindAreaName()
        {
            var areaNames =
                from areaRegistrationType in typeof(TController).Assembly.ExportedTypes
                where areaRegistrationType.IsSubclassOf(typeof(AreaRegistration))
                let controllerBelongsToArea = typeof(TController).Namespace.StartsWith(areaRegistrationType.Namespace)
                where controllerBelongsToArea
                let areaRegistration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType)
                select areaRegistration.AreaName;

            return areaNames.SingleOrDefault() ?? string.Empty;
        }
    }
}


text:
package com.cloudata.mq.web;

import java.io.IOException;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet to support the AWS SQS API
 *
 * We use a servlet because the AWS APIs aren't really RESTful
 *
 */
@Singleton
public class SqsServlet extends HttpServlet {
  private static final Logger log = LoggerFactory.getLogger(SqsServlet.class);

  private static final long serialVersionUID = 1L;

  @Inject
  ActionFactory actionFactory;

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String actionName = request.getParameter("Action");
    log.debug("Got request: {}", actionName);
    Action action = actionFactory.getAction(actionName);
    if (action == null) {
      log.debug("InvalidAction: {}", actionName);
      sendError(response, 400, "InvalidAction");
      return;
    }

    try {
      action.init(request, response);

      action.run();
    } catch (Exception e) {
      log.error("Unexpected failure running action", e);
      sendError(response, 500, "InternalFailure");
    }
  }

  private void sendError(HttpServletResponse resp, int code, String message) throws IOException {
    resp.sendError(code, message);
  }

}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Microsoft.Practices.ServiceLocation</name>
    </assembly>
    <members>
        <member name="T:Microsoft.Practices.ServiceLocation.ServiceLocatorProvider">
            <summary>
            This delegate type is used to provide a method that will
            return the current container. Used with the <see cref="T:Microsoft.Practices.ServiceLocation.ServiceLocator"/>
            static accessor class.
            </summary>
            <returns>An <see cref="T:Microsoft.Practices.ServiceLocation.IServiceLocator"/>.</returns>
        </member>
        <member name="T:Microsoft.Practices.ServiceLocation.ServiceLocator">
            <summary>
            This class provides the ambient container for this application. If your
            framework defines such an ambient container, use ServiceLocator.Current
            to get it.
            </summary>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(Microsoft.Practices.ServiceLocation.ServiceLocatorProvider)">
            <summary>
            Set the delegate that is used to retrieve the current container.
            </summary>
            <param name="newProvider">Delegate that, when called, will return
            the current ambient container.</param>
        </member>
        <member name="P:Microsoft.Practices.ServiceLocation.ServiceLocator.Current">
            <summary>
            The current ambient container.
            </summary>
        </member>
        <member name="T:Microsoft.Practices.ServiceLocation.ActivationException">
            <summary>
            The standard exception thrown when a ServiceLocator has an error in resolving an object.
            </summary>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor">
            <summary>
            Initializes a new instance of the <see cref="T:System.Exception" /> class.
            </summary>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor(System.String)">
            <summary>
            Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message.
            </summary>
            <param name="message">
            The message that describes the error.
             </param>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ActivationException.#ctor(System.String,System.Exception)">
            <summary>
            Initializes a new instance of the <see cref="T:System.Exception" /> class with a specified error message and a reference to the inner exception that is the cause of this exception.
            </summary>
            <param name="message">
            The error message that explains the reason for the exception.
            </param>
            <param name="innerException">
            The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.
            </param>
        </member>
        <member name="T:Microsoft.Practices.ServiceLocation.IServiceLocator">
            <summary>
            The generic Service Locator interface. This interface is used
            to retrieve services (instances identified by type and optional
            name) from a container.
            </summary>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance(System.Type)">
            <summary>
            Get an instance of the given <paramref name="serviceType"/>.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance(System.Type,System.String)">
            <summary>
            Get an instance of the given named <paramref name="serviceType"/>.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <param name="key">Name the object was registered with.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetAllInstances(System.Type)">
            <summary>
            Get all instances of the given <paramref name="serviceType"/> currently
            registered in the container.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>A sequence of instances of the requested <paramref name="serviceType"/>.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance``1">
            <summary>
            Get an instance of the given <typeparamref name="TService"/>.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetInstance``1(System.String)">
            <summary>
            Get an instance of the given named <typeparamref name="TService"/>.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <param name="key">Name the object was registered with.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.IServiceLocator.GetAllInstances``1">
            <summary>
            Get all instances of the given <typeparamref name="TService"/> currently
            registered in the container.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>A sequence of instances of the requested <typeparamref name="TService"/>.</returns>
        </member>
        <member name="T:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase">
            <summary>
            This class is a helper that provides a default implementation
            for most of the methods of <see cref="T:Microsoft.Practices.ServiceLocation.IServiceLocator"/>.
            </summary>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetService(System.Type)">
            <summary>
            Implementation of <see cref="M:System.IServiceProvider.GetService(System.Type)"/>.
            </summary>
            <param name="serviceType">The requested service.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error in resolving the service instance.</exception>
            <returns>The requested object.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(System.Type)">
            <summary>
            Get an instance of the given <paramref name="serviceType"/>.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(System.Type,System.String)">
            <summary>
            Get an instance of the given named <paramref name="serviceType"/>.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <param name="key">Name the object was registered with.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is an error resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetAllInstances(System.Type)">
            <summary>
            Get all instances of the given <paramref name="serviceType"/> currently
            registered in the container.
            </summary>
            <param name="serviceType">Type of object requested.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>A sequence of instances of the requested <paramref name="serviceType"/>.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance``1">
            <summary>
            Get an instance of the given <typeparamref name="TService"/>.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance``1(System.String)">
            <summary>
            Get an instance of the given named <typeparamref name="TService"/>.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <param name="key">Name the object was registered with.</param>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetAllInstances``1">
            <summary>
            Get all instances of the given <typeparamref name="TService"/> currently
            registered in the container.
            </summary>
            <typeparam name="TService">Type of object requested.</typeparam>
            <exception cref="T:Microsoft.Practices.ServiceLocation.ActivationException">if there is are errors resolving
            the service instance.</exception>
            <returns>A sequence of instances of the requested <typeparamref name="TService"/>.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.DoGetInstance(System.Type,System.String)">
            <summary>
            When implemented by inheriting classes, this method will do the actual work of resolving
            the requested service instance.
            </summary>
            <param name="serviceType">Type of instance requested.</param>
            <param name="key">Name of registered service you want. May be null.</param>
            <returns>The requested service instance.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.DoGetAllInstances(System.Type)">
            <summary>
            When implemented by inheriting classes, this method will do the actual work of
            resolving all the requested service instances.
            </summary>
            <param name="serviceType">Type of service requested.</param>
            <returns>Sequence of service instance objects.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.FormatActivationExceptionMessage(System.Exception,System.Type,System.String)">
            <summary>
            Format the exception message for use in an <see cref="T:Microsoft.Practices.ServiceLocation.ActivationException"/>
            that occurs while resolving a single service.
            </summary>
            <param name="actualException">The actual exception thrown by the implementation.</param>
            <param name="serviceType">Type of service requested.</param>
            <param name="key">Name requested.</param>
            <returns>The formatted exception message string.</returns>
        </member>
        <member name="M:Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.FormatActivateAllExceptionMessage(System.Exception,System.Type)">
            <summary>
            Format the exception message for use in an <see cref="T:Microsoft.Practices.ServiceLocation.ActivationException"/>
            that occurs while resolving multiple service instances.
            </summary>
            <param name="actualException">The actual exception thrown by the implementation.</param>
            <param name="serviceType">Type of service requested.</param>
            <returns>The formatted exception message string.</returns>
        </member>
        <member name="T:Microsoft.Practices.ServiceLocation.Properties.Resources">
            <summary>
              A strongly-typed resource class, for looking up localized strings, etc.
            </summary>
        </member>
        <member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ResourceManager">
            <summary>
              Returns the cached ResourceManager instance used by this class.
            </summary>
        </member>
        <member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.Culture">
            <summary>
              Overrides the current thread's CurrentUICulture property for all
              resource lookups using this strongly typed resource class.
            </summary>
        </member>
        <member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ActivateAllExceptionMessage">
            <summary>
              Looks up a localized string similar to Activation error occured while trying to get all instances of type {0}.
            </summary>
        </member>
        <member name="P:Microsoft.Practices.ServiceLocation.Properties.Resources.ActivationExceptionMessage">
            <summary>
              Looks up a localized string similar to Activation error occured while trying to get instance of type {0}, key "{1}".
            </summary>
        </member>
    </members>
</doc>


text:
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Random Matrix Theory </title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Random Matrix Theory

 Wigner's semicircle law: (a) combinatorial method, (b) Stieltjes' transform method, (c) Chatterjee's invariance principle method.

 Gaussian unitary and orthogonal ensembles: (a) Exact density of eigenvalues. (b) Orthogonal polynomials and determinantal formulas
leading to another proof of Wigner's semicircle law.

 Tridiagonal reduction for GUE and GOE: (a) Another derivation of eigenvalue density. (b) Another proof of Wigner's semicircle law.
 (c) Matrix models for Beta ensembles. (c) Selberg's integral.

Other models of random matrices - Wishart and Jacobi ensembles.

Free probability: (a) Noncommutative probability space and free independence. (b) Combinatorial approach to freeness. (c) Limiting
 spectra of sums of random matrices.

Non-hemitian random matrices: (a) Ginibre ensemble. (b) Circular law for matrices with i.i.d entries.

Fluctuation behaviour of eigenvalues (if time permits).


text:
module IbssmApiClient
  class Homework < Base

    # Returns a summary of a student's homework.
    def summary(token,student_profile_id)
      path = "homework/index"
      return get_data(token,path,'?student_profile_id=' + student_profile_id.to_s)
    end

    def completed(token,student_profile_id)
      path = "homework/completed"
      return get_data(token,path,'?student_profile_id=' + student_profile_id.to_s)
    end

    def missing(token,student_profile_id)
      path = "homework/missing"
      return get_data(token,path,'?student_profile_id=' + student_profile_id.to_s)
    end

    def future(token,student_profile_id)
      path = "homework/future"
      return get_data(token,path,'?student_profile_id=' + student_profile_id.to_s)
    end

    def homework_by_type(token,student_profile_id,homework_type)
      case homework_type
      when "completed"
        completed(token,student_profile_id)
      when "future"
        future(token,student_profile_id)
      else
        # fail
      end
    end
  end
end


text:
// Copyright (c). All rights reserved.
//
// Licensed under the MIT license.

using System;
using System.Runtime.InteropServices;

namespace Microsoft.Dism
{
    public static partial class DismApi
    {
        ///
        /// Describes the custom properties of a package. Custom properties are any properties that are not found in DismPackage Structure or DismFeature Structure.
        ///
        /// <remarks>
        ///
        /// typedef struct _DismCustomProperty
        /// {
        ///     PCWSTR Name;
        ///     PCWSTR Value;
        ///     PCWSTR Path;
        /// } DismCustomProperty;
        /// </remarks>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)]
        internal struct DismCustomProperty_
        {
            ///
            /// The name of the custom property.
            ///
            public string Name;

            ///
            /// The value of the custom property.
            ///
            public string Value;

            ///
            /// The value of the custom property.
            ///
            public string Path;
        }
    }

    ///
    /// Represents the custom properties of a package. Custom properties are any properties that are not found in <see cref="DismPackage" /> or <see cref="DismFeature" />.
    ///
    public class DismCustomProperty : IEquatable<DismCustomProperty>
    {
        private readonly DismApi.DismCustomProperty_ _customProperty;

        ///
        /// Initializes a new instance of the <see cref="DismCustomProperty" /> class.
        ///
        /// <param name="customProperty">A native <see cref="DismApi.DismCustomProperty_" /> struct that holds the data of the custom property</param>
        internal DismCustomProperty(DismApi.DismCustomProperty_ customProperty)
        {
            // Save a reference to the native struct
            _customProperty = customProperty;
        }

        ///
        /// Gets the name of the custom property.
        ///
        public string Name => _customProperty.Name;

        ///
        /// Gets the value of the custom property.
        ///
        public string Path => _customProperty.Path;

        ///
        /// Gets the value of the custom property.
        ///
        public string Value => _customProperty.Value;

        ///
        /// Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.
        ///
        /// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority>
        /// <returns>true if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            return obj != null && Equals(obj as DismCustomProperty);
        }

        ///
        /// Determines whether the specified <see cref="DismCustomProperty" /> is equal to the current <see cref="DismCustomProperty" />.
        ///
        /// <param name="other">A <see cref="DismCustomProperty" /> object to compare with the current object.</param>
        /// <returns>true if the specified <see cref="DismCustomProperty" /> is equal to the current <see cref="DismCustomProperty" />; otherwise, false.</returns>
        public bool Equals(DismCustomProperty other)
        {
            return other != null
                   && Name == other.Name
                   && Path == other.Path
                   && Value == other.Value;
        }

        ///
        /// Serves as a hash function for a particular type.
        ///
        /// <returns>A hash code for the current <see cref="T:System.Object" />.</returns>
        public override int GetHashCode()
        {
            return (string.IsNullOrEmpty(Name) ? 0 : Name.GetHashCode())
                   ^ (string.IsNullOrEmpty(Path) ? 0 : Path.GetHashCode())
                   ^ (string.IsNullOrEmpty(Value) ? 0 : Value.GetHashCode());
        }
    }
}


text:
struct ss_encryptor *ss_create_encryptor(enum ss_encrypt_method method,
					 const uint8_t *key, size_t key_len)
{
	struct ss_encryptor *encryptor;

	switch (method) {
	case XOR_METHOD:
		encryptor = calloc(1, sizeof(typeof(*encryptor)) + key_len);
		encryptor->enc_method = method;
		encryptor->xor_enc.key_len = key_len;
		memcpy(encryptor->xor_enc.key, key, key_len);
		return encryptor;
	case RC4_METHOD:
		encryptor = calloc(1, sizeof(typeof(*encryptor)) + key_len);
		encryptor->enc_method = method;
		encryptor->rc4_enc.key_len = key_len;
		memcpy(encryptor->rc4_enc.key, key, key_len);
		rc4_init(&encryptor->rc4_enc.en_state, key, key_len);
		rc4_init(&encryptor->rc4_enc.de_state, key, key_len);
		return encryptor;
	default:
		DIE("not support %d", method);
	}
}

void ss_release_encryptor(struct ss_encryptor *encryptor)
{
	free(encryptor);
}

uint8_t *ss_encrypt(struct ss_encryptor *encryptor, uint8_t *dest,
		    uint8_t *src, size_t src_len)
{
	switch (encryptor->enc_method) {
	case XOR_METHOD:
		if (dest == src)
			return xor_encrypt(src, src_len,
					encryptor->xor_enc.key,
					encryptor->xor_enc.key_len,
					&encryptor->xor_enc.encry_loc);
		else {
			memcpy(dest, src, src_len);
			return xor_encrypt(dest, src_len,
					encryptor->xor_enc.key,
					encryptor->xor_enc.key_len,
					&encryptor->xor_enc.encry_loc);
		}
		break;
	case RC4_METHOD:
		rc4_crypt(&encryptor->rc4_enc.en_state, src, dest, src_len);
		return dest;
	default:
		DIE("not support %d", encryptor->enc_method);
	}
}

uint8_t *ss_decrypt(struct ss_encryptor *decryptor, uint8_t *dest,
		    uint8_t *src, size_t src_len)
{
	switch (decryptor->enc_method) {
	case XOR_METHOD:
		if (dest == src)
			return xor_decrypt(src, src_len,
					decryptor->xor_enc.key,
					decryptor->xor_enc.key_len,
					&decryptor->xor_enc.decry_loc);
		else {
			memcpy(dest, src, src_len);
			return xor_decrypt(dest, src_len,
					decryptor->xor_enc.key,
					decryptor->xor_enc.key_len,
					&decryptor->xor_enc.decry_loc);
		}
		break;
	case RC4_METHOD:
		rc4_crypt(&decryptor->rc4_enc.de_state, src, dest, src_len);
		return dest;
	default:
		DIE("not support %d", decryptor->enc_method);
	}
}


text:
namespace graphic
{
	class box
	{
	public:
		box(void);
		~box(void);

		void SetBox(const Vector3 &vMin, const Vector3 &vMax);
		bool IsCollision(const Box &box);
		void SetWorldTM(const Matrix44 &tm);
		Vector3 m_min, m_max;
		vector<Vector3> m_box;
		Matrix44 m_tm;
	};
}


text:
package com.github.xiaoma.jdbc;

/**
 * Created by machunxiao on 2017/2/8.
 */
public interface SuccessCallback extends Callback {

}


text:
	#define plyr_is_crtr(C) (C->ai == 0)
#else
	#define plyr_is_crtr(C) ((C) == &PLYR)
#endif

void update_vis(void);
void update_status(void);

// player willed actions
void plyr_act_pickup(int, const char **);
void plyr_act_drop(int, const char **);
void plyr_act_inv(int, const char **);
void plyr_act_equipped(int, const char **);
void plyr_act_consume(int, const char **);
void plyr_act_equip(int, const char **);
void plyr_act_throw(int, const char **);
void plyr_act_cast(int, const char **);
void plyr_act_idle(int, const char **);
void plyr_act_use(int, const char **);
void plyr_stance_neutral(int, const char **);
void plyr_stance_defense(int, const char **);
void plyr_stance_attack(int, const char **);

// player displacement
void plyr_act_move_left(int, const char **);
void plyr_act_move_right(int, const char **);
void plyr_act_move_up(int, const char **);
void plyr_act_move_down(int, const char **);
void plyr_act_move_upleft(int, const char **);
void plyr_act_move_upright(int, const char **);
void plyr_act_move_downleft(int, const char **);
void plyr_act_move_downright(int, const char **);
void plyr_act_enter(int, const char **);

// the inevitable
void plyr_ev_birth(void);
void plyr_ev_death(creature *, const char *);
void plyr_ev_lvlup(creature *);
void plyr_ev_act_comp(creature *, item *);
void plyr_ev_act_fail(creature *, void *);

#endif


text:
This tool streamlines the process of testing Google Cloud Platform samples. It is intended to
identify bugs that arise in the deployment process, and does not cover unit testing. Currently
the tool only supports Cloud Run.

Serverless Sample Tester does the following steps:

1. Deploys the sample to Cloud Run
1. Checks the deployed service for expected responses
1. Returns a log if any tests failed
1. Cleans up created resources

## Getting Started
Build Serverless Sample Tester:
```bash
go build -o sst main.go
```

Authenticate gcloud with your user account:
```bash
gcloud auth login
```

Consider setting defaults for Cloud Run operations, such as setting the region:
```bash
gcloud config set run/region us-central1
gcloud config set run/platform managed
```

## Usage
Run Serverless Sample Tester by passing in the root directory of the sample you wish to test:
```bash
./sst [target-dir]
```

### README parsing
To parse build and deploy commands from your sample's README, include the following comment code tag before each gcloud command:

```text
[//]: # ({sst-run-unix})
```

For example:
````text
[//]: # ({sst-run-unix})
```
gcloud builds submit --tag=gcr.io/${GOOGLE_CLOUD_PROJECT}/run-mysql
```
````
In the absence of a README, the tool will fall back on reasonable defaults based on whether the sample is Java-based and/or has a Dockerfile.

## Configuration and Implementation

### README location
For parsing the README, the tool assumes that it is located in the target directory. If you wish to parse a README file located elsewhere, you can include the README's location
in a `config.yaml` file in the target directory, using the key `readme`. You can specify an absolute directory, or you can simply
specify a directory relative to the sample's directory.

For example, if the README is in the parent directory of the sample:
```text
readme: ../README.md
```

### Parsing rules
No parsed commands are run through a shell, meaning that the tool will not perform any typical expansions, pipelines, redirections, or other functions. This also means that popular shell builtin commands like `cd`, `export`, `echo`, and
others may not work as expected.

However, any environment variables referenced in the form of `$var` or `${var}` will be expanded. In addition, the tool supports
bash-style multiline commands (non-quoted backslashes at the end of a line that indicate a line continuation).

The Cloud Run region should be set through the `run/region` gcloud property, as described above. Do not set the region through the `--region`
flag in the `gcloud run` commands; the tool may not work as expected.

To accurately splice out the default Cloud Run service name that is used in the README, include this service name
as the environment variable `$CLOUD_RUN_SERVICE_NAME`. If this is not provided, the tool will attempt to parse
what the name is, but it may not always be accurate. For example, if your README contains the command
```
gcloud run deploy run-mysql --image gcr.io/[YOUR_PROJECT_ID]/run-mysql
```
then `$CLOUD_RUN_SERVICE_NAME` should be set to `run-mysql`.


text:
Nightwatch introduces starting with version `v0.7` a new BDD-style assertion library which greatly improves the flexibility as well as readability of the assertions.

The `expect` assertions use a subset of the `Expect` api from the [Chai framework](http://chaijs.com/api/bdd/) and are available for elements only at this point. Here's an example:

module.exports = {
  'Demo test Google' : function (client) {
    client
      .url('http://google.no')
      .pause(1000);

    // expect element  to be present in 1000ms
    client.expect.element('body').to.be.present.before(1000);

    // expect element <#lst-ib> to have css property 'display'
    client.expect.element('#lst-ib').to.have.css('display');

    // expect element  to have attribute 'class' which contains text 'vasq'
    client.expect.element('body').to.have.attribute('class').which.contains('vasq');

    // expect element <#lst-ib> to be an input tag
    client.expect.element('#lst-ib').to.be.an('input');

    // expect element <#lst-ib> to be visible
    client.expect.element('#lst-ib').to.be.visible;

    client.end();
  }
};

The `expect` interface provides a much more flexible and fluid language for defining assertions, significantly improved over the existing `assert` interface. The only downside is that it's not possible to chain assertions anymore and at this point custom messages aren't yet supported.

For a complete list of available `expect` assertions, refer to the [API docs](/api/#expect).


text:
require 'twilio-ruby'

# Initialize the client
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
client = Twilio::REST::Client.new(account_sid, auth_token)

# Create the service
service = client.sync.v1.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

# Delete a Map Item
response = service.sync_maps('Players').sync_map_items('steph_curry').delete

puts response


text:
classdef TestWarpAffine
    %TestWarpAffine
    properties (Constant)
        img = imread(fullfile(mexopencv.root(),'test','img001.jpg'));
    end

    methods (Static)
        function test_1
            im = TestWarpAffine.img;
            M = eye(2,3);  % identity transform
            dst = cv.warpAffine(im, M);
            validateattributes(dst, {class(im)}, {'size',size(im)});
            assert(isequal(im, dst));
        end

        function test_2
            im = rgb2gray(TestWarpAffine.img);
            M = eye(2,3);  % identity transform
            dst = cv.warpAffine(im, M, 'DSize',[256 256], ...
                'Interpolation','Linear', 'WarpInverse',false, ...
                'BorderType','Constant', 'BorderValue',0);
            validateattributes(dst, {class(im)}, {'size',[256 256]});
        end

        function test_3
            im = TestWarpAffine.img;
            [h,w,~] = size(im);
            M = cv.getRotationMatrix2D([w h]./2, 30, 0.7);
            dst = cv.warpAffine(im, M, 'Dst',im, 'BorderType','Transparent');
            validateattributes(dst, {class(im)}, {'size',size(im)});
        end

        function test_error_1
            try
                cv.warpAffine();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


text:
	function listAlarme() {
	var win = Ti.UI.createWindow({
		title:"title",
		backgroundColor:'white'
	});

	var win = Ti.UI.createWindow({
		backgroundColor: '#f5f5dc',
		navBarHidden: true,
		exitOnClose: false
	});

	var removendo = [false , false];

	var imageTitle = Ti.UI.createImageView({
		  top: '0',
		  image:'/title.png'
		});

	win.add(imageTitle)

	// Create a custom template that displays an image on the left,
	// then a title next to it with a subtitle below it.
	var myTemplate = {
	    childTemplates: [
	        {                            // Image justified left
	            type: 'Ti.UI.ImageView', // Use an image view for the image
	            bindId: 'pic',           // Maps to a custom pic property of the item data
	            properties: {            // Sets the image view  properties
	                width: '50dp', height: '50dp', left: 0
	            }
	        },
	        {                            // Title
	            type: 'Ti.UI.Label',     // Use a label for the title
	            bindId: 'info',          // Maps to a custom info property of the item data
	            properties: {            // Sets the label properties
	                color: '#cc0000',
	                font: { fontFamily:'Arial', fontSize: '14dp', fontWeight:'bold' },
	                left: '60dp', top: 0
	            }
	        },
	        {                            // Subtitle
	            type: 'Ti.UI.Label',     // Use a label for the subtitle
	            bindId: 'es_info',       // Maps to a custom es_info property of the item data
	            properties: {            // Sets the label properties
	                color: '#e4717a',
	                font: { fontFamily:'Arial', fontSize: '14dp' },
	                left: '60dp', top: '25dp',
	            }
	        },
	        {                            // Subtitle
	            type: 'Titanium.UI.Button',     // Use a label for the subtitle
	            bindId: 'bt_excluir',       // Maps to a custom es_info property of the item data
	            properties: {            // Sets the label properties
	            	title: 'X',
	                color: '#cc0000',
	                backgroundColor:'transparent',
	                borderColor: 'transparent',
	                font: { fontFamily:'Arial', fontSize: '20dp', fontWeight : 'bold'},
	                right: 0, top: 12,
	            	},
	            	events:
	         	   {
	         		   click: removeAlarme
	         	   }
	        	}
	    ]
	};

	var listView = Ti.UI.createListView({
	    // Maps myTemplate dictionary to 'template' string
	    templates: { 'template': myTemplate },
	    borderColor:'transparent',
	    top: '60dp',
	    // Use 'template', that is, the myTemplate dict created earlier
	    // for all items as long as the template property is not defined for an item.
	    defaultItemTemplate: 'template'
	});

	var remedioSection = Ti.UI.createListSection();
	var remedioDataSet = [
	    // the text property of info maps to the text property of the title label
	    // the text property of es_info maps to text property of the subtitle label
	    // the image property of pic maps to the image property of the image view
	    { info: {text: 'Anador'}, es_info: {text: '12:00'}, pic: {image: 'images/pill.png'}},
	    { info: {text: 'Loprazol'}, es_info: {text: '20:00'}, pic: {image: 'images/pill.png'}}
	];
	remedioSection.setItems(remedioDataSet);

	function removeAlarme(e){
		removendo[e.itemIndex] = true;
		Ti.UI.createAlertDialog({
		   		title:'Info', message:"Você está removendo o alarme"+e.itemIndex,
		   		buttonNames:[Ti.Android.currentActivity.getString(Ti.Android.R.string.ok)]
	   			}).show()

	   	remedioSection.deleteItemsAt(e.itemIndex,1);
	}

	listView.sections = [remedioSection];
	listView.addEventListener('itemclick', function(e){
		if(!removendo[e.itemIndex]){
	    var item = remedioSection.getItemAt(e.itemIndex);
	    Ti.UI.createAlertDialog({
		   		title:'Info', message:"Você clicou no alarme"+remedioSection.getItemAt(e.itemIndex).info.text,
		   		buttonNames:[Ti.Android.currentActivity.getString(Ti.Android.R.string.ok)]
	   			}).show()
		}
	    //abrir tela com os dados do remédios
	});
	win.add(listView);
	win.open();
}

exports.listAlarme = listAlarme;


text:
#ifndef __ILibSSDPClient__
#define __ILibSSDPClient__

#include "UPnPControlPointStructs.h"

void* ILibCreateSSDPClientModule(void *chain, char* DeviceURN, int DeviceURNLength, void (*FunctionCallback)(void *sender, char* UDN, int Alive, char* LocationURL, struct sockaddr* LocationAddr, int Timeout, UPnPSSDP_MESSAGE m, void *user), void *user);
void ILibSSDP_IPAddressListChanged(void *SSDPToken);

#endif


text:
package vips

import (
	"context"
	"fmt"
	"runtime"

	"github.com/DMarby/picsum-photos/internal/image"
	"github.com/DMarby/picsum-photos/internal/logger"
	"github.com/DMarby/picsum-photos/internal/queue"
	"github.com/DMarby/picsum-photos/internal/vips"
)

// Processor is an image processor that uses vips to process images
type Processor struct {
	queue *queue.Queue
}

// New initializes a new processor instance
func New(ctx context.Context, log *logger.Logger, cache *image.Cache) (*Processor, error) {
	err := vips.Initialize(log)
	if err != nil {
		return nil, err
	}

	workers := getWorkerCount()
	workerQueue := queue.New(ctx, workers, taskProcessor(cache))
	instance := &Processor{
		queue: workerQueue,
	}

	go workerQueue.Run()
	log.Infof("starting vips worker queue with %d workers", workers)

	return instance, err
}

func getWorkerCount() int {
	workers := runtime.NumCPU()
	return workers
}

// ProcessImage loads an image from a byte buffer, processes it, and returns a buffer containing the processed image
func (p *Processor) ProcessImage(ctx context.Context, task *image.Task) (processedImage []byte, err error) {
	result, err := p.queue.Process(ctx, task)

	if err != nil {
		return nil, err
	}

	image, ok := result.([]byte)
	if !ok {
		return nil, fmt.Errorf("error getting result")
	}

	return image, nil
}

func taskProcessor(cache *image.Cache) func(ctx context.Context, data interface{}) (interface{}, error) {
	return func(ctx context.Context, data interface{}) (interface{}, error) {
		task, ok := data.(*image.Task)
		if !ok {
			return nil, fmt.Errorf("invalid data")
		}

		imageBuffer, err := cache.Get(ctx, task.ImageID)
		if err != nil {
			return nil, fmt.Errorf("error getting image from cache: %s", err)
		}

		processedImage, err := resizeImage(imageBuffer, task.Width, task.Height)
		if err != nil {
			return nil, err
		}

		if task.ApplyBlur {
			processedImage, err = processedImage.blur(task.BlurAmount)
			if err != nil {
				return nil, err
			}
		}

		if task.ApplyGrayscale {
			processedImage, err = processedImage.grayscale()
			if err != nil {
				return nil, err
			}
		}

		processedImage.setUserComment(task.UserComment)

		var buffer []byte
		switch task.OutputFormat {
		case image.JPEG:
			buffer, err = processedImage.saveToJpegBuffer()
		case image.WebP:
			buffer, err = processedImage.saveToWebPBuffer()
		}

		if err != nil {
			return nil, err
		}

		return buffer, nil
	}
}

// Shutdown shuts down the image processor and deinitialises vips
func (p *Processor) Shutdown() {
	vips.Shutdown()
}


text:
DROP TABLE IF EXISTS tbl;
DROP TABLE IF EXISTS tbl_t1;
DROP TABLE IF EXISTS tbl_t2;
DROP VIEW IF EXISTS view_v1;
DROP VIEW IF EXISTS view_v2;

CREATE TABLE tbl (col1 int, col2 int);
INSERT INTO tbl VALUES (1,1), (2,2);

CREATE TABLE tbl_t1 SELECT * FROM tbl;
CREATE TABLE tbl_t2 AS SELECT * FROM tbl;

SELECT * FROM tbl_t2;

CREATE VIEW view_v1
SELECT col1
FROM tbl A
WHERE col1 = ( SELECT col1 FROM tbl ORDER BY col1 LIMIT 1 );

CREATE VIEW view_v2 AS
SELECT col1
FROM tbl A
WHERE col1 = ( SELECT col1 FROM tbl ORDER BY col1 LIMIT 1 );

SELECT * FROM view_v2;

SELECT 1 SELECT 2 SELECT 3 SELECT 4;

DROP TABLE IF EXISTS tbl;
DROP TABLE IF EXISTS tbl_t1;
DROP TABLE IF EXISTS tbl_t2;
DROP VIEW IF EXISTS view_v1;
DROP VIEW IF EXISTS view_v2;


text:
package com.pedro.encoder.input.decoder;

import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.util.Log;
import com.pedro.encoder.Frame;
import com.pedro.encoder.input.audio.GetMicrophoneData;
import com.pedro.encoder.utils.CodecUtil;
import com.pedro.encoder.utils.PCMUtil;
import java.nio.ByteBuffer;

/**
 * Created by pedro on 20/06/17.
 */
public class AudioDecoder extends BaseDecoder {

  private final AudioDecoderInterface audioDecoderInterface;
  private final GetMicrophoneData getMicrophoneData;
  private int sampleRate;
  private boolean isStereo;
  private int channels = 1;
  private int size = 2048;
  private byte[] pcmBuffer = new byte[size];
  private byte[] pcmBufferMuted = new byte[11];
  private boolean muted = false;

  public AudioDecoder(GetMicrophoneData getMicrophoneData,
      AudioDecoderInterface audioDecoderInterface) {
    TAG = "AudioDecoder";
    this.getMicrophoneData = getMicrophoneData;
    this.audioDecoderInterface = audioDecoderInterface;
  }

  @Override
  protected boolean extract(MediaExtractor audioExtractor) {
    size = 2048;
    for (int i = 0; i < audioExtractor.getTrackCount() && !mime.startsWith("audio/"); i++) {
      mediaFormat = audioExtractor.getTrackFormat(i);
      mime = mediaFormat.getString(MediaFormat.KEY_MIME);
      if (mime.startsWith("audio/")) {
        audioExtractor.selectTrack(i);
      } else {
        mediaFormat = null;
      }
    }
    if (mediaFormat != null) {
      channels = mediaFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT);
      isStereo = channels >= 2;
      sampleRate = mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE);
      duration = mediaFormat.getLong(MediaFormat.KEY_DURATION);
      fixBuffer();
      return true;
      //audio decoder not supported
    } else {
      mime = "";
      return false;
    }
  }

  private void fixBuffer() {
    if (channels >= 2) {
      size *= channels;
    }
    pcmBuffer = new byte[size];
  }

  public boolean prepareAudio() {
    return prepare(null);
  }

  @Override
  protected boolean decodeOutput(ByteBuffer outputBuffer) {
    //This buffer is PCM data
    if (muted) {
      outputBuffer.get(pcmBufferMuted, 0,
              Math.min(outputBuffer.remaining(), pcmBufferMuted.length));
      getMicrophoneData.inputPCMData(new Frame(pcmBufferMuted, 0, pcmBufferMuted.length));
    } else {
      if (pcmBuffer.length < outputBuffer.remaining()) {
        pcmBuffer = new byte[outputBuffer.remaining()];
      }
      outputBuffer.get(pcmBuffer, 0, Math.min(outputBuffer.remaining(), pcmBuffer.length));
      if (channels > 2) { //downgrade to stereo
        byte[] bufferStereo = PCMUtil.pcmToStereo(pcmBuffer, channels);
        getMicrophoneData.inputPCMData(new Frame(bufferStereo, 0, bufferStereo.length));
      } else {
        getMicrophoneData.inputPCMData(new Frame(pcmBuffer, 0, pcmBuffer.length));
      }
    }
    return false;
  }

  @Override
  protected void finished() {
    audioDecoderInterface.onAudioDecoderFinished();
  }

  /**
   * This method should be called after prepare.
   * Get max output size to set max input size in encoder.
   */
  public int getOutsize() {
    if (!(mime.equals(CodecUtil.AAC_MIME) || mime.equals(CodecUtil.OPUS_MIME) || mime.equals(
        CodecUtil.VORBIS_MIME))) {
      Log.i(TAG, "fixing input size");
      try {
        if (running) {
          return codec.getOutputBuffers()[0].remaining();
        } else {
          if (codec != null) {
            codec.start();
            int outSize = codec.getOutputBuffers()[0].remaining();
            stopDecoder();
            if (prepare(null)) return outSize;
          }
          return 0;
        }
      } catch (Exception e) {
        return 0;
      }
    } else {
      Log.i(TAG, "default input size");
      return 0;
    }
  }

  public void mute() {
    muted = true;
  }

  public void unMute() {
    muted = false;
  }

  public boolean isMuted() {
    return muted;
  }

  public int getSampleRate() {
    return sampleRate;
  }

  public boolean isStereo() {
    return isStereo;
  }
}


text:
<?php

namespace CustomerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CustomerController extends Controller
{
    public function indexAction()
    {
        return $this->render('CustomerBundle:Customer:index.html.twig');
    }
}


text:
use core::prelude::*;
use core::mem;
use core::num::Float;
use collections::vec::Vec;
use collections::vec_map::VecMap;
use core::ops::{Add, Sub, Mul};
use alloc::boxed::Box;

use std::sync::mpsc;

use motionevent;
use motionevent::append_motion_event;
use android::input::AInputEvent;

use point;
use point::{ShaderPaintPoint, Coordinate, PointEntry, PointConsumer, PointProducer, PointInfo, ShaderPointEvent};
use drawevent::Events;

rolling_average_count!(RollingAverage16, 16);

/// lifetime storage for a pointer's past state
struct PointStorage {
    info: Option<ShaderPaintPoint>,
    sizeavg: RollingAverage16<f32>,
    speedavg: RollingAverage16<Coordinate>,
}

pub struct MotionEventConsumer {
    consumer: PointConsumer,
    current_points: VecMap<PointStorage>,
    point_counter: i32,
    point_count: i32,
}

pub struct MotionEventProducer {
    pub producer: PointProducer,
    pointer_data: motionevent::Data,
}

pub fn create_motion_event_handler(left_edge: i32) -> (MotionEventConsumer, MotionEventProducer) {
    let (producer, consumer) = mpsc::channel::<PointEntry>();
    let handler = MotionEventConsumer {
        consumer: consumer,
        current_points: VecMap::new(),
        point_counter: 0, // unique value for each new pointer
        point_count: 0, // # of currently active pointers
    };
    let producer = MotionEventProducer {
        producer: producer,
        pointer_data: motionevent::Data::new(left_edge),
    };
    debug_logi!("created motion event pair");
    (handler, producer)
}

pub unsafe fn destroy_motion_event_handler(consumer: Box<MotionEventConsumer>, producer: Box<MotionEventProducer>) {
    mem::drop(consumer);
    mem::drop(producer);
}

//FIXME: needs meaningful name
pub fn jni_append_motion_event(s: &mut MotionEventProducer, evt: *const AInputEvent) {
    append_motion_event(&mut s.pointer_data, evt, &mut s.producer);
}

pub fn jni_pause_motion_event(s: &mut MotionEventProducer) {
    motionevent::pause(&mut s.pointer_data, &mut s.producer);
}

fn manhattan_distance(a: Coordinate, b: Coordinate) -> f32 {
    let x = if a.x > b.x { a.x - b.x } else { b.x - a.x };
    let y = if a.y > b.y { a.y - b.y } else { b.y - a.y };
    return if x > y { x } else { y };
}

#[inline]
pub fn next_point(s: &mut MotionEventConsumer, e: &mut Events) -> (point::ShaderPointEvent, u8) {
    let ref mut queue = s.consumer;
    let ref mut current_points = s.current_points;
    match queue.try_recv() {
        Ok(point) => {
            e.pushpoint(point);
            let idx = point.index;
            let newpoint = point.entry;
            if !current_points.contains_key(&(idx as usize)) {
                current_points.insert(idx as usize, PointStorage {
                    info: None,
                    sizeavg: RollingAverage16::new(),
                    speedavg: RollingAverage16::new(),
                });
            }
            let oldpoint = current_points.get_mut(&(idx as usize)).unwrap();
            let pointevent = match (oldpoint.info, newpoint) {
                (Some(op), PointInfo::Point(np)) => {
                    let dist = manhattan_distance(op.pos, np.pos);
                    let avgsize = oldpoint.sizeavg.push(np.size);
                    let avgspeed = oldpoint.speedavg.push(op.pos - np.pos);
                    let npdata = ShaderPaintPoint {
                        pos: np.pos,
                        time: np.time,
                        size: avgsize,
                        speed: avgspeed,
                        distance: op.distance + dist,
                        counter: op.counter,
                    };
                    oldpoint.info = Some(npdata);
                    ShaderPointEvent::Move(op, npdata)
                },
                (_, PointInfo::FrameStop) => {
                    ShaderPointEvent::NoEvent
                },
                (op_opt, PointInfo::Stop) => {
                    let op = op_opt.unwrap_or(ShaderPaintPoint {
                        pos: Coordinate { x: 0f32, y: 0f32 },
                        time: 0f32,
                        size: 0f32,
                        speed: Coordinate { x: 0f32, y: 0f32 },
                        distance: 0f32,
                        counter: 0f32,
                    });
                    oldpoint.info = None;
                    oldpoint.sizeavg.clear();
                    oldpoint.speedavg.clear();
                    s.point_count -= 1;
                    ShaderPointEvent::Up(op)
                },
                (_, PointInfo::Point(p)) => {
                    let old_counter = s.point_counter;
                    s.point_counter += 1;
                    s.point_count += 1;
                    let npdata = ShaderPaintPoint {
                        pos: p.pos,
                        time: p.time,
                        size: p.size,
                        distance: 0f32,
                        speed: Coordinate { x: 0f32, y: 0f32 },
                        counter: old_counter as f32,
                    };
                    oldpoint.info = Some(npdata);
                    ShaderPointEvent::Down(npdata)
                },
            };
            (pointevent, idx as u8)
        },
        Err(_) => {
            (ShaderPointEvent::NoEvent, 0u8)
        }
    }
}

#[inline]
fn get_count(a: &ShaderPaintPoint, b: &ShaderPaintPoint) -> i32 {
    let distx = if (*a).pos.x > (*b).pos.x { (*a).pos.x - (*b).pos.x } else { (*b).pos.x - (*a).pos.x };
    let disty = if (*a).pos.y > (*b).pos.y { (*a).pos.y - (*b).pos.y } else { (*b).pos.y - (*a).pos.y };
    ((if distx > disty { distx } else { disty }) / 1f32) as i32
}

#[inline]
pub fn push_point(drawvec: &mut Vec<ShaderPaintPoint>, a: &ShaderPaintPoint) {
    let timescale = 10f32;
    let mut addpoint = *a;
    addpoint.time = (addpoint.time / timescale) % 1f32;
    drawvec.push(addpoint);
}

#[inline]
pub fn push_line(drawvec: &mut Vec<ShaderPaintPoint>, a: &ShaderPaintPoint, b: &ShaderPaintPoint) {
    let count = get_count(a, b);
    let timescale = 10f32;
    let stepx = ((*b).pos.x - (*a).pos.x) / count as f32;
    let stepy = ((*b).pos.y - (*a).pos.y) / count as f32;
    let steptime = ((*b).time - (*a).time) / (count as f32 * timescale);
    let stepsize = ((*b).size - (*a).size) / count as f32;
    let stepspeedx = ((*b).speed.x - (*a).speed.x) / count as f32;
    let stepspeedy = ((*b).speed.y - (*a).speed.y) / count as f32;
    let stepdistance = ((*b).distance - (*a).distance) / count as f32;
    let mut addpoint = *a;
    addpoint.time = (addpoint.time / timescale) % 1f32;
    for _ in range(0, count) {
        drawvec.push(addpoint);
        addpoint.pos.x += stepx;
        addpoint.pos.y += stepy;
        addpoint.time += steptime;
        addpoint.time = if addpoint.time > 1f32 { addpoint.time - 1f32 } else { addpoint.time };
        addpoint.size += stepsize;
        addpoint.speed.x += stepspeedx;
        addpoint.speed.y += stepspeedy;
        addpoint.distance += stepdistance;
    }
}

#[inline]
//pub fn push_catmullrom(drawvec: &mut Vec<ShaderPaintPoint>, a: &ShaderPaintPoint, b: ShaderPaintPoint, c: ShaderPaintPoint, d: ShaderPaintPoint) {
pub fn push_catmullrom(drawvec: &mut Vec<ShaderPaintPoint>, points: &[ShaderPaintPoint; 4]) {
    push_splinepts::<CatmullRom>(drawvec, points);
}
#[inline]
pub fn push_cubicbezier(drawvec: &mut Vec<ShaderPaintPoint>, points: &[ShaderPaintPoint; 4]) {
    push_splinepts::<CubicBezier>(drawvec, points);
}
#[inline]
fn push_splinepts<T: Spline<Coordinate>>(drawvec: &mut Vec<ShaderPaintPoint>, points: &[ShaderPaintPoint; 4]) {
    let coords = unsafe {
        let mut coords: [Coordinate; 4] = mem::uninitialized();
        for i in range(0, 4) {
            *coords.get_unchecked_mut(i) = points.get_unchecked(i).pos;
        }
        coords
    };
    let spline: T = Spline::new(coords);
    let (tstart, tend) = spline.get_time_scale();
    let count = unsafe { get_count(points.get_unchecked(1), points.get_unchecked(2)) };
    let timestep = (tend - tstart) / (count as f32);

    let mut addpoint = points[0];
    let mut curtime = tstart;

    let (a, b) = unsafe { (points.get_unchecked(1), points.get_unchecked(2)) };
    let timescale = 10f32;
    let steptime = ((*b).time - (*a).time) / (count as f32 * timescale);
    let stepsize = ((*b).size - (*a).size) / count as f32;
    let stepspeedx = ((*b).speed.x - (*a).speed.x) / count as f32;
    let stepspeedy = ((*b).speed.y - (*a).speed.y) / count as f32;
    let stepdistance = ((*b).distance - (*a).distance) / count as f32;
    addpoint.time = (addpoint.time / timescale) % 1f32;

    for _ in range(0, count) {
        drawvec.push(addpoint);
        addpoint.pos = spline.interpolate(curtime);
        curtime += timestep;

        addpoint.time += steptime;
        addpoint.time = if addpoint.time > 1f32 { addpoint.time - 1f32 } else { addpoint.time };
        addpoint.size += stepsize;
        addpoint.speed.x += stepspeedx;
        addpoint.speed.y += stepspeedy;
        addpoint.distance += stepdistance;
    }
}

trait Spline<T: Mul<f32> + Add<T> + Sub<T>> {
    fn new(points: [T; 4]) -> Self;
    fn get_time_scale(&self) -> (f32, f32);
    fn interpolate(&self, t: f32) -> T;
}

struct CatmullRom {
    points: [Coordinate; 4],
    time: [f32; 4],
}

impl Spline<Coordinate> for CatmullRom {
    fn new(points: [Coordinate; 4]) -> CatmullRom {
        let mut time = [0f32; 4];
        let mut total = 0f32;
        unsafe {
            for i in range(0, 3) {
                let (p, pnext) = (points.get_unchecked(i), points.get_unchecked(i+1));
                let Coordinate { x: dx, y: dy } = *pnext - *p;
                total += (dx * dx + dy * dy).powf(0.25f32);
                *time.get_unchecked_mut(i+1) = total;
            }
        }
        CatmullRom { points: points, time: time }
    }
    fn get_time_scale(&self) -> (f32, f32) {
        (self.time[1], self.time[2])
    }
    fn interpolate(&self, t: f32) -> Coordinate {
        let (p, time) = (self.points, self.time);
        let l01 = p[0] * ((time[1] - t) / (time[1] - time[0])) + p[1] * ((t - time[0]) / (time[1] - time[0]));
        let l12 = p[1] * ((time[2] - t) / (time[2] - time[1])) + p[2] * ((t - time[1]) / (time[2] - time[1]));
        let l23 = p[2] * ((time[3] - t) / (time[3] - time[2])) + p[3] * ((t - time[2]) / (time[3] - time[2]));
        let l012 = l01 * ((time[2] - t) / (time[2] - time[0])) + l12  * ((t - time[0]) / (time[2] - time[0]));
        let l123 = l12 * ((time[3] - t) / (time[3] - time[1])) + l23  * ((t - time[1]) / (time[3] - time[1]));
        let c12 = l012 * ((time[2] - t) / (time[2] - time[1])) + l123 * ((t - time[1]) / (time[2] - time[1]));
        c12
    }
}

struct CubicBezier {
    pub points: [Coordinate; 4],
}

impl Spline<Coordinate> for CubicBezier {
    fn new(points: [Coordinate; 4]) -> CubicBezier {
        CubicBezier { points: points }
    }
    fn get_time_scale(&self) -> (f32, f32) {
        (0f32, 1f32)
    }
    fn interpolate(&self, t: f32) -> Coordinate {
        let p = self.points;
        let negt = 1f32 - t;
        let (t2, negt2) = (t * t, negt * negt);
        let p0 = p[0] * (negt * negt2);
        let p1 = p[1] * (negt2 * t * 3f32);
        let p2 = p[2] * (negt * t2 * 3f32);
        let p3 = p[3] * (t * t2);
        p0 + p1 + p2 + p3
    }
}


text:
<#
.SYNOPSIS
    Converts a hashtable of parameter values to the format expected by the StatusCake API
.DESCRIPTION
    Converts a hashtable of parameter values to the format expected by the StatusCake API
.PARAMETER InputHashTable
    Hashtable containing the parameters and values to be converted
.PARAMETER DateUnix
    Keys with values which should be converted to Unix timestamp instead of RFC3339 format
.PARAMETER CsvString
    Key with values which should be converted to a CSV string instead of as an array
.EXAMPLE
   C:\PS>$inputHashtable | ConvertTo-StatusCakeHelperAPIValue
   Convert values of a hashtable into values to the format expected by StatusCake API
#>
function ConvertTo-StatusCakeHelperAPIValue
{
    [CmdletBinding()]
    [OutputType([hashtable])]
    Param(
        [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
        [hashtable] $InputHashTable,

        [string[]]$DateUnix,

        [string[]]$CsvString
    )

    Process
    {
        $workingHashtable = $PSBoundParameters["InputHashTable"]
        $outputHashtable = @{}

        foreach ($var in $workingHashtable.GetEnumerator())
        {
            $name = $var.name

            switch($var.value.GetType().Name)
            {
                'Boolean'{ # Boolean should be converted to lower case "true/false"
                    $value = "false"
                    If($var.value -eq $true){
                        $value = "true"
                    }
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'DateTime'{ #Dates needs to be in RFC3339 unless Unix timestamp has been specified for the parameter
                    if($name -in $DateUnix)
                    {
                        $value = [int64]($var.value).ToUniversalTime() | Get-Date -UFormat %s
                    }
                    else
                    {
                        $value = ($var.value).ToUniversalTime() | Get-Date -Format s
                        $value = "$value`Z"
                    }
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'Hashtable'{ # Hash table should be converted to JSON (CustomHeader)
                    $value = $var.value  | ConvertTo-Json
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'IPAddress[]'{ # IP Address string should be used
                    $ipAddresses = [System.Collections.Generic.List[PSObject]]::new()
                    $value = $var.value | ForEach-Object{$ipAddresses.Add($_.IPAddressToString)}
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'Object'{ # Hash table should be converted to JSON (CustomHeader)
                    $value = $var.value  | ConvertTo-Json
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'Object[]'{ #Convert arrays to CSV if specified
                    $value = $var.value
                    if($name -in $CsvString)
                    {
                        $value = $var.value -join ","
                    }
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'SecureString'{ #SecureString needs to be converted to plaintext
                    $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList "UserName", $var.value
                    $value = $Credentials.GetNetworkCredential().Password
                    Write-Verbose "[$($var.name)] [$($var.value.GetType().Name)] will be added with value [$("*".PadRight(8, "*"))]"
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'String[]'{ #Convert arrays to CSV if specified
                    $value = $var.value
                    if($name -in $CsvString)
                    {
                        $value = $var.value -join ","
                    }
                    $outputHashtable.Add($name,$value)
                    Break
                }
                'Uri'{ # Original string of URI should be used
                    $value = $($var.value).OriginalString
                    $outputHashtable.Add($name,$value)
                    Break
                }
                default {
                    $value = $var.value
                    $outputHashtable.Add($name,$value)
                }
            }

            if($var.value.GetType().Name -ne 'SecureString')
            {
                Write-Verbose "[$($var.name)] [$($var.value.GetType().Name)] will be added with value [$value]"
            }
        }
        Return $outputHashtable
    }
}


text:
package org.jetbrains.kotlin.idea.stubindex;

import com.intellij.openapi.project.Project;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.StubIndex;
import com.intellij.psi.stubs.StubIndexKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.psi.KtNamedDeclaration;
import java.util.Collection;

public class KotlinPropertyShortNameIndex extends AbstractStringStubIndexExtension<KtNamedDeclaration> {
    private static final StubIndexKey<String, KtNamedDeclaration> KEY = KotlinIndexUtil.createIndexKey(KotlinPropertyShortNameIndex.class);

    private static final KotlinPropertyShortNameIndex ourInstance = new KotlinPropertyShortNameIndex();

    public static KotlinPropertyShortNameIndex getInstance() {
        return ourInstance;
    }

    private KotlinPropertyShortNameIndex() {
        super(KtNamedDeclaration.class);
    }

    @NotNull
    @Override
    public StubIndexKey<String, KtNamedDeclaration> getKey() {
        return KEY;
    }

    @NotNull
    @Override
    public Collection<KtNamedDeclaration> get(@NotNull String s, @NotNull Project project, @NotNull GlobalSearchScope scope) {
        return StubIndex.getElements(KEY, s, project, scope, KtNamedDeclaration.class);
    }

}


text:
require 'helper'

class TestPrintingWords < TestHelper
  context 'Scratch::PrintingWords' do
    %w(print puts pstack).each do |meth|
      should "define #{meth}"do
        assert Scratch::PrintingWords.instance_methods(false).include?( meth )
      end
    end

    should "puts stack items when calling #puts" do
      Kernel.expects(:puts).with 4
      terp.run '4'
      assert_equal_stack [4], terp.stack
      terp.run "puts"
    end

    should "print stack items when calling #print" do
      terp.run '6'
      Kernel.expects(:print).with 6
      assert_equal_stack [6], terp.stack
      terp.run 'print'
    end

    should "puts stack when 'pstack' is called" do
      terp.run '5'
      Kernel.expects(:puts).with terp.stack.stack
      assert_equal_stack [5], terp.stack
      terp.run "pstack"
    end
  end
end