text:
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#ifndef OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_RV_TIMER_AUTOGEN_H_
#define OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_RV_TIMER_AUTOGEN_H_

// THIS FILE HAS BEEN GENERATED, DO NOT EDIT MANUALLY. COMMAND:
// util/make_new_dif.py --mode=regen --only=autogen

/**
 * @file
 * @brief RV_TIMER Device Interface Functions
 */

#include <stdbool.h>
#include <stdint.h>

#include "sw/device/lib/base/macros.h"
#include "sw/device/lib/base/mmio.h"
#include "sw/device/lib/dif/dif_base.h"

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus

/**
 * A handle to rv_timer.
 *
 * This type should be treated as opaque by users.
 */
typedef struct dif_rv_timer {
  /**
   * The base address for the rv_timer hardware registers.
   */
  mmio_region_t base_addr;
} dif_rv_timer_t;

/**
 * Creates a new handle for a(n) rv_timer peripheral.
 *
 * This function does not actuate the hardware.
 *
 * @param base_addr The MMIO base address of the rv_timer peripheral.
 * @param[out] rv_timer Out param for the initialized handle.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_init(mmio_region_t base_addr,
                               dif_rv_timer_t *rv_timer);

/**
 * A rv_timer alert type.
 */
typedef enum dif_rv_timer_alert {
  /**
   * This fatal alert is triggered when a fatal TL-UL bus integrity fault is
   * detected inside the RV_TIMER unit.
   */
  kDifRvTimerAlertFatalFault = 0,
} dif_rv_timer_alert_t;

/**
 * Forces a particular alert, causing it to be escalated as if the hardware
 * had raised it.
 *
 * @param rv_timer A rv_timer handle.
 * @param alert The alert to force.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_alert_force(const dif_rv_timer_t *rv_timer,
                                      dif_rv_timer_alert_t alert);

/**
 * A rv_timer interrupt request type.
 */
typedef enum dif_rv_timer_irq {
  /**
   * Raised if hart0's timer0 expired (mtimecmp >= mtime)
   */
  kDifRvTimerIrqTimerExpiredHart0Timer0 = 0,
} dif_rv_timer_irq_t;

/**
 * A snapshot of the state of the interrupts for this IP.
 *
 * This is an opaque type, to be used with the `dif_rv_timer_irq_get_state()`
 * function.
 */
typedef uint32_t dif_rv_timer_irq_state_snapshot_t;

/**
 * Returns the type of a given interrupt (i.e., event or status) for this IP.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @param[out] type Out-param for the interrupt type.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_get_type(const dif_rv_timer_t *rv_timer,
                                       dif_rv_timer_irq_t irq,
                                       dif_irq_type_t *type);

/**
 * Returns the state of all interrupts (i.e., pending or not) for this IP.
 *
 * @param rv_timer A rv_timer handle.
 * @param hart_id The hart to manipulate.
 * @param[out] snapshot Out-param for interrupt state snapshot.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_get_state(
    const dif_rv_timer_t *rv_timer, uint32_t hart_id,
    dif_rv_timer_irq_state_snapshot_t *snapshot);

/**
 * Returns whether a particular interrupt is currently pending.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @param[out] is_pending Out-param for whether the interrupt is pending.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_is_pending(const dif_rv_timer_t *rv_timer,
                                         dif_rv_timer_irq_t irq,
                                         bool *is_pending);

/**
 * Acknowledges all interrupts, indicating to the hardware that all
 * interrupts have been successfully serviced.
 *
 * @param rv_timer A rv_timer handle.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_acknowledge_all(const dif_rv_timer_t *rv_timer,
                                              uint32_t hart_id);

/**
 * Acknowledges a particular interrupt, indicating to the hardware that it has
 * been successfully serviced.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_acknowledge(const dif_rv_timer_t *rv_timer,
                                          dif_rv_timer_irq_t irq);

/**
 * Forces a particular interrupt, causing it to be serviced as if hardware had
 * asserted it.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @param val Value to be set.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_force(const dif_rv_timer_t *rv_timer,
                                    dif_rv_timer_irq_t irq, const bool val);

/**
 * A snapshot of the enablement state of the interrupts for this IP.
 *
 * This is an opaque type, to be used with the
 * `dif_rv_timer_irq_disable_all()` and `dif_rv_timer_irq_restore_all()`
 * functions.
 */
typedef uint32_t dif_rv_timer_irq_enable_snapshot_t;

/**
 * Checks whether a particular interrupt is currently enabled or disabled.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @param[out] state Out-param toggle state of the interrupt.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_get_enabled(const dif_rv_timer_t *rv_timer,
                                          dif_rv_timer_irq_t irq,
                                          dif_toggle_t *state);

/**
 * Sets whether a particular interrupt is currently enabled or disabled.
 *
 * @param rv_timer A rv_timer handle.
 * @param irq An interrupt request.
 * @param state The new toggle state for the interrupt.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_set_enabled(const dif_rv_timer_t *rv_timer,
                                          dif_rv_timer_irq_t irq,
                                          dif_toggle_t state);

/**
 * Disables all interrupts, optionally snapshotting all enable states for later
 * restoration.
 *
 * @param rv_timer A rv_timer handle.
 * @param hart_id The hart to manipulate.
 * @param[out] snapshot Out-param for the snapshot; may be `NULL`.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_disable_all(
    const dif_rv_timer_t *rv_timer, uint32_t hart_id,
    dif_rv_timer_irq_enable_snapshot_t *snapshot);

/**
 * Restores interrupts from the given (enable) snapshot.
 *
 * @param rv_timer A rv_timer handle.
 * @param hart_id The hart to manipulate.
 * @param snapshot A snapshot to restore from.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_rv_timer_irq_restore_all(
    const dif_rv_timer_t *rv_timer, uint32_t hart_id,
    const dif_rv_timer_irq_enable_snapshot_t *snapshot);

#ifdef __cplusplus
}  // extern "C"
#endif  // __cplusplus

#endif  // OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_RV_TIMER_AUTOGEN_H_


text:
class TestTrack::Fake::Visitor
  attr_reader :id

  Assignment = Struct.new(:split_name, :variant, :unsynced, :context)

  def self.instance
    @instance ||= new(TestTrack::FakeServer.seed)
  end

  def self.reset!
    @instance = nil
    TestTrack::Fake::SplitRegistry.reset!
  end

  def initialize(id)
    @id = id
  end

  def assignments
    @assignments ||= _assignments
  end

  def split_registry
    TestTrack::SplitRegistry.new(TestTrack::Fake::SplitRegistry.instance.to_h)
  end

  private

  def _assignments
    split_registry.split_names.map do |split_name|
      variant = TestTrack::VariantCalculator.new(visitor: self, split_name: split_name).variant
      Assignment.new(split_name, variant, false, "the_context")
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
                    Incorporação registrada em 06 de abril de 2016,
                    sob o R. 5 da matrícula 140.331 do 1º Oficial
                    de Registro de Imóveis de Sorocaba.

                         Entre em contato

                    Av. 3 de Março, 1.317

                    (Ao lado do Parque Natural)

                    Alto da Boa Vista - Sorocaba/SP

                    Fone.: (15) 3228-2221

                    2017 © Todos os Direitos Reservados - Natural Park Residencial


text:
function out = f_global(v)

    global m s md qt v_max v_min
    %get mean of the vector
    m = mean(v);
    % get the standard deviation of the vector
    s = std(v);
    % get median of the vector
    md = median(v);
    sorted = sort(v);
    % get each quartis of the vector
    qt(1) = median(sorted(sorted<median(sorted)));
    qt(2) = median(sorted);
    qt(3) = median(sorted(sorted>median(sorted)));

    % get the max value of the vector
    v_max = sorted(size(sorted, 2));

    % get the min value
    v_min = sorted(1);

    out = {m, s, md, qt, v_max, v_min};

    clear global


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace biz.dfch.CS.Osram.Lightify.Client.Model
{
    public class OperationResponse : BaseDto
    {
        [JsonProperty("returnCode")]
        public int ReturnCode;
    }
}


text:
* Update PackageManagement's strong name signing

## 1.4.8
* Add NuGet as a source when generating nuget.config file for user in the NuGet Provider

## 1.4.7
* Update security protocol to use TLS 1.2
* Remove catalog file

## 1.4.6
* Update `HelpInfoUri` to point to the latest content

## 1.4.5
* Bug fix for deadlock when getting parameters in an event

## 1.4.4
* Bug fix when installing modules from private feeds

## 1.4.3
* Another bug fix when registering repositories with PowerShellGet

## 1.4.2
* Bug fix for passing credentials from PowerShellGet when registering repositories

## 1.4.1
* Bug fix for using credential provider installed in Visual Studio

## 1.4
* Allow credential persistance for registering private repositories and finding or installing packages from those repositories

## 1.3.2
* Enable bootstrap on PSCore
* Bug fix to run on .NET Core 3.0

## 1.3.1

Targets net452 and netstandard2.0 instead of net451, netcoreapp2.0, and netstandard1.6

## Previous releases are not included in this Changelog


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
    [Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
    public class YieldStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
    {
        internal override Type GetHighlighterType()
            => typeof(YieldStatementHighlighter);

        [Fact]
        public async Task TestExample1_1()
        {
            await TestAsync(
@"class C
{
    IEnumerable<int> Range(int min, int max)
    {
        while (true)
        {
            if (min >= max)
            {
                {|Cursor:[|yield break|];|}
            }

            [|yield return|] min++;
        }
    }
}");
        }

        [Fact]
        public async Task TestExample1_2()
        {
            await TestAsync(
@"class C
{
    IEnumerable<int> Range(int min, int max)
    {
        while (true)
        {
            if (min >= max)
            {
                [|yield break|];
            }

            {|Cursor:[|yield return|]|} min++;
        }
    }
}");
        }

        [Fact]
        public async Task TestExample1_3()
        {
            await TestAsync(
@"class C
{
    IEnumerable<int> Range(int min, int max)
    {
        while (true)
        {
            if (min >= max)
            {
                yield break;
            }

            yield return {|Cursor:min++|};
        }
    }
}");
        }

        [Fact]
        public async Task TestExample1_4()
        {
            await TestAsync(
@"class C
{
    IEnumerable<int> Range(int min, int max)
    {
        while (true)
        {
            if (min >= max)
            {
                [|yield break|];
            }

            [|yield return|] min++;{|Cursor:|}
        }
    }
}");
        }
    }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdTapAndPlay extends React.Component<IconBaseProps, any> { }


text:
package com.utn.ag.algoritmocanonico.service;

import com.utn.ag.algoritmocanonico.AppConstants;
import com.utn.ag.algoritmocanonico.model.Poblacion;

public interface AlgoritmoCanonico {
	public static final Double PROBABILIDAD_MUTACION = AppConstants.PROBMUTACION;
	public static final Double PROBABILIDAD_CROSSOVER = AppConstants.PROBCROSSOVER;

	public Poblacion nuevaPoblacion();
	public Poblacion nuevaPoblacion(Poblacion poblacion);
}


text:
import pyodbc
import sys
import logging

log = logging.getLogger(__name__)
db_name = ""
db_user = "dbadmin"
db_pass = ""
db_host = "127.0.0.1"
db_port = "5433"
db_error_map = {"08001": "Vertica not running.  Please start a database"}
db_conn_str = "DRIVER=HPVertica;" + "SERVER=" + db_host + ";" + "DATABASE=" + \
              db_name + ";" + "PORT=" + db_port + ";" + "UID=" + db_user + \
              ";" + "PWD=" + db_pass

def main():
    conn = None

    try:
        conn = pyodbc.connect(db_conn_str)
    except pyodbc.Error, e:
        # print "Caught an exception: %s" % e
        handle_vertica_errors(e)

    try:
        if conn is not None:
            with conn.cursor() as cursor:
                # show_system_tables(cursor)
                # show_performance_metrics(cursor)
                # show_utilization_metrics(cursor)
                show_version(cursor)
        else:
            print "Cursor is NULL, verify that a Vertica database is started/running!"
    except Exception as e:
        handle_vertica_errors(e)

def show_version(cursor=None):
    query = "SELECT VERSION();"

    try:
        rows = cursor.execute(query).fetchone()
        version = rows[0].decode('utf16').split()[-1:][0]
        print version
    except (Exception, pyodbc.ProgrammingError, pyodbc.NotSupportedError) as e:
        raise e

def show_utilization_metrics(cursor=None):
    results_dict = {}
    qlist = ["SELECT READ_KBYTES_PER_SEC, WRITTEN_KBYTES_PER_SEC FROM "
             "V_MONITOR.IO_USAGE LIMIT(1);",
             "SELECT AVERAGE_MEMORY_USAGE_PERCENT FROM "
             "V_MONITOR.MEMORY_USAGE LIMIT(1);",
             "SELECT AVERAGE_CPU_USAGE_PERCENT FROM "
             "V_MONITOR.CPU_USAGE LIMIT(1);"]

    for q in qlist:
        try:
            rows = cursor.execute(q).fetchall()
            for row in rows:
                counter = 0
                for column_list in row.cursor_description:
                    column_name = column_list[0]
                    value = row[counter]
                    results_dict[column_name] = value
                    counter += 1
        except (Exception, pyodbc.ProgrammingError, pyodbc.NotSupportedError) as e:
            raise e

    print results_dict

def show_performance_metrics(cursor=None):
    query = "select total_session_count, running_query_count from " \
            "v_monitor.query_metrics;"

    try:
        rows = cursor.execute(query).fetchall()
        for row in rows:
            # for tuple in row.cursor_description:
            #     print tuple[0]
            print 'total_session_count', row.total_session_count, \
                'running_query_count', row.running_query_count
    except (Exception, pyodbc.ProgrammingError, pyodbc.NotSupportedError) as e:
        raise e

def show_system_tables(cursor=None):
    query = "SELECT * FROM system_tables ORDER BY table_schema, table_name;"

    try:
        rows = cursor.execute(query).fetchall()
        print 'table_schema_id \t table_schema \t table_id \t table_name ' \
              '\t table_description'
        for row in rows:
            # for tuple in row.cursor_description:
            #     print tuple[0]
            print row.table_schema_id, row.table_schema.decode('utf16'), \
                row.table_id, row.table_name.decode('utf16'), \
                row.table_description.decode('utf16')
    except (Exception, pyodbc.ProgrammingError, pyodbc.NotSupportedError) as e:
        raise e

def handle_vertica_errors(e=None):
    error_code = None
    error_message = "No error message available"

    if len(e.args) > 0:
        error_code = e.args[0]

    if len(e.args) > 1:
        error_message = e.args[1]

    if error_code in db_error_map:
        print "%s" % db_error_map.get(error_code)
    else:
        print "Caught an exception: %s %s %s" % (error_code, error_message, e)
    sys.exit()

if __name__ == "__main__":
    main()


text:
<?php

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer;

class RoutableFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getGenerateFragmentUriData
     */
    public function testGenerateFragmentUri($uri, $controller)
    {
        $this->assertEquals($uri, $this->getRenderer()->doGenerateFragmentUri($controller, Request::create('/')));
    }

    /**
     * @dataProvider getGenerateFragmentUriData
     */
    public function testGenerateAbsoluteFragmentUri($uri, $controller)
    {
        $this->assertEquals('http://localhost'.$uri, $this->getRenderer()->doGenerateFragmentUri($controller, Request::create('/'), true));
    }

    public function getGenerateFragmentUriData()
    {
        return array(
            array('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array())),
            array('/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('_format' => 'xml'), array())),
            array('/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo', '_format' => 'json'), array())),
            array('/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo'), array('bar' => 'bar'))),
            array('/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array('foo' => 'foo'))),
        );
    }

    public function testGenerateFragmentUriWithARequest()
    {
        $request = Request::create('/');
        $request->attributes->set('_format', 'json');
        $request->setLocale('fr');
        $controller = new ControllerReference('controller', array(), array());

        $this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->getRenderer()->doGenerateFragmentUri($controller, $request));
    }

    private function getRenderer()
    {
        return new Renderer();
    }
}

class Renderer extends RoutableFragmentRenderer
{
    public function render($uri, Request $request, array $options = array())
    {
    }
    public function getName()
    {
    }

    public function doGenerateFragmentUri(ControllerReference $reference, Request $request, $absolute = false)
    {
        return parent::generateFragmentUri($reference, $request, $absolute);
    }
}


text:
from django.db import models

# Create your models here.

class CommonInfoModel(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True


text:
//Write a program that compares two char arrays lexicographically (letter by letter).
using System;

class ArrayComparison
{
    static void Main()
    {
        char[] firstArray = EnterArray("first");

        char[] secondArray = EnterArray("second");

        bool areEqual = ArrayCompare(firstArray, secondArray);

        if (areEqual)
        {
            Console.WriteLine("Two arrays are equal!");
        }
        else
        {
            Console.WriteLine("Two arrays are not equal!");
        }
    }

    private static bool ArrayCompare(char[] firstArray, char[] secondArray)
    {
        bool areEqual = true;
        if (firstArray.Length == secondArray.Length)
        {
            for (int i = 0; i < firstArray.Length; i++)
            {
                if (firstArray[i] != secondArray[i])
                {
                    areEqual = false;
                    break;
                }
            }
        }
        else
        {
            areEqual = false;
        }
        return areEqual;
    }

    private static char[] EnterArray(string index)
    {
        Console.Write("Enter the length of the {0} array: ", index);
        int length = int.Parse(Console.ReadLine());
        char[] array = new char[length];
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write("Enter value for {0}Array[{1}] ", index, i);
            array[i] = char.Parse(Console.ReadLine());
        }
        return array;
    }
}


text:
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#include "power_down.h"

/*
 * Disable AVR modules not being used to save power
 */
void disable_unused_circuits()
{
  power_twi_disable();
  ACSR = _BV(ACD);  // Disable analog comparator (60uA)
}

/*
 * Goes into specified sleep mode. Be sure to configure a wake-up
 * condition, otherwise only a power reset can wake the chip up.
 */
static void __sleep(uint8_t mode)
{
  set_sleep_mode(mode);
  // disable brown-out to save power and sleep
  cli();
  sleep_enable();
  sleep_bod_disable();
  // Make sure we can wake up
  sei();
  sleep_cpu();
  sleep_disable();
}

/*
 * Sleeps in low power mode until Timer 2 overflows.
 * Provides option to reduce clock speed to allow longer sleep time.
 *
 * Sleep time with clock_down:
 * 8 * 1024 * 255 * 1000 / F_CPU ms (584ms @3.58MHz, 104ms @20MHz)
 *
 * Sleep time without clock_down:
 * 1024 * 255 * 1000 / F_CPU ms (73ms @3.58MHz, 13ms @20MHz)
 *
 * SLEEP_MODE_IDLE:
 * Draws about 0.3mA @ 3.58MHz @ 4V, and wakes up immediately
 * 1.0mA avg (measured) when sleep_until_timer is called in a loop.
 *
 * SLEEP_MODE_PWR_SAVE:
 * Draws about 1uA @ 3.58MHz @ 4V, but takes 4ms + 1024clk to wake up
 * 0.1mA avg (measured) when sleep_until_timer is called in a loop.
 */
void sleep_until_timer(uint8_t mode, bool clock_down)
{
  TCCR2B = 0; // Stop timer while we setup
  TCNT2 = 0; // Set timer value to 0
  TIMSK2 |= _BV(TOIE2); // Enable Overflow interrupt

  // Preserve original power settings
  uint8_t power_reduction = PRR;

  // Disable additional circuits to save power
  power_adc_disable();

  // Clock down if requested
  if (clock_down) {
    clock_prescale_set(clock_div_8);
  }

  // Clock = Fcpu/1024 = 3496Hz @ 3.58MHz
  TCCR2B |= _BV(CS22) | _BV(CS21) | _BV(CS20);

  __sleep(mode);

  // Clock back to normal
  clock_prescale_set(clock_div_1);

  // Restore previous power settings
  PRR = power_reduction;
}

/*
 * Sleep AVR in lowest power state. If you want to wake up, make
 * sure to set a wakeup or reset condition beforehand.
 * Note that watch dog timer can awake, so disable beforehand if applicable.
 */
void sleep_forever()
{
  // Preserve original power settings
  uint8_t power_reduction = PRR;
  PRR = 0xFF;  // turn off all peripherals

  __sleep(SLEEP_MODE_PWR_DOWN);

  // Restore previous power settings
  PRR = power_reduction;
}

/*
 * Configures AVR to wake up when PCINT1 goes low.
 */
void wakeup_on_external_interrupt(void)
{
  // configure PB1 as input.
  DDRB &= ~_BV(PB1);
  // PB1 pull-up.
  PORTB |= _BV(PB1);

  // Enable level change on PB1 (PCINT1) to trigger PCINT0
  PCICR |= _BV(PCIE0);
  PCMSK0 |= _BV(PCINT1);
}

/*
 * Triggers a hard reset (via WDT) when the voltage on pin PD3 changes.
 * By wiring this pin to ext power, this will reset the device when ext.
 * power is plugged in our out. This is needed to wake up a battery device
 * from low battery shut-off.
 */
void reset_on_power_change(void) {
  // Configure PD3 (PCINT19) as Input
  DDRD &= ~_BV(PD3);
  // No Pull-up
  PORTD &= ~_BV(PD3);

  // Enable PCINT19 pin level change to trigger PCINT2
  PCMSK2 |= _BV(PCINT19);
  PCICR |= _BV(PCIE2);
}

/*
 * Disables automatic reboot on ext. power change.
 */
void disable_reset_on_power_change(void) {
  PCMSK2 &= ~_BV(PCINT19);
}

EMPTY_INTERRUPT(TIMER2_OVF_vect)

EMPTY_INTERRUPT(PCINT0_vect)

__attribute__((naked)) ISR(PCINT2_vect)
{
  // TODO: Do not count this as a WDT reset as it is intentional

  // Force a cold reset by triggering watchdog timer
  // http://support.atmel.no/bin/customer.exe?=&action=viewKbEntry&id=21
  wdt_enable(WDTO_15MS);
  while(1);
}


text:
CREATE TABLE buckets (
  id integer,
  uid integer NOT NULL,
  page page_category NOT NULL,
  filter_category text DEFAULT NULL,
  value integer NOT NULL
);

ALTER TABLE buckets
  ADD CONSTRAINT buckets_pkey PRIMARY KEY (id);

CREATE SEQUENCE buckets_id_seq
  AS integer
  START WITH 1
  INCREMENT BY 1
  NO MINVALUE
  NO MAXVALUE
  CACHE 1;

ALTER SEQUENCE buckets_id_seq OWNED BY buckets.id;
ALTER TABLE buckets ALTER COLUMN id SET DEFAULT nextval('buckets_id_seq'::regclass);

ALTER TABLE buckets
  ADD CONSTRAINT buckets_uid_foreign FOREIGN KEY (uid) REFERENCES users(uid) ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE buckets
  ADD CONSTRAINT buckets_filter_unique UNIQUE (uid, page, filter_category);

CREATE UNIQUE INDEX buckets_single_null ON buckets (uid, page, (filter_category IS NULL)) WHERE filter_category IS NULL;

CREATE TABLE bucket_investment (
  uid integer NOT NULL,
  value integer NOT NULL
);

ALTER TABLE bucket_investment
  ADD CONSTRAINT bucket_investment_pkey PRIMARY KEY (uid);

ALTER TABLE bucket_investment
  ADD CONSTRAINT buckets_uid_foreign FOREIGN KEY (uid) REFERENCES users(uid) ON UPDATE CASCADE ON DELETE CASCADE;


text:
#ifndef __XFS_ITABLE_H__
#define	__XFS_ITABLE_H__

/*
 * xfs_bulkstat() is used to fill in xfs_bstat structures as well as dm_stat
 * structures (by the dmi library). This is a pointer to a formatter function
 * that will iget the inode and fill in the appropriate structure.
 * see xfs_bulkstat_one() and xfs_dm_bulkstat_one() in dmapi_xfs.c
 */
typedef int (*bulkstat_one_pf)(struct xfs_mount	*mp,
			       xfs_ino_t	ino,
			       void		__user *buffer,
			       int		ubsize,
			       void		*private_data,
			       xfs_daddr_t	bno,
			       int		*ubused,
			       void		*dip,
			       int		*stat);

/*
 * Values for stat return value.
 */
#define	BULKSTAT_RV_NOTHING	0
#define	BULKSTAT_RV_DIDONE	1
#define	BULKSTAT_RV_GIVEUP	2

/*
 * Values for bulkstat flag argument.
 */
#define	BULKSTAT_FG_IGET	0x1	/* Go through the buffer cache */
#define	BULKSTAT_FG_QUICK	0x2	/* No iget, walk the dinode cluster */
#define BULKSTAT_FG_VFSLOCKED	0x4	/* Already have vfs lock */

/*
 * Return stat information in bulk (by-inode) for the filesystem.
 */
int					/* error status */
xfs_bulkstat(
	xfs_mount_t	*mp,		/* mount point for filesystem */
	xfs_ino_t	*lastino,	/* last inode returned */
	int		*count,		/* size of buffer/count returned */
	bulkstat_one_pf formatter,	/* func that'd fill a single buf */
	void		*private_data,	/* private data for formatter */
	size_t		statstruct_size,/* sizeof struct that we're filling */
	char		__user *ubuffer,/* buffer with inode stats */
	int		flags,		/* flag to control access method */
	int		*done);		/* 1 if there're more stats to get */

int
xfs_bulkstat_single(
	xfs_mount_t		*mp,
	xfs_ino_t		*lastinop,
	char			__user *buffer,
	int			*done);

int
xfs_bulkstat_one(
	xfs_mount_t		*mp,
	xfs_ino_t		ino,
	void			__user *buffer,
	int			ubsize,
	void			*private_data,
	xfs_daddr_t		bno,
	int			*ubused,
	void			*dibuff,
	int			*stat);

int					/* error status */
xfs_inumbers(
	xfs_mount_t		*mp,	/* mount point for filesystem */
	xfs_ino_t		*last,	/* last inode returned */
	int			*count,	/* size of buffer/count returned */
	xfs_inogrp_t		__user *buffer);/* buffer with inode info */

#endif	/* __XFS_ITABLE_H__ */


text:
<?php

namespace Zend\Mvc\I18n\Router;

use Interop\Container\ContainerInterface;
use Zend\I18n\Translator\TranslatorInterface;
use Zend\ServiceManager\DelegatorFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class HttpRouterDelegatorFactory implements DelegatorFactoryInterface
{
    /**
     * Decorate the HttpRouter factory.
     *
     * If the HttpRouter factory returns a TranslatorAwareTreeRouteStack, we
     * should inject it with a translator.
     *
     * If the MvcTranslator service is available, that translator is used.
     * If the TranslatorInterface service is available, that translator is used.
     *
     * Otherwise, we disable translation in the instance before returning it.
     *
     * @param ContainerInterface $container
     * @param string $name
     * @param callable $callback
     * @param null|arry $options
     * @return \Zend\Router\RouteStackInterface|TranslatorAwareTreeRouteStack
     */
    public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null)
    {
        $router = $callback();

        if (! $router instanceof TranslatorAwareTreeRouteStack) {
            return $router;
        }

        if ($container->has('MvcTranslator')) {
            $router->setTranslator($container->get('MvcTranslator'));
            return $router;
        }

        if ($container->has(TranslatorInterface::class)) {
            $router->setTranslator($container->get(TranslatorInterface::class));
            return $router;
        }

        $router->setTranslatorEnabled(false);

        return $router;
    }

    /**
     * zend-servicemanager v2 compabibility
     *
     * @param ServiceLocatorInterface $container
     * @param string $name
     * @param string $requestedName
     * @param callable $callback
     * @return \Zend\Router\RouteStackInterface|TranslatorAwareTreeRouteStack
     */
    public function createDelegatorWithName(ServiceLocatorInterface $container, $name, $requestedName, $callback)
    {
        return $this($container, $requestedName, $callback);
    }
}


text:
using System;
using System.Collections;

using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Asn1.X509
{
    /**
     * The extendedKeyUsage object.
     * <pre>
     *      extendedKeyUsage ::= Sequence SIZE (1..MAX) OF KeyPurposeId
     * </pre>
     */
    public class ExtendedKeyUsage
        : Asn1Encodable
    {
        internal readonly IDictionary usageTable = Platform.CreateHashtable();
        internal readonly Asn1Sequence seq;

		public static ExtendedKeyUsage GetInstance(
            Asn1TaggedObject	obj,
            bool				explicitly)
        {
            return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
        }

		public static ExtendedKeyUsage GetInstance(
            object obj)
        {
            if (obj is ExtendedKeyUsage)
            {
                return (ExtendedKeyUsage) obj;
            }

			if (obj is Asn1Sequence)
            {
                return new ExtendedKeyUsage((Asn1Sequence) obj);
            }

			if (obj is X509Extension)
			{
				return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj));
			}

			throw new ArgumentException("Invalid ExtendedKeyUsage: " + obj.GetType().Name);
        }

		private ExtendedKeyUsage(
            Asn1Sequence seq)
        {
            this.seq = seq;

			foreach (object o in seq)
			{
				if (!(o is DerObjectIdentifier))
					throw new ArgumentException("Only DerObjectIdentifier instances allowed in ExtendedKeyUsage.");

				this.usageTable.Add(o, o);
            }
        }

		public ExtendedKeyUsage(
			params KeyPurposeID[] usages)
		{
			this.seq = new DerSequence(usages);

			foreach (KeyPurposeID usage in usages)
			{
				this.usageTable.Add(usage, usage);
			}
		}

#if !SILVERLIGHT
        [Obsolete]
        public ExtendedKeyUsage(
            ArrayList usages)
            : this((IEnumerable)usages)
        {
        }
#endif

        public ExtendedKeyUsage(
            IEnumerable usages)
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

			foreach (Asn1Object o in usages)
            {
				v.Add(o);

				this.usageTable.Add(o, o);
            }

			this.seq = new DerSequence(v);
        }

		public bool HasKeyPurposeId(
            KeyPurposeID keyPurposeId)
        {
            return usageTable[keyPurposeId] != null;
        }

#if !SILVERLIGHT
        [Obsolete("Use 'GetAllUsages'")]
        public ArrayList GetUsages()
        {
            return new ArrayList(usageTable.Values);
        }
#endif

        /**
		 * Returns all extended key usages.
		 * The returned ArrayList contains DerObjectIdentifier instances.
		 * @return An ArrayList with all key purposes.
		 */
		public IList GetAllUsages()
		{
			return Platform.CreateArrayList(usageTable.Values);
		}

        public int Count
		{
			get { return usageTable.Count; }
		}

		public override Asn1Object ToAsn1Object()
        {
            return seq;
        }
    }
}


text:
using namespace opentelemetry::sdk::metrics;
namespace nostd = opentelemetry::nostd;
TEST(Aggregation, LongSumAggregation)
{
  LongSumAggregation aggr(true);
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<SumPointData>(data));
  auto sum_data = nostd::get<SumPointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<int64_t>(sum_data.value_));
  EXPECT_EQ(nostd::get<int64_t>(sum_data.value_), 0);
  aggr.Aggregate((int64_t)12, {});
  aggr.Aggregate((int64_t)0, {});
  sum_data = nostd::get<SumPointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<int64_t>(sum_data.value_), 12);
}

TEST(Aggregation, DoubleSumAggregation)
{
  DoubleSumAggregation aggr(true);
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<SumPointData>(data));
  auto sum_data = nostd::get<SumPointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<double>(sum_data.value_));
  EXPECT_EQ(nostd::get<double>(sum_data.value_), 0);
  aggr.Aggregate(12.0, {});
  aggr.Aggregate(1.0, {});
  sum_data = nostd::get<SumPointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<double>(sum_data.value_), 13.0);
}

TEST(Aggregation, LongLastValueAggregation)
{
  LongLastValueAggregation aggr;
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<LastValuePointData>(data));
  auto lastvalue_data = nostd::get<LastValuePointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<int64_t>(lastvalue_data.value_));
  EXPECT_EQ(lastvalue_data.is_lastvalue_valid_, false);
  aggr.Aggregate((int64_t)12, {});
  aggr.Aggregate((int64_t)1, {});
  lastvalue_data = nostd::get<LastValuePointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<int64_t>(lastvalue_data.value_), 1.0);
}

TEST(Aggregation, DoubleLastValueAggregation)
{
  DoubleLastValueAggregation aggr;
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<LastValuePointData>(data));
  auto lastvalue_data = nostd::get<LastValuePointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<double>(lastvalue_data.value_));
  EXPECT_EQ(lastvalue_data.is_lastvalue_valid_, false);
  aggr.Aggregate(12.0, {});
  aggr.Aggregate(1.0, {});
  lastvalue_data = nostd::get<LastValuePointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<double>(lastvalue_data.value_), 1.0);
}

TEST(Aggregation, LongHistogramAggregation)
{
  LongHistogramAggregation aggr;
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<HistogramPointData>(data));
  auto histogram_data = nostd::get<HistogramPointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<int64_t>(histogram_data.sum_));
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.sum_), 0);
  EXPECT_EQ(histogram_data.count_, 0);
  aggr.Aggregate((int64_t)12, {});   // lies in fourth bucket
  aggr.Aggregate((int64_t)100, {});  // lies in eight bucket
  histogram_data = nostd::get<HistogramPointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.min_), 12);
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.max_), 100);
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.sum_), 112);
  EXPECT_EQ(histogram_data.count_, 2);
  EXPECT_EQ(histogram_data.counts_[3], 1);
  EXPECT_EQ(histogram_data.counts_[7], 1);
  aggr.Aggregate((int64_t)13, {});   // lies in fourth bucket
  aggr.Aggregate((int64_t)252, {});  // lies in ninth bucket
  histogram_data = nostd::get<HistogramPointData>(aggr.ToPoint());
  EXPECT_EQ(histogram_data.count_, 4);
  EXPECT_EQ(histogram_data.counts_[3], 2);
  EXPECT_EQ(histogram_data.counts_[8], 1);
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.min_), 12);
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.max_), 252);

  // Merge
  LongHistogramAggregation aggr1;
  aggr1.Aggregate((int64_t)1, {});
  aggr1.Aggregate((int64_t)11, {});
  aggr1.Aggregate((int64_t)26, {});

  LongHistogramAggregation aggr2;
  aggr2.Aggregate((int64_t)2, {});
  aggr2.Aggregate((int64_t)3, {});
  aggr2.Aggregate((int64_t)13, {});
  aggr2.Aggregate((int64_t)28, {});
  aggr2.Aggregate((int64_t)105, {});

  auto aggr3     = aggr1.Merge(aggr2);
  histogram_data = nostd::get<HistogramPointData>(aggr3->ToPoint());

  EXPECT_EQ(histogram_data.count_, 8);      // 3 each from aggr1 and aggr2
  EXPECT_EQ(histogram_data.counts_[1], 3);  // 1, 2, 3
  EXPECT_EQ(histogram_data.counts_[3], 2);  // 11, 13
  EXPECT_EQ(histogram_data.counts_[4], 2);  // 25, 28
  EXPECT_EQ(histogram_data.counts_[7], 1);  // 105
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.min_), 1);
  EXPECT_EQ(nostd::get<int64_t>(histogram_data.max_), 105);

  // Diff
  auto aggr4     = aggr1.Diff(aggr2);
  histogram_data = nostd::get<HistogramPointData>(aggr4->ToPoint());
  EXPECT_EQ(histogram_data.count_, 2);      // aggr2:5 - aggr1:3
  EXPECT_EQ(histogram_data.counts_[1], 1);  // aggr2(2, 3) - aggr1(1)
  EXPECT_EQ(histogram_data.counts_[3], 0);  // aggr2(13) - aggr1(11)
  EXPECT_EQ(histogram_data.counts_[4], 0);  // aggr2(28) - aggr1(25)
  EXPECT_EQ(histogram_data.counts_[7], 1);  // aggr2(105) - aggr1(0)
}

TEST(Aggregation, LongHistogramAggregationBoundaries)
{
  std::shared_ptr<opentelemetry::sdk::metrics::HistogramAggregationConfig> aggregation_config{
      new opentelemetry::sdk::metrics::HistogramAggregationConfig};
  std::list<double> user_boundaries = {0.0,   50.0,   100.0,  250.0,  500.0,
                                       750.0, 1000.0, 2500.0, 5000.0, 10000.0};
  aggregation_config->boundaries_   = user_boundaries;
  LongHistogramAggregation aggr{aggregation_config.get()};
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<HistogramPointData>(data));
  auto histogram_data = nostd::get<HistogramPointData>(data);
  EXPECT_EQ(histogram_data.boundaries_, user_boundaries);
}

TEST(Aggregation, DoubleHistogramAggregationBoundaries)
{
  std::shared_ptr<opentelemetry::sdk::metrics::HistogramAggregationConfig> aggregation_config{
      new opentelemetry::sdk::metrics::HistogramAggregationConfig};
  std::list<double> user_boundaries = {0.0,   50.0,   100.0,  250.0,  500.0,
                                       750.0, 1000.0, 2500.0, 5000.0, 10000.0};
  aggregation_config->boundaries_   = user_boundaries;
  DoubleHistogramAggregation aggr{aggregation_config.get()};
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<HistogramPointData>(data));
  auto histogram_data = nostd::get<HistogramPointData>(data);
  EXPECT_EQ(histogram_data.boundaries_, user_boundaries);
}

TEST(Aggregation, DoubleHistogramAggregation)
{
  DoubleHistogramAggregation aggr;
  auto data = aggr.ToPoint();
  ASSERT_TRUE(nostd::holds_alternative<HistogramPointData>(data));
  auto histogram_data = nostd::get<HistogramPointData>(data);
  ASSERT_TRUE(nostd::holds_alternative<double>(histogram_data.sum_));
  EXPECT_EQ(nostd::get<double>(histogram_data.sum_), 0);
  EXPECT_EQ(histogram_data.count_, 0);
  aggr.Aggregate(12.0, {});   // lies in fourth bucket
  aggr.Aggregate(100.0, {});  // lies in eight bucket
  histogram_data = nostd::get<HistogramPointData>(aggr.ToPoint());
  EXPECT_EQ(nostd::get<double>(histogram_data.sum_), 112);
  EXPECT_EQ(histogram_data.count_, 2);
  EXPECT_EQ(histogram_data.counts_[3], 1);
  EXPECT_EQ(histogram_data.counts_[7], 1);
  EXPECT_EQ(nostd::get<double>(histogram_data.min_), 12);
  EXPECT_EQ(nostd::get<double>(histogram_data.max_), 100);
  aggr.Aggregate(13.0, {});   // lies in fourth bucket
  aggr.Aggregate(252.0, {});  // lies in ninth bucket
  histogram_data = nostd::get<HistogramPointData>(aggr.ToPoint());
  EXPECT_EQ(histogram_data.count_, 4);
  EXPECT_EQ(histogram_data.counts_[3], 2);
  EXPECT_EQ(histogram_data.counts_[8], 1);
  EXPECT_EQ(nostd::get<double>(histogram_data.sum_), 377);
  EXPECT_EQ(nostd::get<double>(histogram_data.min_), 12);
  EXPECT_EQ(nostd::get<double>(histogram_data.max_), 252);

  // Merge
  DoubleHistogramAggregation aggr1;
  aggr1.Aggregate(1.0, {});
  aggr1.Aggregate(11.0, {});
  aggr1.Aggregate(25.1, {});

  DoubleHistogramAggregation aggr2;
  aggr2.Aggregate(2.0, {});
  aggr2.Aggregate(3.0, {});
  aggr2.Aggregate(13.0, {});
  aggr2.Aggregate(28.1, {});
  aggr2.Aggregate(105.0, {});

  auto aggr3     = aggr1.Merge(aggr2);
  histogram_data = nostd::get<HistogramPointData>(aggr3->ToPoint());

  EXPECT_EQ(histogram_data.count_, 8);      // 3 each from aggr1 and aggr2
  EXPECT_EQ(histogram_data.counts_[1], 3);  // 1.0, 2.0, 3.0
  EXPECT_EQ(histogram_data.counts_[3], 2);  // 11.0, 13.0
  EXPECT_EQ(histogram_data.counts_[4], 2);  // 25.1, 28.1
  EXPECT_EQ(histogram_data.counts_[7], 1);  // 105.0
  EXPECT_EQ(nostd::get<double>(histogram_data.min_), 1);
  EXPECT_EQ(nostd::get<double>(histogram_data.max_), 105);

  // Diff
  auto aggr4     = aggr1.Diff(aggr2);
  histogram_data = nostd::get<HistogramPointData>(aggr4->ToPoint());
  EXPECT_EQ(histogram_data.count_, 2);      // aggr2:5 - aggr1:3
  EXPECT_EQ(histogram_data.counts_[1], 1);  // aggr2(2.0, 3.0) - aggr1(1.0)
  EXPECT_EQ(histogram_data.counts_[3], 0);  // aggr2(13.0) - aggr1(11.0)
  EXPECT_EQ(histogram_data.counts_[4], 0);  // aggr2(28.1) - aggr1(25.1)
  EXPECT_EQ(histogram_data.counts_[7], 1);  // aggr2(105.0) - aggr1(0)
}


text:
/*
 * Licensed Materials - Property of IBM
 * RMI-IIOP v1.0
 * Copyright IBM Corp. 1998 1999  All Rights Reserved
 *
 */

package com.sun.corba.se.impl.io;

import java.lang.reflect.Field;
import java.lang.Comparable;
import java.util.Hashtable;

import sun.corba.Bridge ;
import java.security.AccessController ;
import java.security.PrivilegedAction ;

/**
 * A description of a field in a serializable class.
 * A array of these is used to declare the persistent fields of
 * a class.
 *
 */
public class ObjectStreamField implements Comparable
{
    private static final Bridge bridge =
        (Bridge)AccessController.doPrivileged(
            new PrivilegedAction() {
                public Object run() {
                    return Bridge.get() ;
                }
            }
        ) ;

    /**
     * Create a named field with the specified type.
     */
    ObjectStreamField(String n, Class clazz) {
        name = n;
        this.clazz = clazz;

        // Compute the typecode for easy switching
        if (clazz.isPrimitive()) {
            if (clazz == Integer.TYPE) {
                type = 'I';
            } else if (clazz == Byte.TYPE) {
                type = 'B';
            } else if (clazz == Long.TYPE) {
                type = 'J';
            } else if (clazz == Float.TYPE) {
                type = 'F';
            } else if (clazz == Double.TYPE) {
                type = 'D';
            } else if (clazz == Short.TYPE) {
                type = 'S';
            } else if (clazz == Character.TYPE) {
                type = 'C';
            } else if (clazz == Boolean.TYPE) {
                type = 'Z';
            }
        } else if (clazz.isArray()) {
            type = '[';
            typeString = ObjectStreamClass.getSignature(clazz);
        } else {
            type = 'L';
            typeString = ObjectStreamClass.getSignature(clazz);
        }

        if (typeString != null)
            signature = typeString;
        else
            signature = String.valueOf(type);

    }

    ObjectStreamField(Field field) {
        this(field.getName(), field.getType());
        setField( field ) ;
    }

    /**
     * Create an ObjectStreamField containing a reflected Field.
     */
    ObjectStreamField(String n, char t, Field f, String ts)
    {
        name = n;
        type = t;
        setField( f ) ;
        typeString = ts;

        if (typeString != null)
            signature = typeString;
        else
            signature = String.valueOf(type);

    }

    /**
     * Get the name of this field.
     */
    public String getName() {
        return name;
    }

    /**
     * Get the type of the field.
     */
    public Class getType() {
        if (clazz != null)
            return clazz;
        switch (type) {
        case 'B': clazz = Byte.TYPE;
            break;
        case 'C': clazz = Character.TYPE;
            break;
        case 'S': clazz = Short.TYPE;
            break;
        case 'I': clazz = Integer.TYPE;
            break;
        case 'J': clazz = Long.TYPE;
            break;
        case 'F': clazz = Float.TYPE;
            break;
        case 'D': clazz = Double.TYPE;
            break;
        case 'Z': clazz = Boolean.TYPE;
            break;
        case '[':
        case 'L':
            clazz = Object.class;
            break;
        }

        return clazz;
    }

    public char getTypeCode() {
        return type;
    }

    public String getTypeString() {
        return typeString;
    }

    Field getField() {
        return field;
    }

    void setField(Field field) {
        this.field = field;
        this.fieldID = bridge.objectFieldOffset( field ) ;
    }

    /*
     * Default constructor creates an empty field.
     * Usually used just to get to the sort functions.
     */
    ObjectStreamField() {
    }

    /**
     * test if this field is a primitive or not.
     */
    public boolean isPrimitive() {
        return (type != '[' && type != 'L');
    }

    /**
     * Compare this with another ObjectStreamField.
     * return -1 if this is smaller, 0 if equal, 1 if greater
     * types that are primitives are "smaller" than objects.
     * if equal, the names are compared.
     */
    public int compareTo(Object o) {
        ObjectStreamField f2 = (ObjectStreamField)o;
        boolean thisprim = (this.typeString == null);
        boolean otherprim = (f2.typeString == null);

        if (thisprim != otherprim) {
            return (thisprim ? -1 : 1);
        }
        return this.name.compareTo(f2.name);
    }

    /**
     * Compare the types of two class descriptors.
     * The match if they have the same primitive types.
     * or if they are both objects and the object types match.
     */
    public boolean typeEquals(ObjectStreamField other) {
        if (other == null || type != other.type)
            return false;

        /* Return true if the primitive types matched */
        if (typeString == null && other.typeString == null)
            return true;

        return ObjectStreamClass.compareClassNames(typeString,
                                                   other.typeString,
                                                   '/');
    }

    /* Returns the signature of the Field.
     *
     */
    public String getSignature() {

        return signature;

    }

    /**
     * Return a string describing this field.
     */
    public String toString() {
        if (typeString != null)
            return typeString + " " + name;
        else
            return type + " " + name;
    }

    public Class getClazz() {
        return clazz;
    }

    /* Returns the Field ID
     *
     */
    public long getFieldID() {
        return fieldID ;
    }

    private String name;                // the name of the field
    private char type;                  // type first byte of the type signature
    private Field field;                // Reflected field
    private String typeString;          // iff object, typename
    private Class clazz;                // the type of this field, if has been resolved

    // the next 2 things are RMI-IIOP specific, it can be easily
    // removed, if we can figure out all place where there are dependencies
    // to this.  Signature is esentially equal to typestring. Then
    // essentially we can use the java.io.ObjectStreamField as such.

    private String signature;   // the signature of the field
    private long fieldID = Bridge.INVALID_FIELD_OFFSET ;
}


text:
import { Request, Response } from 'express';
import * as admin from 'firebase-admin';
import { ClearReportRequest } from '../../common-types';

export async function clearReport(req: Request, res: Response) {
  try {
    const request = req.body as ClearReportRequest;
    // Verify the identify of the currently signed-in user.
    const uid = (
      await admin
        .auth()
        .verifyIdToken(request.idToken, /* checkedRevoked = */ true)
    ).uid;
    const platform = request.platform;
    const documentId = request.documentId;
    const firestore = admin.firestore();
    const document = firestore.doc(
      `users/${uid}/${platform}_reports/${documentId}`
    );
    await deleteDocument(document, firestore);
    res.end();
  } catch (e) {
    console.error('Error clearing repoort: ' + e);
    res.status(500).send('Error clearing report');
  }
}

async function deleteDocument(
  doc: FirebaseFirestore.DocumentReference,
  firestore: FirebaseFirestore.Firestore
) {
  const subcollections = await doc.listCollections();
  for (const collection of subcollections) {
    await deleteCollection(collection, firestore);
  }
  await doc.delete();
}

async function deleteCollection(
  collection: FirebaseFirestore.CollectionReference,
  firestore: FirebaseFirestore.Firestore
) {
  const docs = await collection.listDocuments();
  if (docs.length === 0) {
    return;
  }
  for (const doc of docs) {
    await deleteDocument(doc, firestore);
  }
}


text:
export function onmessage (msg: any): void;
export function setupWebsocket (msg: any): void;
export var comm: any;


text:
/**
 */
package gluemodel.CIM.IEC61970.LoadModel.impl;

import gluemodel.CIM.IEC61970.LoadModel.ConformLoad;
import gluemodel.CIM.IEC61970.LoadModel.ConformLoadGroup;
import gluemodel.CIM.IEC61970.LoadModel.ConformLoadSchedule;
import gluemodel.CIM.IEC61970.LoadModel.LoadModelPackage;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'Conform Load Group'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link gluemodel.CIM.IEC61970.LoadModel.impl.ConformLoadGroupImpl#getEnergyConsumers Energy Consumers}

 *
{@link gluemodel.CIM.IEC61970.LoadModel.impl.ConformLoadGroupImpl#getConformLoadSchedules Conform Load Schedules}

 *

 *
 * @generated
 */
public class ConformLoadGroupImpl extends LoadGroupImpl implements ConformLoadGroup {
	/**
	 * The cached value of the '{@link #getEnergyConsumers() Energy Consumers}' reference list.
	 *
	 *
	 * @see #getEnergyConsumers()
	 * @generated
	 * @ordered
	 */
	protected EList<ConformLoad> energyConsumers;

	/**
	 * The cached value of the '{@link #getConformLoadSchedules() Conform Load Schedules}' reference list.
	 *
	 *
	 * @see #getConformLoadSchedules()
	 * @generated
	 * @ordered
	 */
	protected EList<ConformLoadSchedule> conformLoadSchedules;

	/**
	 *
	 *
	 * @generated
	 */
	protected ConformLoadGroupImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return LoadModelPackage.Literals.CONFORM_LOAD_GROUP;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EList<ConformLoad> getEnergyConsumers() {
		if (energyConsumers == null) {
			energyConsumers = new EObjectWithInverseResolvingEList<ConformLoad>(ConformLoad.class, this, LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS, LoadModelPackage.CONFORM_LOAD__LOAD_GROUP);
		}
		return energyConsumers;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public EList<ConformLoadSchedule> getConformLoadSchedules() {
		if (conformLoadSchedules == null) {
			conformLoadSchedules = new EObjectWithInverseResolvingEList<ConformLoadSchedule>(ConformLoadSchedule.class, this, LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES, LoadModelPackage.CONFORM_LOAD_SCHEDULE__CONFORM_LOAD_GROUP);
		}
		return conformLoadSchedules;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getEnergyConsumers()).basicAdd(otherEnd, msgs);
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				return ((InternalEList<InternalEObject>)(InternalEList<?>)getConformLoadSchedules()).basicAdd(otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				return ((InternalEList<?>)getEnergyConsumers()).basicRemove(otherEnd, msgs);
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				return ((InternalEList<?>)getConformLoadSchedules()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				return getEnergyConsumers();
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				return getConformLoadSchedules();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				getEnergyConsumers().clear();
				getEnergyConsumers().addAll((Collection<? extends ConformLoad>)newValue);
				return;
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				getConformLoadSchedules().clear();
				getConformLoadSchedules().addAll((Collection<? extends ConformLoadSchedule>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				getEnergyConsumers().clear();
				return;
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				getConformLoadSchedules().clear();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case LoadModelPackage.CONFORM_LOAD_GROUP__ENERGY_CONSUMERS:
				return energyConsumers != null && !energyConsumers.isEmpty();
			case LoadModelPackage.CONFORM_LOAD_GROUP__CONFORM_LOAD_SCHEDULES:
				return conformLoadSchedules != null && !conformLoadSchedules.isEmpty();
		}
		return super.eIsSet(featureID);
	}

} //ConformLoadGroupImpl


text:
package org.anstis.client.grid.model.mergable;

import org.anstis.client.grid.model.IGridCell;

/**
 * Extension to a regular non-merged grid to support merged cells.
 * @param <T> The Type of value
 */
public interface IMergableGridCell<T> extends IGridCell<T> {

    /**
     * Whether the cell in a merged state
     * @return true if merged
     */
    boolean isMerged();

    /**
     * Return the number of cells merged into this cell. For cells that are at the top
     * of a merged block this should be the number of merged cells, including this cell.
     * For cells that are not the top of a merged block but are contained in a merged
     * block this should return zero. For non-merged cells this should return one.
     * @return The number of cells merged into this cell, or zero if part of a merged block or one if not merged.
     */
    int getMergedCellCount();

    /**
     * Whether the cell is collapsed. For cells that are at the top of a collapsed
     * block this should return false. For cells that are not the top of a collapsed block
     * but are contained in a collapsed block this should return false.
     * @return true is collapsed.
     */
    boolean isCollapsed();

    /**
     * Collapse the cell.
     */
    void collapse();

    /**
     * Expand the cell.
     */
    void expand();

    /**
     * Reset the cell to a non-merged, non-collapsed state.
     */
    void reset();

}


text:
namespace sling {
namespace task {

// Task for training models using multiple workers.
class LearnerTask : public Process {
 public:
  // Run training using workers.
  void Train(Task *task, myelin::Network *model);

  // Signal completion of training epoch. Return true when training is done.
  bool EpochCompleted();

  // Worker thread for training model.
  virtual void Worker(int index, myelin::Network *model) = 0;

  // Model evaluation. Return false to end training.
  virtual bool Evaluate(int64 epoch, myelin::Network *model) { return true; }

  // Checkpoint model.
  virtual void Checkpoint(int64 epoch, myelin::Network *model) {}

 private:
  // Total number of training epochs.
  int64 epochs_ = 10000;

  // Number of epochs between model evaluation.
  int64 report_interval_ = 100;

  // Number of seconds between starting up workers.
  int64 rampup_ = 0;

  // Number of seconds between starting the first and the rest of the workers.
  int64 warmup_ = 0;

  // Current number of completed epochs.
  std::atomic<int64> epoch_{0};

  // Flag set when training is done.
  bool done_ = false;

  // Signal model evaluation or completions.
  Mutex eval_mu_;
  std::condition_variable eval_model_;

  // Checkpoint model at regular intervals.
  int checkpoint_interval_ = 100000;
  int last_checkpoint_ = 0;

  // Staticstics.
  Counter *num_workers_ = nullptr;
  Counter *num_epochs_ = nullptr;
};

// Initialize optimizer from task parameters.
myelin::Optimizer *GetOptimizer(Task *task);

}  // namespace task
}  // namespace sling

#endif  // SLING_TASK_LEARNER_H_


text:
  /** Provides a set of static properties to access commonly used schedulers. */
  var Scheduler = Rx.Scheduler = (function () {

    function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
      this.now = now;
      this._schedule = schedule;
      this._scheduleRelative = scheduleRelative;
      this._scheduleAbsolute = scheduleAbsolute;
    }

    function invokeRecImmediate(scheduler, pair) {
      var state = pair.first, action = pair.second, group = new CompositeDisposable(),
      recursiveAction = function (state1) {
        action(state1, function (state2) {
          var isAdded = false, isDone = false,
          d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
            if (isAdded) {
              group.remove(d);
            } else {
              isDone = true;
            }
            recursiveAction(state3);
            return disposableEmpty;
          });
          if (!isDone) {
            group.add(d);
            isAdded = true;
          }
        });
      };
      recursiveAction(state);
      return group;
    }

    function invokeRecDate(scheduler, pair, method) {
      var state = pair.first, action = pair.second, group = new CompositeDisposable(),
      recursiveAction = function (state1) {
        action(state1, function (state2, dueTime1) {
          var isAdded = false, isDone = false,
          d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
            if (isAdded) {
              group.remove(d);
            } else {
              isDone = true;
            }
            recursiveAction(state3);
            return disposableEmpty;
          });
          if (!isDone) {
            group.add(d);
            isAdded = true;
          }
        });
      };
      recursiveAction(state);
      return group;
    }

    function invokeAction(scheduler, action) {
      action();
      return disposableEmpty;
    }

    var schedulerProto = Scheduler.prototype;

    /**
     * Schedules an action to be executed.
     * @param {Function} action Action to execute.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
     */
    schedulerProto.schedule = function (action) {
      return this._schedule(action, invokeAction);
    };

    /**
     * Schedules an action to be executed.
     * @param state State passed to the action to be executed.
     * @param {Function} action Action to be executed.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
     */
    schedulerProto.scheduleWithState = function (state, action) {
      return this._schedule(state, action);
    };

    /**
     * Schedules an action to be executed after the specified relative due time.
     * @param {Function} action Action to execute.
     * @param {Number} dueTime Relative time after which to execute the action.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
     */
    schedulerProto.scheduleWithRelative = function (dueTime, action) {
      return this._scheduleRelative(action, dueTime, invokeAction);
    };

    /**
     * Schedules an action to be executed after dueTime.
     * @param state State passed to the action to be executed.
     * @param {Function} action Action to be executed.
     * @param {Number} dueTime Relative time after which to execute the action.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
     */
    schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
      return this._scheduleRelative(state, dueTime, action);
    };

    /**
     * Schedules an action to be executed at the specified absolute due time.
     * @param {Function} action Action to execute.
     * @param {Number} dueTime Absolute time at which to execute the action.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
      */
    schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
      return this._scheduleAbsolute(action, dueTime, invokeAction);
    };

    /**
     * Schedules an action to be executed at dueTime.
     * @param {Mixed} state State passed to the action to be executed.
     * @param {Function} action Action to be executed.
     * @param {Number}dueTime Absolute time at which to execute the action.
     * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
     */
    schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
      return this._scheduleAbsolute(state, dueTime, action);
    };

    /** Gets the current time according to the local machine's system clock. */
    Scheduler.now = defaultNow;

    /**
     * Normalizes the specified TimeSpan value to a positive value.
     * @param {Number} timeSpan The time span value to normalize.
     * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
     */
    Scheduler.normalize = function (timeSpan) {
      timeSpan < 0 && (timeSpan = 0);
      return timeSpan;
    };

    return Scheduler;
  }());

  var normalizeTime = Scheduler.normalize;


text:
package main;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class Probability {

	private double mathExpectation;
	private double standDeviation;
	public double probalityOfClass;
	public ArrayList<Integer> randomVariable;

	Probability(ArrayList<Integer> randomVariables, double probalityOfClass){
		this.randomVariable = new ArrayList<Integer>( new HashSet<Integer>(randomVariables));
		Collections.sort(this.randomVariable);
		this.probalityOfClass = probalityOfClass;
		this.mathExpectation = mathematicalExpectation(randomVariables);
		this.standDeviation = standardDeviation(randomVariables);
	}

	private double mathematicalExpectation(ArrayList<Integer> randomVariables){
		int sum = 0;
		for(int i=0; i<randomVariables.size(); i++){
			sum+=randomVariables.get(i);
		}
		return sum/randomVariables.size();
	}

	private double standardDeviation(ArrayList<Integer> randomVariables){
		double sum = 0;
		for(int i=0; i<randomVariables.size(); i++){
			sum+=Math.pow(randomVariables.get(i)-mathExpectation,2);
		}
		return Math.sqrt(sum/randomVariables.size());
	}

	public double probabilityDensity(double point){
		double first = (standDeviation*Math.sqrt(Math.PI*2));
		double second = Math.exp(Math.pow((point-mathExpectation)/standDeviation,2)/-2);
		return second/first;
	}
}


text:
package io.github.sunxu3074.shoppoingdemo.activity;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import io.github.sunxu3074.shoppoingdemo.R;

public class BaseActivity extends ActionBarActivity {

    private static final int ACTIONBAR_BACKGROUND = R.color.actionbar_background;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);

        initActionBar();

    }

    private void initActionBar() {

        ActionBar actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(ACTIONBAR_BACKGROUND));
        //google的actionbar是分为上下两栏显示的,上面的代码只能设置顶部actionbar的背景色,
        //为了让下面的背景色一致,还需要添加一行代码:
        actionBar.setSplitBackgroundDrawable(new ColorDrawable(ACTIONBAR_BACKGROUND));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_base, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
local pack = require "ejoy2d.spritepack.c"

--	table or number , texture
--	table data

--	return { texture = maxtex, max = maxid, size = capsize, data = block, export = {} }

-- don't release pack_pool
local pack_pool = {}

local spritepack = {}

local TYPE_PICTURE = assert(pack.TYPE_PICTURE)
local TYPE_ANIMATION = assert(pack.TYPE_ANIMATION)
local TYPE_POLYGON = assert(pack.TYPE_POLYGON)
local TYPE_LABEL = assert(pack.TYPE_LABEL)
local TYPE_PANNEL = assert(pack.TYPE_PANNEL)
local TYPE_MATRIX =assert(pack.TYPE_MATRIX)

local function pack_picture(src, ret)
	table.insert(ret , pack.byte(TYPE_PICTURE))
	local n = #src
	table.insert(ret, pack.byte(n))
	local maxid = 0
	for i=1,n do
		local data = src[i]
		local texid = (data.tex or 1) - 1
		if texid > maxid then
			maxid = texid
		end
		table.insert(ret, pack.byte(texid))
		for j=1,8 do
			table.insert(ret, pack.word(data.src[j]))
		end
		for j=1,8 do
			table.insert(ret, pack.int32(data.screen[j]))
		end
	end

	return pack.picture_size(n) , maxid
end

local function pack_polygon(src, ret)
	table.insert(ret , pack.byte(TYPE_POLYGON))
	local n = #src
	table.insert(ret, pack.byte(n))
	local maxid = 0
	local total_point = 0
	for i=1,n do
		local data = src[i]
		local texid = (data.tex or 1) - 1
		if texid > maxid then
			maxid = texid
		end
		table.insert(ret, pack.byte(texid))
		local pn = #data.src
		total_point = total_point + pn
		assert(pn == #data.screen)
		table.insert(ret, pack.byte(pn/2))
		for j=1,pn do
			table.insert(ret, pack.word(data.src[j]))
		end
		for j=1,pn do
			table.insert(ret, pack.int32(data.screen[j]))
		end
	end

	return pack.polygon_size(n, total_point) , maxid
end

local function is_identity( mat )
	if mat == nil then
		return false
	end
	return mat[1] == 1024 and mat[2] == 0 and mat[3] == 0
			and mat[4] == 1024 and mat[5] == 0 and mat[6] == 0
end

local function pack_part(data, ret)
	if type(data) == "number" then
		table.insert(ret, pack.frametag "i")
		table.insert(ret, pack.word(data))

		return pack.part_size()
	else
		local tag = "i"
		assert(data.index, "frame need an index")
		local mat = data.mat
		if type(mat) == "number" then
			tag = tag .. "M"
		else
			if is_identity(mat) then
				mat = nil
			end
			if mat then
				tag = tag .. "m"
			end
		end
		if data.color and data.color ~= 0xffffffff then
			tag = tag .. "c"
		end
		if data.add and data.add ~= 0 then
			tag = tag .. "a"
		end
		if data.touch then
			tag = tag .. "t"
		end
		table.insert(ret, pack.frametag(tag))

		table.insert(ret, pack.word(data.index))
		if mat then
			if type(mat) == "number" then
				table.insert(ret, pack.int32(mat))
			else
				for i=1,6 do
					table.insert(ret, pack.int32(mat[i]))
				end
			end
		end
		if data.color and data.color ~= 0xffffffff then
			table.insert(ret, pack.color(data.color))
		end
		if data.add and data.add ~= 0 then
			table.insert(ret, pack.color(data.add))
		end
		if data.touch then
			table.insert(ret, pack.word(1))
		end
		return pack.part_size(mat)
	end
end

local function pack_frame(data, ret)
	local size = 0
	table.insert(ret, pack.word(#data))
	for _,v in ipairs(data) do
		local psize = pack_part(v, ret)
		size = size + psize
	end
	return size
end

local function pack_label(data, ret)
	table.insert(ret, pack.byte(TYPE_LABEL))
	table.insert(ret, pack.byte(data.align))
	table.insert(ret, pack.color(data.color))
	table.insert(ret, pack.word(data.size))
	table.insert(ret, pack.word(data.width))
	table.insert(ret, pack.word(data.height))
    table.insert(ret, pack.byte(data.noedge and 0 or 1))
    table.insert(ret, pack.byte(data.space_w or 0))
    table.insert(ret, pack.byte(data.space_h or 0))
    table.insert(ret, pack.byte(data.auto_size or 0))
	return pack.label_size()
end

local function pack_pannel(data, ret)
	table.insert(ret, pack.byte(TYPE_PANNEL))
	table.insert(ret, pack.int32(data.width))
	table.insert(ret, pack.int32(data.height))
	table.insert(ret, pack.byte(data.scissor and 1 or 0))
	return pack.pannel_size()
end

local function pack_animation(data, ret)
	local size = 0
	local max_id = 0
	table.insert(ret , pack.byte(TYPE_ANIMATION))
	local component = assert(data.component)
	table.insert(ret , pack.word(#component))
	for _, v in ipairs(component) do
		if v.id and v.id > max_id then
			max_id = v.id
		end
		if v.id == nil then
			assert(v.name, "Anchor need a name")
			v.id = 0xffff	-- Anchor use id 0xffff
		end
		table.insert(ret, pack.word(v.id))
		table.insert(ret, pack.string(v.name))
		size = size + pack.string_size(v.name)
	end
	table.insert(ret, pack.word(#data))	-- action number
	local frame = 0
	for _, v in ipairs(data) do
		table.insert(ret, pack.string(v.action))
		table.insert(ret, pack.word(#v))
		size = size + pack.string_size(v.action)
		frame = frame + #v
	end
	table.insert(ret, pack.word(frame))	-- total frame
	size = size + pack.animation_size(frame, #component, #data)
	for _, v in ipairs(data) do
		for _, f in ipairs(v) do
			local fsz = pack_frame(f, ret)
			size = size + fsz
		end
	end

	return size, max_id
end

function spritepack.pack( data )
	local ret = { texture = 0, maxid = 0, size = 0 , data = {}, export = {} }
	local ani_maxid = 0

	for _,v in ipairs(data) do
		if v.type == "matrix" then
			table.insert(ret.data, pack.word(0))	-- dummy id for TYPE_MATRIX
			table.insert(ret.data, pack.byte(TYPE_MATRIX))
			local n = #v
			table.insert(ret.data, pack.int32(n))
			for _, mat in ipairs(v) do
				for i=1,6 do
					table.insert(ret.data, pack.int32(mat[i]))
				end
			end
			ret.size = ret.size + n * 24	-- each matrix 24 bytes
		elseif v.type ~= "particle" then
			local id = assert(tonumber(v.id))
			if id > ret.maxid then
				ret.maxid = id
			end
			local exportname = v.export
			if exportname then
				assert(ret.export[exportname] == nil, "Duplicate export name"..exportname)
				ret.export[exportname] = id
			end
			table.insert(ret.data, pack.word(id))
			if v.type == "picture" then
				local sz, texid = pack_picture(v, ret.data)
				ret.size = ret.size + sz
				if texid > ret.texture then
					ret.texture = texid
				end
			elseif v.type == "animation" then
				local sz , maxid = pack_animation(v, ret.data)
				ret.size = ret.size + sz
				if maxid > ani_maxid then
					ani_maxid = maxid
				end
			elseif v.type == "polygon" then
				local sz, texid = pack_polygon(v, ret.data)
				ret.size = ret.size + sz
				if texid > ret.texture then
					ret.texture = texid
				end
			elseif v.type == "label" then
				local sz = pack_label(v, ret.data)
				ret.size = ret.size + sz
			elseif v.type == "pannel" then
				local sz = pack_pannel(v, ret.data)
				ret.size = ret.size + sz
			else
				error ("Unknown type " .. tostring(v.type))
			end
		end
	end

	if ani_maxid > ret.maxid then
		error ("Invalid id in animation ".. ani_maxid)
	end

	ret.texture = ret.texture + 1
	ret.data = table.concat(ret.data)
	ret.size = ret.size + pack.pack_size(ret.maxid, ret.texture)
	return ret
end

function spritepack.export(meta)
	local result = { true }
	table.insert(result, pack.word(meta.maxid))
	table.insert(result, pack.word(meta.texture))
	table.insert(result, pack.int32(meta.size))
	table.insert(result, pack.int32(#meta.data))
	local s = 0
	for k,v in pairs(meta.export) do
		table.insert(result, pack.word(v))
		table.insert(result, pack.string(k))
		s = s + 1
	end
	result[1] = pack.word(s)
	table.insert(result, meta.data)
	return table.concat(result)
end

function spritepack.import(data)
	local meta = { export = {} }
	local export_n, off = pack.import_value(data, 1, 'w')
	meta.maxid , off = pack.import_value(data, off, 'w')
	meta.texture , off = pack.import_value(data, off, 'w')
	meta.size , off = pack.import_value(data, off, 'i')
	meta.data_sz , off = pack.import_value(data, off, 'i')
	for i=1, export_n do
		local id, name
		id, off = pack.import_value(data, off, 'w')
		name, off = pack.import_value(data, off, 's')
		meta.export[name] = id
	end
	meta.data = pack.import_value(data, off, 'p')

	return meta
end

function spritepack.init( name, texture, meta )
	assert(pack_pool[name] == nil , string.format("sprite package [%s] is exist", name))
	if type(texture) == "number" then
		assert(meta.texture == 1)
	else
		assert(meta.texture == #texture)
	end
	pack_pool[name] = {
		cobj = pack.import(texture,meta.maxid,meta.size,meta.data, meta.data_sz),
		export = meta.export,
	}
	meta.data = nil

	return pack_pool[name]
end

function spritepack.query( packname, name )
	local p = assert(pack_pool[packname], "Load package first:"..packname)
	local id
	if type(name) == "number" then
		id = name
	else
		id = p.export[name]
	end
	if not id then
		error(string.format("'%s' is not exist in package %s", name, packname))
	end
	return p.cobj, id
end

return spritepack


text:
package org.supercsv.cellprocessor;

import org.supercsv.cellprocessor.ift.CellProcessor;

/**
 * This processor returns null if it meets the empty String in a column and does not call subsequent processors in its
 * chain. It is a simple customization of the <tt>MagicToken</tt>. If you need to return different values than null,
 * use that class instead.
 *
 * @author Kasper B. Graversen
 */
public class Optional extends Token {
/**
 * Upon meeting the empty string in a column, return null
 */
public Optional() {
	super("", null);
}

/**
 * Upon meeting the empty string in a column, return null
 */
public Optional(final CellProcessor next) {
	super("", null, next);
}
}


text:
<?php namespace Rancherize\Blueprint\Infrastructure\Service\Maker\PhpFpm;
use Rancherize\Exceptions\Exception;

/**
 * Class NoPhpVersionsAvailableException
 * @package Rancherize\Blueprint\Infrastructure\Service\Maker\PhpFpmMaker
 */
class NoPhpVersionsAvailableException extends Exception {

	/**
	 * NoPhpVersionsAvailableException constructor.
	 * @param int $code
	 * @param \Exception $e
	 */
	public function __construct($code = 0, \Exception $e = null) {
		parent::__construct("A PhpFpm Service was requested but no versions are available.", $code, $e);
	}
}


text:
package corehandlers_test

import (
	"testing"

	"bosun.org/_third_party/github.com/stretchr/testify/assert"

	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws"
	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws/awserr"
	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws/corehandlers"
	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws/request"
	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws/service"
	"bosun.org/_third_party/github.com/aws/aws-sdk-go/aws/service/serviceinfo"
	"bosun.org/_third_party/github.com/stretchr/testify/require"
)

var testSvc = func() *service.Service {
	s := &service.Service{
		ServiceInfo: serviceinfo.ServiceInfo{
			Config:      &aws.Config{},
			ServiceName: "mock-service",
			APIVersion:  "2015-01-01",
		},
	}
	return s
}()

type StructShape struct {
	RequiredList   []*ConditionalStructShape          `required:"true"`
	RequiredMap    map[string]*ConditionalStructShape `required:"true"`
	RequiredBool   *bool                              `required:"true"`
	OptionalStruct *ConditionalStructShape

	hiddenParameter *string

	metadataStructureShape
}

type metadataStructureShape struct {
	SDKShapeTraits bool
}

type ConditionalStructShape struct {
	Name           *string `required:"true"`
	SDKShapeTraits bool
}

func TestNoErrors(t *testing.T) {
	input := &StructShape{
		RequiredList: []*ConditionalStructShape{},
		RequiredMap: map[string]*ConditionalStructShape{
			"key1": {Name: aws.String("Name")},
			"key2": {Name: aws.String("Name")},
		},
		RequiredBool:   aws.Bool(true),
		OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")},
	}

	req := testSvc.NewRequest(&request.Operation{}, input, nil)
	corehandlers.ValidateParametersHandler.Fn(req)
	require.NoError(t, req.Error)
}

func TestMissingRequiredParameters(t *testing.T) {
	input := &StructShape{}
	req := testSvc.NewRequest(&request.Operation{}, input, nil)
	corehandlers.ValidateParametersHandler.Fn(req)

	require.Error(t, req.Error)
	assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
	assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList\n- missing required parameter: RequiredMap\n- missing required parameter: RequiredBool", req.Error.(awserr.Error).Message())
}

func TestNestedMissingRequiredParameters(t *testing.T) {
	input := &StructShape{
		RequiredList: []*ConditionalStructShape{{}},
		RequiredMap: map[string]*ConditionalStructShape{
			"key1": {Name: aws.String("Name")},
			"key2": {},
		},
		RequiredBool:   aws.Bool(true),
		OptionalStruct: &ConditionalStructShape{},
	}

	req := testSvc.NewRequest(&request.Operation{}, input, nil)
	corehandlers.ValidateParametersHandler.Fn(req)

	require.Error(t, req.Error)
	assert.Equal(t, "InvalidParameter", req.Error.(awserr.Error).Code())
	assert.Equal(t, "3 validation errors:\n- missing required parameter: RequiredList[0].Name\n- missing required parameter: RequiredMap[\"key2\"].Name\n- missing required parameter: OptionalStruct.Name", req.Error.(awserr.Error).Message())
}

type testInput struct {
	StringField string            `min:"5"`
	PtrStrField *string           `min:"2"`
	ListField   []string          `min:"3"`
	MapField    map[string]string `min:"4"`
}

var testsFieldMin = []struct {
	err awserr.Error
	in  testInput
}{
	{
		err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 5: StringField", nil),
		in:  testInput{StringField: "abcd"},
	},
	{
		err: awserr.New("InvalidParameter", "2 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField", nil),
		in:  testInput{StringField: "abcd", ListField: []string{"a", "b"}},
	},
	{
		err: awserr.New("InvalidParameter", "3 validation errors:\n- field too short, minimum length 5: StringField\n- field too short, minimum length 3: ListField\n- field too short, minimum length 4: MapField", nil),
		in:  testInput{StringField: "abcd", ListField: []string{"a", "b"}, MapField: map[string]string{"a": "a", "b": "b"}},
	},
	{
		err: awserr.New("InvalidParameter", "1 validation errors:\n- field too short, minimum length 2: PtrStrField", nil),
		in:  testInput{StringField: "abcde", PtrStrField: aws.String("v")},
	},
	{
		err: nil,
		in: testInput{StringField: "abcde", PtrStrField: aws.String("value"),
			ListField: []string{"a", "b", "c"}, MapField: map[string]string{"a": "a", "b": "b", "c": "c", "d": "d"}},
	},
}

func TestValidateFieldMinParameter(t *testing.T) {
	for i, c := range testsFieldMin {
		req := testSvc.NewRequest(&request.Operation{}, &c.in, nil)
		corehandlers.ValidateParametersHandler.Fn(req)

		require.Equal(t, c.err, req.Error, "%d case failed", i)
	}
}


text:
package org.atdl4j.ui.javafx.config;

import org.atdl4j.config.AbstractAtdl4jConfiguration;

public class JavaFXAtdl4jConfiguration extends AbstractAtdl4jConfiguration {
	private static String PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX = "org.atdl4j.ui.javafx.";

	public JavaFXAtdl4jConfiguration()
	{
		super();
	}

	protected String getDefaultClassNameStrategiesUI() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "impl.JavaFXStrategiesUI";
	}

	protected String getDefaultClassNameStrategyUI() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "impl.JavaFXStrategyUI";
	}

	protected String getDefaultClassNameFixatdlFileSelectionPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXFixatdlFileSelectionPanel";
	}

	protected String getDefaultClassNameFixMsgLoadPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXFixMsgLoadPanel";
	}

	protected String getDefaultClassNameStrategySelectionPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXStrategySelectionPanel";
	}

	protected String getDefaultClassNameStrategyDescriptionPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXStrategyDescriptionPanel";
	}

	protected String getDefaultClassNameAtdl4jTesterPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXAtdl4jTesterPanel";
	}

	protected String getDefaultClassNameAtdl4jInputAndFilterDataSelectionPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXAtdl4jInputAndFilterDataSelectionPanel";
	}

	protected String getDefaultClassNameAtdl4jInputAndFilterDataPanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXAtdl4jInputAndFilterDataPanel";
	}

	protected String getDefaultClassNameAtdl4jCompositePanel() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXAtdl4jCompositePanel";
	}

	protected String getDefaultClassNameAtdl4jUserMessageHandler() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "app.impl.JavaFXAtdl4jUserMessageHandler";
	}

	protected String getDefaultClassNameAtdl4jWidgetForCheckBoxListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXCheckBoxListWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForCheckBoxT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXButtonWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForClockT() {
		// return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXClockWidget";
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXJideClockWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForDoubleSpinnerT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXSpinnerWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForDropDownListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXDropDownListWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForEditableDropDownListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXDropDownListWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForHiddenFieldT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXHiddenFieldWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForLabelT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXLabelWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForMultiSelectListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXListBoxWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForRadioButtonListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXRadioButtonListWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForRadioButtonT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXButtonWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForSingleSelectListT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXListBoxWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForSingleSpinnerT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXSpinnerWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForSliderT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXSliderWidget";
	}

	protected String getDefaultClassNameAtdl4jWidgetForTextFieldT() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "widget.JavaFXTextFieldWidget";
	}

	protected String getDefaultClassNameStrategyPanelHelper() {
		return PACKAGE_PATH_ORG_ATDL4J_UI_JavaFX + "impl.JavaFXStrategyPanelHelper";
	}
}


text:
#include "qdeclarativeinfo.h"

#include "private/qdeclarativedata_p.h"
#include "qdeclarativecontext.h"
#include "private/qdeclarativecontext_p.h"
#include "private/qdeclarativemetatype_p.h"
#include "private/qdeclarativeengine_p.h"

#include <QCoreApplication>

QT_BEGIN_NAMESPACE

/*!
    \fn QDeclarativeInfo qmlInfo(const QObject *object)
    \relates QDeclarativeEngine

    Prints warning messages that include the file and line number for the
    specified QML \a object.

    When QML types display warning messages, it improves traceability
    if they include the QML file and line number on which the
    particular instance was instantiated.

    To include the file and line number, an object must be passed.  If
    the file and line number is not available for that instance
    (either it was not instantiated by the QML engine or location
    information is disabled), "unknown location" will be used instead.

    For example,

    \code
    qmlInfo(object) << tr("component property is a write-once property");
    \endcode

    prints

    \code
    QML MyCustomType (unknown location): component property is a write-once property
    \endcode
*/

class QDeclarativeInfoPrivate
{
public:
    QDeclarativeInfoPrivate() : ref (1), object(0) {}

    int ref;
    const QObject *object;
    QString buffer;
    QList<QDeclarativeError> errors;
};

QDeclarativeInfo::QDeclarativeInfo(QDeclarativeInfoPrivate *p)
: QDebug(&p->buffer), d(p)
{
    nospace();
}

QDeclarativeInfo::QDeclarativeInfo(const QDeclarativeInfo &other)
: QDebug(other), d(other.d)
{
    d->ref++;
}

QDeclarativeInfo::~QDeclarativeInfo()
{
    if (0 == --d->ref) {
        QList<QDeclarativeError> errors = d->errors;

        QDeclarativeEngine *engine = 0;

        if (!d->buffer.isEmpty()) {
            QDeclarativeError error;

            QObject *object = const_cast<QObject *>(d->object);

            if (object) {
                engine = qmlEngine(d->object);
                QString typeName;
                QDeclarativeType *type = QDeclarativeMetaType::qmlType(object->metaObject());
                if (type) {
                    typeName = QLatin1String(type->qmlTypeName());
                    int lastSlash = typeName.lastIndexOf(QLatin1Char('/'));
                    if (lastSlash != -1)
                        typeName = typeName.mid(lastSlash+1);
                } else {
                    typeName = QString::fromUtf8(object->metaObject()->className());
                    int marker = typeName.indexOf(QLatin1String("_QMLTYPE_"));
                    if (marker != -1)
                        typeName = typeName.left(marker);
                }

                d->buffer.prepend(QLatin1String("QML ") + typeName + QLatin1String(": "));

                QDeclarativeData *ddata = QDeclarativeData::get(object, false);
                if (ddata && ddata->outerContext && !ddata->outerContext->url.isEmpty()) {
                    error.setUrl(ddata->outerContext->url);
                    error.setLine(ddata->lineNumber);
                    error.setColumn(ddata->columnNumber);
                }
            }

            error.setDescription(d->buffer);

            errors.prepend(error);
        }

        QDeclarativeEnginePrivate::warning(engine, errors);

        delete d;
    }
}

QDeclarativeInfo qmlInfo(const QObject *me)
{
    QDeclarativeInfoPrivate *d = new QDeclarativeInfoPrivate;
    d->object = me;
    return QDeclarativeInfo(d);
}

QDeclarativeInfo qmlInfo(const QObject *me, const QDeclarativeError &error)
{
    QDeclarativeInfoPrivate *d = new QDeclarativeInfoPrivate;
    d->object = me;
    d->errors << error;
    return QDeclarativeInfo(d);
}

QDeclarativeInfo qmlInfo(const QObject *me, const QList<QDeclarativeError> &errors)
{
    QDeclarativeInfoPrivate *d = new QDeclarativeInfoPrivate;
    d->object = me;
    d->errors = errors;
    return QDeclarativeInfo(d);
}

QT_END_NAMESPACE


text:
/* tslint:disable:no-unused-variable */
import * as React from 'react'
/* tslint:enable:no-unused-variable */
import {fromJS} from 'immutable'
import {storiesOf} from '@kadira/storybook'
import UserHovercard from '.'

const user = fromJS({
  id: '1',
  name: 'John Doe',
  email: 'jdoe@microsoft.com',
  job_title: 'Software Engineer'
})

storiesOf('User Hovercard', module)
  .add('default', () => (
    <UserHovercard
      user={user}
    />
  ))


text:
var http = require('http')

var constant = require('./constants')
var helper = require('./helper')
var cfg = require('./config')

var parseExitCode = function (buffer, defaultCode) {
  var tailPos = buffer.length - Buffer.byteLength(constant.EXIT_CODE) - 1

  if (tailPos < 0) {
    return defaultCode
  }

  // tail buffer which might contain the message
  var tail = buffer.slice(tailPos)
  var tailStr = tail.toString()
  if (tailStr.substr(0, tailStr.length - 1) === constant.EXIT_CODE) {
    tail.fill('\x00')
    return parseInt(tailStr.substr(-1), 10)
  }

  return defaultCode
}

// TODO(vojta): read config file (port, host, urlRoot)
exports.run = function (config, done) {
  done = helper.isFunction(done) ? done : process.exit
  config = cfg.parseConfig(config.configFile, config)

  var exitCode = 1
  var options = {
    hostname: config.hostname,
    path: config.urlRoot + 'run',
    port: config.port,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  }

  var request = http.request(options, function (response) {
    response.on('data', function (buffer) {
      exitCode = parseExitCode(buffer, exitCode)
      process.stdout.write(buffer)
    })

    response.on('end', function () {
      done(exitCode)
    })
  })

  request.on('error', function (e) {
    if (e.code === 'ECONNREFUSED') {
      console.error('There is no server listening on port %d', options.port)
      done(1)
    } else {
      throw e
    }
  })

  request.end(JSON.stringify({
    args: config.clientArgs,
    removedFiles: config.removedFiles,
    changedFiles: config.changedFiles,
    addedFiles: config.addedFiles,
    refresh: config.refresh
  }))
}


text:
'use strict';

const gulp = require('gulp');
const config = require('../../config');
const jsonlint = require('gulp-jsonlint');

module.exports = function() {
  return gulp.src(config.src.json)
    .pipe(jsonlint());
};


text:
<?php
//	error_reporting(E_ALL);
//	ini_set("display_errors", 1);
// var_dump($_GET);
	$root = $_SERVER['DOCUMENT_ROOT']."/";

	require_once($root.'/Framework/locale.php');
	require_once $root.'backends/admin-backend.php';
	require_once $root.'/views/back/Layout_View_n.php';

	$option 	= 'videos';

	$data 		= $backend->loadBackend($option);

	$data['title'] 			= "Main videos";
	$data['section'] 		= 'videos';
	$data['icon']			= 'fa-dashboard';
	$data['template-class'] = '';

	$view 		= new Layout_View($data, 'Videos');

	echo $view->printHTMLPage('videos');


text:
package aQute.bnd.deployer.repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.resource.Capability;
import org.osgi.resource.Namespace;
import org.osgi.resource.Requirement;
import org.osgi.resource.Resource;

/**
 * @ThreadSafe
 */
public class CapabilityIndex {

	private final Map<String,List<Capability>> capabilityMap = new HashMap<>();

	public synchronized void clear() {
		capabilityMap.clear();
	}

	public void addResource(Resource resource) {
		addCapabilities(resource.getCapabilities(null));
	}

	public void addCapability(Capability cap) {
		addCapabilities(Collections.singletonList(cap));
	}

	private synchronized void addCapabilities(Iterable<Capability> capabilities) {
		for (Capability cap : capabilities) {
			List<Capability> list = capabilityMap.get(cap.getNamespace());
			if (list == null) {
				list = new LinkedList<>();
				capabilityMap.put(cap.getNamespace(), list);
			}
			list.add(cap);
		}
	}

	public void appendMatchingCapabilities(Requirement requirement, Collection< ? super Capability> capabilities) {
		List<Capability> caps;

		synchronized (this) {
			if (capabilityMap.containsKey(requirement.getNamespace()))
				caps = new ArrayList<>(capabilityMap.get(requirement.getNamespace()));
			else
				caps = Collections.emptyList();
		}

		if (caps.isEmpty())
			return;

		try {
			String filterStr = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
			Filter filter = filterStr != null ? FrameworkUtil.createFilter(filterStr) : null;

			for (Capability cap : caps) {
				boolean match;
				if (filter == null)
					match = true;
				else
					match = filter.match(new MapToDictionaryAdapter(cap.getAttributes()));

				if (match)
					capabilities.add(cap);
			}
		} catch (InvalidSyntaxException e) {
			// Assume no matches
		}
	}

}