text:
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------

namespace System.Activities.Presentation.Hosting
{
    //WorkflowCommandExtensionItem - this class allows user to update each workflow's designer command
    //(i.e. input gestures collection). user has to provide IWorkflowCommandExtensionCallback implementation
    //to get notifications flowing in.
    public sealed class WorkflowCommandExtensionItem : ContextItem
    {
        public WorkflowCommandExtensionItem()
        {
        }

        public WorkflowCommandExtensionItem(IWorkflowCommandExtensionCallback callback)
        {
            if (null == callback)
            {
                throw FxTrace.Exception.AsError(new ArgumentNullException("callback"));
            }
            this.CommandExtensionCallback = callback;
        }

        public override Type ItemType
        {
            get { return typeof(WorkflowCommandExtensionItem); }
        }

        internal IWorkflowCommandExtensionCallback CommandExtensionCallback
        {
            get;
            private set;
        }
    }
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'simple_mysql_api', "~> 0.0.4"

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install simple_mysql_api

## Usage

Method name: mysql_search(options={})

options:

Simple search

    User.mysql_search({search_params: {name: "alex", address: "new"}})

    It will return Users having name matching alex:(mysql like "%alex%") and address matching "new"

Search in associated models

 1. If model has has_many relations with other models then

    Ex. User has_many cities =>

    User.mysql_search({search_params: {name: "alex", city_name_: "new"}, has_many: true})

 2. If model has belongs_to relations with other model then

    Ex. Project belongs_to users =>

    Project.mysql_search({search_params: {name: "my_p", user_name_: "ale"}, belongs_to: true})

 3. Search by ranges(Integer and decimals):
    Ex. If Item has price field then search for price by range
    Item.mysql_search({search_params: {price: "1000-2500"}}) # for items having price between 1000 to 2500
    Item.mysql_search({search_params: {price: "<2500"}}) # for items having price less than 2500

    Operators: <, >, <= , >=, - #for integer and floating attributes
 4. Search by ranges(Datetime):

     Ex. If Item has posted_at field then search for posted_at by range

     Item.mysql_search({search_params: {posted_at: "2012-09-08 15:28:21 +0530..2012-09-10 15:27:27 +0530"}}) # for items having posted_at date between the given dates

     Item.mysql_search({search_params: {posted_at: "<2012-09-08 15:28:21 +0530"}}) # for items having posted_at date earlier than given date

     Operators: <, >, <= , >=, ..(for range) #for datetime attributes

 3. It joins the tables automatically (Please specify primary & foreign keys if you are using custom keys)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

redpajama_set_name: RedPajamaGithub


text:
/*
 * tabular.js
 *
 * A standalone library for sorting HTML tables
 *
 * Author: Paul Stuart
 * License: MIT
 *
 */

/*
 * Make a table sortable by clicking on the column header
 */

var sortable = function(id) {
    var table = document.getElementById(id);
    var fn = tableSort.bind(table);
    var head = table.tHead.rows[0]
    for (var i = 0; i < head.cells.length; i++) {
        head.cells[i].addEventListener("click", function() {
            fn(this.cellIndex);
        }, false);
    }
}

/*
 * Sort a table by the column specified
 * Sorting is currently either numeric or string based
 * (it could be easily extended to sort by date or others)
 *
 * applies class "sort_arrow" to span showing the sort direction
 * style as you see fit
 */

var tableSort = function(col) {
    var up = "▲";
    var down = "▼";
    var invert = false;

    // clear prior arrow
    if (typeof this.lastColumn != 'undefined') {
        var prior = this.tHead.rows[0].cells[this.lastColumn].innerHTML;
        this.tHead.rows[0].cells[this.lastColumn].innerHTML = prior.replace(//, "");
    }

    if (this.lastColumn == col) {
        if (typeof this.inverted == 'undefined') {
            invert = (this.lastColumn == col);
        } else {
            invert = ! this.inverted;
        }
    }
    var arrow = invert ? up : down;
    this.tHead.rows[0].cells[col].innerHTML += ' ' + arrow + "";

    var intcomp = function(a, b) {
        var one = this.rows[a].cells[col].innerHTML;
        var two = this.rows[b].cells[col].innerHTML;
        return invert ? two - one : one - two ;
    }
    var strcomp = function(a, b) {
        var one = this.rows[a].cells[col].innerHTML;
        var two = this.rows[b].cells[col].innerHTML;
        return invert ? two.localeCompare(one) : one.localeCompare(two);
    }

    var headCount = this.tHead.rows.length;
    var kind = this.rows[headCount + 1].cells[col].innerHTML;
    var comp;
    if (Number(kind) === kind) {
        comp = intcomp.bind(this);
    } else {
        comp = strcomp.bind(this);
    }

    // create proxy array to sort table
    var proxy = new Array(this.rows.length - headCount);

    // adjust for offset by headCount rows
    for (var i = 0; i < proxy.length; i++) {
        proxy[i]=i + headCount;
    }
    proxy.sort(comp);

    // add new body to copy our rows to
    this.appendChild(document.createElement('tbody'))

    // copy rows in sorted order
    for (var i = 0; i < proxy.length; i++) {
        var n = this.rows[proxy[i]].cloneNode(true);
        this.tBodies[1].appendChild(n);
    }

    // delete original unsorted table
    this.tBodies[0].remove();

    // save settings to know if to invert sort order
    this.lastColumn = col;
    this.inverted = invert;
}


text:
<!DOCTYPE html>

    <title>NXT Controller</title>

<button onclick="window.controller.forward()">FORWARD</button>

<button onclick="window.controller.reverse()">REVERSE</button>

<button onclick="window.controller.stop()">STOP</button>

<button onclick="window.controller.beep()">BEEP</button>


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Functions dealing with attributes and meta_items

use ast;
use codemap::{spanned, dummy_spanned};
use attr;
use codemap::BytePos;
use diagnostic::span_handler;
use parse::comments::{doc_comment_style, strip_doc_comment_decoration};

use core::hashmap::HashSet;
use std;

/* Constructors */

pub fn mk_name_value_item_str(name: @~str, value: @~str)
                           -> @ast::meta_item {
    let value_lit = dummy_spanned(ast::lit_str(value));
    mk_name_value_item(name, value_lit)
}

pub fn mk_name_value_item(name: @~str, value: ast::lit)
        -> @ast::meta_item {
    @dummy_spanned(ast::meta_name_value(name, value))
}

pub fn mk_list_item(name: @~str, items: ~[@ast::meta_item]) ->
   @ast::meta_item {
    @dummy_spanned(ast::meta_list(name, items))
}

pub fn mk_word_item(name: @~str) -> @ast::meta_item {
    @dummy_spanned(ast::meta_word(name))
}

pub fn mk_attr(item: @ast::meta_item) -> ast::attribute {
    dummy_spanned(ast::attribute_ { style: ast::attr_inner,
                                    value: item,
                                    is_sugared_doc: false })
}

pub fn mk_sugared_doc_attr(text: ~str,
                           lo: BytePos, hi: BytePos) -> ast::attribute {
    let style = doc_comment_style(text);
    let lit = spanned(lo, hi, ast::lit_str(@text));
    let attr = ast::attribute_ {
        style: style,
        value: @spanned(lo, hi, ast::meta_name_value(@~"doc", lit)),
        is_sugared_doc: true
    };
    spanned(lo, hi, attr)
}

/* Conversion */

pub fn attr_meta(attr: ast::attribute) -> @ast::meta_item {
    attr.node.value
}

// Get the meta_items from inside a vector of attributes
pub fn attr_metas(attrs: &[ast::attribute]) -> ~[@ast::meta_item] {
    do attrs.map |a| { attr_meta(*a) }
}

pub fn desugar_doc_attr(attr: &ast::attribute) -> ast::attribute {
    if attr.node.is_sugared_doc {
        let comment = get_meta_item_value_str(attr.node.value).get();
        let meta = mk_name_value_item_str(@~"doc",
                                     @strip_doc_comment_decoration(*comment));
        mk_attr(meta)
    } else {
        *attr
    }
}

/* Accessors */

pub fn get_attr_name(attr: &ast::attribute) -> @~str {
    get_meta_item_name(attr.node.value)
}

pub fn get_meta_item_name(meta: @ast::meta_item) -> @~str {
    match meta.node {
        ast::meta_word(n) => n,
        ast::meta_name_value(n, _) => n,
        ast::meta_list(n, _) => n,
    }
}

/**
 * Gets the string value if the meta_item is a meta_name_value variant
 * containing a string, otherwise none
 */
pub fn get_meta_item_value_str(meta: @ast::meta_item) -> Option<@~str> {
    match meta.node {
        ast::meta_name_value(_, v) => {
            match v.node {
                ast::lit_str(s) => Some(s),
                _ => None,
            }
        },
        _ => None
    }
}

/// Gets a list of inner meta items from a list meta_item type
pub fn get_meta_item_list(meta: @ast::meta_item)
                       -> Option<~[@ast::meta_item]> {
    match meta.node {
        ast::meta_list(_, ref l) => Some(/* FIXME (#2543) */ copy *l),
        _ => None
    }
}

/**
 * If the meta item is a nam-value type with a string value then returns
 * a tuple containing the name and string value, otherwise `none`
 */
pub fn get_name_value_str_pair(item: @ast::meta_item)
                            -> Option<(@~str, @~str)> {
    match attr::get_meta_item_value_str(item) {
      Some(value) => {
        let name = attr::get_meta_item_name(item);
        Some((name, value))
      }
      None => None
    }
}

/* Searching */

/// Search a list of attributes and return only those with a specific name
pub fn find_attrs_by_name(attrs: &[ast::attribute], name: &str) ->
   ~[ast::attribute] {
    do vec::filter_mapped(attrs) |a| {
        if name == *get_attr_name(a) {
            Some(*a)
        } else {
            None
        }
    }
}

/// Search a list of meta items and return only those with a specific name
pub fn find_meta_items_by_name(metas: &[@ast::meta_item], name: &str) ->
   ~[@ast::meta_item] {
    let mut rs = ~[];
    for metas.each |mi| {
        if name == *get_meta_item_name(*mi) {
            rs.push(*mi)
        }
    }
    rs
}

/**
 * Returns true if a list of meta items contains another meta item. The
 * comparison is performed structurally.
 */
pub fn contains(haystack: &[@ast::meta_item],
                needle: @ast::meta_item) -> bool {
    for haystack.each |item| {
        if eq(*item, needle) { return true; }
    }
    return false;
}

fn eq(a: @ast::meta_item, b: @ast::meta_item) -> bool {
    match a.node {
        ast::meta_word(ref na) => match b.node {
            ast::meta_word(ref nb) => (*na) == (*nb),
            _ => false
        },
        ast::meta_name_value(ref na, va) => match b.node {
            ast::meta_name_value(ref nb, vb) => {
                (*na) == (*nb) && va.node == vb.node
            }
            _ => false
        },
        ast::meta_list(ref na, ref misa) => match b.node {
            ast::meta_list(ref nb, ref misb) => {
                if na != nb { return false; }
                for misa.each |mi| {
                    if !misb.contains(mi) { return false; }
                }
                true
            }
            _ => false
        }
    }
}

pub fn contains_name(metas: &[@ast::meta_item], name: &str) -> bool {
    let matches = find_meta_items_by_name(metas, name);
    matches.len() > 0u
}

pub fn attrs_contains_name(attrs: &[ast::attribute], name: &str) -> bool {
    !find_attrs_by_name(attrs, name).is_empty()
}

pub fn first_attr_value_str_by_name(attrs: &[ast::attribute], name: &str)
                                 -> Option<@~str> {

    let mattrs = find_attrs_by_name(attrs, name);
    if mattrs.len() > 0 {
        get_meta_item_value_str(attr_meta(mattrs[0]))
    } else {
        None
    }
}

fn last_meta_item_by_name(items: &[@ast::meta_item], name: &str)
    -> Option<@ast::meta_item> {

    let items = attr::find_meta_items_by_name(items, name);
    items.last_opt().map(|item| **item)
}

pub fn last_meta_item_value_str_by_name(items: &[@ast::meta_item], name: &str)
                                     -> Option<@~str> {

    match last_meta_item_by_name(items, name) {
        Some(item) => {
            match attr::get_meta_item_value_str(item) {
                Some(value) => Some(value),
                None => None
            }
        },
        None => None
    }
}

pub fn last_meta_item_list_by_name(items: ~[@ast::meta_item], name: &str)
    -> Option<~[@ast::meta_item]> {

    match last_meta_item_by_name(items, name) {
      Some(item) => attr::get_meta_item_list(item),
      None => None
    }
}

/* Higher-level applications */

pub fn sort_meta_items(items: &[@ast::meta_item]) -> ~[@ast::meta_item] {
    // This is sort of stupid here, converting to a vec of mutables and back
    let mut v = vec::to_owned(items);
    do std::sort::quick_sort(v) |ma, mb| {
        get_meta_item_name(*ma) <= get_meta_item_name(*mb)
    }

    // There doesn't seem to be a more optimal way to do this
    do v.map |m| {
        match m.node {
            ast::meta_list(n, ref mis) => {
                @spanned {
                    node: ast::meta_list(n, sort_meta_items(*mis)),
                    .. /*bad*/ copy **m
                }
            }
            _ => /*bad*/ copy *m
        }
    }
}

pub fn remove_meta_items_by_name(items: ~[@ast::meta_item], name: &str) ->
   ~[@ast::meta_item] {

    return vec::filter_mapped(items, |item| {
        if name != *get_meta_item_name(*item) {
            Some(*item)
        } else {
            None
        }
    });
}

/**
 * From a list of crate attributes get only the meta_items that affect crate
 * linkage
 */
pub fn find_linkage_metas(attrs: &[ast::attribute]) -> ~[@ast::meta_item] {
    do find_attrs_by_name(attrs, ~"link").flat_map |attr| {
        match attr.node.value.node {
            ast::meta_list(_, ref items) => /* FIXME (#2543) */ copy *items,
            _ => ~[]
        }
    }
}

#[deriving(Eq)]
pub enum inline_attr {
    ia_none,
    ia_hint,
    ia_always,
    ia_never,
}

/// True if something like #[inline] is found in the list of attrs.
pub fn find_inline_attr(attrs: &[ast::attribute]) -> inline_attr {
    // FIXME (#2809)---validate the usage of #[inline] and #[inline(always)]
    do vec::foldl(ia_none, attrs) |ia,attr| {
        match attr.node.value.node {
          ast::meta_word(@~"inline") => ia_hint,
          ast::meta_list(@~"inline", ref items) => {
            if !find_meta_items_by_name(*items, ~"always").is_empty() {
                ia_always
            } else if !find_meta_items_by_name(*items, ~"never").is_empty() {
                ia_never
            } else {
                ia_hint
            }
          }
          _ => ia
        }
    }
}

pub fn require_unique_names(diagnostic: @span_handler,
                            metas: &[@ast::meta_item]) {
    let mut set = HashSet::new();
    for metas.each |meta| {
        let name = get_meta_item_name(*meta);

        // FIXME: How do I silence the warnings? --pcw (#2619)
        if !set.insert(name) {
            diagnostic.span_fatal(meta.span,
                                  fmt!("duplicate meta item `%s`", *name));
        }
    }
}


text:
package pubsub

import (
	"fmt"
	"math"
	"strings"

	pb "google.golang.org/genproto/googleapis/pubsub/v1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// maxPayload is the maximum number of bytes to devote to actual ids in
// acknowledgement or modifyAckDeadline requests. A serialized
// AcknowledgeRequest proto has a small constant overhead, plus the size of the
// subscription name, plus 3 bytes per ID (a tag byte and two size bytes). A
// ModifyAckDeadlineRequest has an additional few bytes for the deadline. We
// don't know the subscription name here, so we just assume the size exclusive
// of ids is 100 bytes.
//
// With gRPC there is no way for the client to know the server's max message size (it is
// configurable on the server). We know from experience that it
// it 512K.
const (
	maxPayload       = 512 * 1024
	reqFixedOverhead = 100
	overheadPerID    = 3
	maxSendRecvBytes = 20 * 1024 * 1024 // 20M
)

func convertMessages(rms []*pb.ReceivedMessage) ([]*Message, error) {
	msgs := make([]*Message, 0, len(rms))
	for i, m := range rms {
		msg, err := toMessage(m)
		if err != nil {
			return nil, fmt.Errorf("pubsub: cannot decode the retrieved message at index: %d, message: %+v", i, m)
		}
		msgs = append(msgs, msg)
	}
	return msgs, nil
}

func trunc32(i int64) int32 {
	if i > math.MaxInt32 {
		i = math.MaxInt32
	}
	return int32(i)
}

// Logic from https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/v1/StatusUtil.java.
func isRetryable(err error) bool {
	s, ok := status.FromError(err)
	if !ok { // includes io.EOF, normal stream close, which causes us to reopen
		return true
	}
	switch s.Code() {
	case codes.DeadlineExceeded, codes.Internal, codes.Canceled, codes.ResourceExhausted:
		return true
	case codes.Unavailable:
		return !strings.Contains(s.Message(), "Server shutdownNow invoked")
	default:
		return false
	}
}

// Split req into a prefix that is smaller than maxSize, and a remainder.
func splitRequest(req *pb.StreamingPullRequest, maxSize int) (prefix, remainder *pb.StreamingPullRequest) {
	const int32Bytes = 4

	// Copy all fields before splitting the variable-sized ones.
	remainder = &pb.StreamingPullRequest{}
	*remainder = *req
	// Split message so it isn't too big.
	size := reqFixedOverhead
	i := 0
	for size < maxSize && (i < len(req.AckIds) || i < len(req.ModifyDeadlineAckIds)) {
		if i < len(req.AckIds) {
			size += overheadPerID + len(req.AckIds[i])
		}
		if i < len(req.ModifyDeadlineAckIds) {
			size += overheadPerID + len(req.ModifyDeadlineAckIds[i]) + int32Bytes
		}
		i++
	}

	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	j := i
	if size > maxSize {
		j--
	}
	k := min(j, len(req.AckIds))
	remainder.AckIds = req.AckIds[k:]
	req.AckIds = req.AckIds[:k]
	k = min(j, len(req.ModifyDeadlineAckIds))
	remainder.ModifyDeadlineAckIds = req.ModifyDeadlineAckIds[k:]
	remainder.ModifyDeadlineSeconds = req.ModifyDeadlineSeconds[k:]
	req.ModifyDeadlineAckIds = req.ModifyDeadlineAckIds[:k]
	req.ModifyDeadlineSeconds = req.ModifyDeadlineSeconds[:k]
	return req, remainder
}


text:
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError

from .. import models

class ComponentsOperations(object):
    """ComponentsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An objec model deserializer.
    :ivar api_version: Client Api Version. Constant value: "2015-05-01".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2015-05-01"

        self.config = config

    def list(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets a list of all Application Insights components within a
        subscription.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of ApplicationInsightsComponent
        :rtype:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponentPaged[~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/providers/microsoft.insights/components'
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.ApplicationInsightsComponentPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.ApplicationInsightsComponentPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def list_by_resource_group(
            self, resource_group_name, custom_headers=None, raw=False, **operation_config):
        """Gets a list of Application Insights components within a resource group.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of ApplicationInsightsComponent
        :rtype:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponentPaged[~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components'
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.ApplicationInsightsComponentPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.ApplicationInsightsComponentPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def delete(
            self, resource_group_name, resource_name, custom_headers=None, raw=False, **operation_config):
        """Deletes an Application Insights component.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param resource_name: The name of the Application Insights component
         resource.
        :type resource_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceName': self._serialize.url("resource_name", resource_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200, 204]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def get(
            self, resource_group_name, resource_name, custom_headers=None, raw=False, **operation_config):
        """Returns an Application Insights component.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param resource_name: The name of the Application Insights component
         resource.
        :type resource_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ApplicationInsightsComponent or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceName': self._serialize.url("resource_name", resource_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ApplicationInsightsComponent', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def create_or_update(
            self, resource_group_name, resource_name, insight_properties, custom_headers=None, raw=False, **operation_config):
        """Creates (or updates) an Application Insights component. Note: You
        cannot specify a different value for InstrumentationKey nor AppId in
        the Put operation.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param resource_name: The name of the Application Insights component
         resource.
        :type resource_name: str
        :param insight_properties: Properties that need to be specified to
         create an Application Insights component.
        :type insight_properties:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ApplicationInsightsComponent or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceName': self._serialize.url("resource_name", resource_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(insight_properties, 'ApplicationInsightsComponent')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ApplicationInsightsComponent', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def update_tags(
            self, resource_group_name, resource_name, tags=None, custom_headers=None, raw=False, **operation_config):
        """Updates an existing component's tags. To update other fields use the
        CreateOrUpdate method.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param resource_name: The name of the Application Insights component
         resource.
        :type resource_name: str
        :param tags: Resource tags
        :type tags: dict[str, str]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: ApplicationInsightsComponent or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.applicationinsights.models.ApplicationInsightsComponent or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        component_tags = models.TagsResource(tags=tags)

        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceName': self._serialize.url("resource_name", resource_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(component_tags, 'TagsResource')

        # Construct and send request
        request = self._client.patch(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ApplicationInsightsComponent', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized


text:
#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>
@class DDUserDataModel;
@interface DDUserDataWindowController : NSWindowController
{
    __strong IBOutlet EGOImageView* _userAvatar;
    __weak IBOutlet NSTextField* _userNameTextField;
    __weak IBOutlet NSTextField* _userNickTextField;
    __weak IBOutlet NSTextField* _userGenderTextField;

    __weak IBOutlet NSTextField* _departmentTextField;
    __weak IBOutlet NSTextField* _jobTextField;
    __weak IBOutlet NSTextField* _emailTextField;
    __weak IBOutlet NSTextField* _phoneTextField;

    __weak IBOutlet NSButton* _modifyAvatarButton;

//    __weak IBOutlet NSProgressIndicator* _loadIndicator;

}
@property (nonatomic,retain)DDUserDataModel* model;

- (IBAction)beginChat:(id)sender;
- (IBAction)modifyUserAvater:(id)sender;
@end


text:
package vgrechka.phizdetsidea.phizdets.configuration;

import com.intellij.ide.ui.search.SearchableOptionContributor;
import com.intellij.ide.ui.search.SearchableOptionProcessor;
import org.jetbrains.annotations.NotNull;

public class PySearchableOptionContributor extends SearchableOptionContributor {
  @Override
  public void processOptions(@NotNull SearchableOptionProcessor processor) {
    processIntegratedTools(processor);
  }

  private static void processIntegratedTools(SearchableOptionProcessor processor) {
    final String configurableId = "vgrechka.phizdetsidea.phizdets.configuration.PyIntegratedToolsModulesConfigurable";
    final String displayName = "Phizdets Integrated Tools";
    processor.addOptions("Package requirements file", displayName, "Package requirements file",
                         configurableId, displayName, true);
    processor.addOptions("Default test runner", displayName, "Default test runner",
                         configurableId, displayName, true);
    processor.addOptions("Docstring format", displayName, "Docstring format",
                         configurableId, displayName, true);
    processor.addOptions("Analyze Phizdets code in docstrings", displayName, "Analyze Phizdets code in docstrings",
                         configurableId, displayName, true);
    processor.addOptions("Sphinx working directory", displayName, "Sphinx working directory",
                         configurableId, displayName, true);
    processor.addOptions("Treat txt files as reStructuredText", displayName, "Treat *.txt files as reStructuredText ",
                         configurableId, displayName, false);
    processor.addOptions("reStructuredText", displayName, "Docstring format",
                         configurableId, displayName, false);
    processor.addOptions("Epytext", "Docstring format", "Docstring format",
                         configurableId, displayName, false);
    processor.addOptions("Plain", displayName, "Docstring format",
                         configurableId, displayName, false);
    processor.addOptions("Unittests", displayName, "Default test runner",
                         configurableId, displayName, false);
    processor.addOptions("py.test", displayName, "Default test runner",
                         configurableId, displayName, false);
    processor.addOptions("Nosetests", displayName, "Default test runner",
                         configurableId, displayName, false);
    processor.addOptions("Attests", displayName, "Default test runner",
                         configurableId, displayName, false);
  }
}


text:
package org.apache.skywalking.apm.agent.core.logging.core;

import com.google.gson.Gson;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogResolver;

public class JsonLogResolver implements LogResolver {
    private static final Gson GSON = new Gson();

    @Override
    public ILog getLogger(Class<?> aClass) {
        return new JsonLogger(aClass, GSON);
    }

    @Override
    public ILog getLogger(String s) {
        return new JsonLogger(s, GSON);
    }
}


text:
import { FromDefinition, ModelDefinition } from "../types/definitions";
import { Model } from "./object-model";

type FromArgsDef<T> = T extends [infer A, ...infer Rest] ? [FromDefinition<A>, ...FromArgsDef<Rest>] : T

export type FunctionSignature<Args extends any[], Return> = {
	(...args: FromArgsDef<Args>): FromDefinition<Return>
}

export interface FunctionModel<Args extends ModelDefinition[], Return extends ModelDefinition> extends Model<{ arguments: Args, return: Return }> {
	(): FunctionSignature<Args, Return>;
	(fn: FunctionSignature<Args, Return>): FunctionSignature<Args, Return>;
	new (fn: FunctionSignature<Args, Return>): FunctionSignature<Args, Return>;
	definition: { arguments: Args, return: Return };

	return<R extends ModelDefinition>(returnValueDefinition: R): FunctionModel<Args, R>;
}

export interface FunctionModelConstructor {
	<Args extends ModelDefinition[]>(...argumentsDefinitions: Args): FunctionModel<Args, any>;
	new<Args extends ModelDefinition[]>(...argumentsDefinitions: Args): FunctionModel<Args, any>;
}

export const FunctionModel: FunctionModelConstructor;


text:
<?php
/*
 * This class was auto-generated from the API references found at
 * https://epayments-api.developer-ingenico.com/s2sapi/v1/
 */
namespace Ingenico\Connect\Sdk\Domain\Payment;

use Ingenico\Connect\Sdk\DataObject;
use UnexpectedValueException;

/**
 * @package Ingenico\Connect\Sdk\Domain\Payment
 */
class TokenizePaymentRequest extends DataObject
{
    /**
     * @var string
     */
    public $alias = null;

    /**
     * @return object
     */
    public function toObject()
    {
        $object = parent::toObject();
        if (!is_null($this->alias)) {
            $object->alias = $this->alias;
        }
        return $object;
    }

    /**
     * @param object $object
     * @return $this
     * @throws UnexpectedValueException
     */
    public function fromObject($object)
    {
        parent::fromObject($object);
        if (property_exists($object, 'alias')) {
            $this->alias = $object->alias;
        }
        return $this;
    }
}


text:
id: 5d822fd413a79914d39e98dc
title: Step 20
challengeType: 0
dashedName: step-20
---

# --description--

The buildings are stacked on top of each other and running off the screen. Let's fix that. Add the properties `display: flex;`, `align-items: flex-end;`, and `justify-content: space-evenly;` to the `background-buildings` class. This will use flexbox again to evenly space the buildings across the bottom of the element.

# --hints--

You should add a `display` of `flex` to the `background-buildings` class.

```js
assert.equal(new __helpers.CSSHelp(document).getStyle('.background-buildings')?.display, 'flex');
```

You should add an `align-items` of `flex-end` to the `background-buildings` class.

```js
assert.equal(new __helpers.CSSHelp(document).getStyle('.background-buildings')?.alignItems, 'flex-end');
```

You should add a `justify-content` of `space-evenly` to the `background-buildings` class.

```js
assert.equal(new __helpers.CSSHelp(document).getStyle('.background-buildings')?.justifyContent, 'space-evenly');
```

# --seed--

## --seed-contents--

```html
<!DOCTYPE html>
<html>
  <head>
    <title>freeCodeCamp Skyline Project</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <div class="background-buildings">
      <div class="bb1">
        <div class="bb1a"></div>
        <div class="bb1b"></div>
        <div class="bb1c"></div>
        <div class="bb1d"></div>
      </div>
      <div class="bb2"></div>
      <div class="bb3"></div>
      <div class="bb4"></div>
    </div>
  </body>
</html>
```

```css
* {
  border: 1px solid black;
  box-sizing: border-box;
}

body {
  height: 100vh;
  margin: 0;
  overflow: hidden;
}
--fcc-editable-region--
.background-buildings {
  width: 100%;
  height: 100%;
}
--fcc-editable-region--
.bb1 {
  width: 10%;
  height: 70%;
  display: flex;
  flex-direction: column;
  align-items: center;
  --building-color1: #aa80ff;
}

.bb1a {
  width: 70%;
  height: 10%;
  background-color: var(--building-color1);
}

.bb1b {
  width: 80%;
  height: 10%;
  background-color: var(--building-color1);
}

.bb1c {
  width: 90%;
  height: 10%;
  background-color: var(--building-color1);
}

.bb1d {
  width: 100%;
  height: 70%;
  background-color: var(--building-color1);
}

.bb2 {
  width: 10%;
  height: 50%;
}

.bb3 {
  width: 10%;
  height: 55%;
}

.bb4 {
  width: 11%;
  height: 58%;
}

```


text:
<?php

function secure_random_bytes($len = 10)
{

   /*
    * Our primary choice for a cryptographic strong randomness function is
    * openssl_random_pseudo_bytes.
    */
   $SSLstr = '4'; // http://xkcd.com/221/
   if (function_exists('openssl_random_pseudo_bytes') &&
       (version_compare(PHP_VERSION, '5.3.4') >= 0 ||
        substr(PHP_OS, 0, 3) !== 'WIN'))
   {
      $SSLstr = openssl_random_pseudo_bytes($len, $strong);
      if ($strong) {
         return $SSLstr;
      }
   }

   /*
    * If mcrypt extension is available then we use it to gather entropy from
    * the operating system's PRNG. This is better than reading /dev/urandom
    * directly since it avoids reading larger blocks of data than needed.
    * Older versions of mcrypt_create_iv may be broken or take too much time
    * to finish so we only use this function with PHP 5.3.7 and above.
    * @see https://bugs.php.net/bug.php?id=55169
    */
   if (function_exists('mcrypt_create_iv') &&
      (version_compare(PHP_VERSION, '5.3.7') >= 0 ||
       substr(PHP_OS, 0, 3) !== 'WIN')) {
      $str = mcrypt_create_iv($len, MCRYPT_DEV_URANDOM);
      if ($str !== false) {
         return $str;
      }
   }

   /*
    * No build-in crypto randomness function found. We collect any entropy
    * available in the PHP core PRNGs along with some filesystem info and memory
    * stats. To make this data cryptographically strong we add data either from
    * /dev/urandom or if its unavailable, we gather entropy by measuring the
    * time needed to compute a number of SHA-1 hashes.
    */
   $str = '';
   $bits_per_round = 2; // bits of entropy collected in each clock drift round
   $msec_per_round = 400; // expected running time of each round in microseconds
   $hash_len = 20; // SHA-1 Hash length
   $total = $len; // total bytes of entropy to collect

   $handle = @fopen('/dev/urandom', 'rb');
   if ($handle && function_exists('stream_set_read_buffer')) {
      @stream_set_read_buffer($handle, 0);
   }

   do
   {
      $bytes = ($total > $hash_len)? $hash_len : $total;
      $total -= $bytes;

      //collect any entropy available from the PHP system and filesystem
      $entropy = rand() . uniqid(mt_rand(), true) . $SSLstr;
      $entropy .= implode('', @fstat(@fopen( __FILE__, 'r')));
      $entropy .= memory_get_usage() . getmypid();
      $entropy .= serialize($_ENV) . serialize($_SERVER);
      if (function_exists('posix_times')) {
        $entropy .= serialize(posix_times());
      }
      if (function_exists('zend_thread_id')) {
        $entropy .= zend_thread_id();
      }
      if ($handle) {
         $entropy .= @fread($handle, $bytes);
      } else  {
         // Measure the time that the operations will take on average
         for ($i = 0; $i < 3; $i++)
         {
            $c1 = get_microtime();
            $var = sha1(mt_rand());
            for ($j = 0; $j < 50; $j++) {
               $var = sha1($var);
            }
            $c2 = get_microtime();
            $entropy .= $c1 . $c2;
         }

         // Based on the above measurement determine the total rounds
         // in order to bound the total running time.
         $rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000));

         // Take the additional measurements. On average we can expect
         // at least $bits_per_round bits of entropy from each measurement.
         $iter = $bytes * (int) (ceil(8 / $bits_per_round));
         for ($i = 0; $i < $iter; $i++)
         {
            $c1 = get_microtime();
            $var = sha1(mt_rand());
            for ($j = 0; $j < $rounds; $j++) {
               $var = sha1($var);
            }
            $c2 = get_microtime();
            $entropy .= $c1 . $c2;
         }

      }
      // We assume sha1 is a deterministic extractor for the $entropy variable.
      $str .= sha1($entropy, true);
   } while ($len > strlen($str));

   if ($handle) {
      @fclose($handle);
   }
   return substr($str, 0, $len);
}


text:
package dk.statsbiblioteket.doms.ecm.repository;

import dk.statsbiblioteket.doms.ecm.repository.exceptions.PIDGeneratorException;

/**
 * Pidgenerator factory class, and interface. Use the static #getPidGenerator() to
 * get an implementation of this class, and then the #generateNextAvailablePID
 * method to generate pids
 */
public abstract class PidGenerator {

    private static PidGenerator gen;

    /**
     * Get the next available pid with the prefix s
     * @param s the prefix
     * @return the next available pid
     * @throws PIDGeneratorException Catch-all exception for everything that
     * can go wrong.
     */
    public abstract String generateNextAvailablePID(String s) throws
                                                              PIDGeneratorException;

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// serialization stuff
using Newtonsoft.Json.Converters;

namespace OpenAsset.RestClient.Library
{
    class CustomResponseConverter : CustomCreationConverter<CustomResponses.Base.BaseCustomResponse>
    {

        public override CustomResponses.Base.BaseCustomResponse Create(Type objectType)
        {
            return new Error();
            //throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType);
        }
    }
}


text:
/**
 * @author Vladimir Nenashev
 * @version $Revision: 1.4 $
 */

#include<stdio.h>
#include<jni.h>
#include<stdlib.h>
#include"StackTest13.h"
#include"share.h"

JNIEXPORT void JNICALL
Java_org_apache_harmony_test_stress_jni_stack_StackTest13_init(JNIEnv *env,
                                                               jobject obj,
                                                               jint cnt) {
  StackTest_init_with_Java_method(env, obj, cnt);
}

JNIEXPORT jintArray JNICALL
Java_org_apache_harmony_test_stress_jni_stack_StackTest13_nativeMethod(JNIEnv* env,
                                                                       jobject thisObject,
                                                                       jintArray intArray,
                                                                       jint len,
                                                                       jint cnt,
                                                                       jint threadId){
  jint* arr;
  jintArray res, res2 = NULL;
  jint* calc_res;

  StackTest_alloc_arrays(env, len, &arr, &calc_res, NULL);
  if (arr == NULL || calc_res == NULL) {
    printf("Native code (thread %d): Cannot allocate jint* arrays\n", (int)threadId);
    return NULL;
  }

  (*env)->GetIntArrayRegion(env, intArray, 0, len, arr);
  if((*env)->ExceptionCheck(env)) {
    printf("Native code (thread %d): Cannot get array elements\n", (int)threadId);
    StackTest_free_arrays(env, arr, calc_res, NULL);
    return NULL;
  }

  StackTest_do_calc(arr, calc_res, len);

  res2 = res = (*env)->NewIntArray(env, len);
  if (res == NULL) {
    StackTest_free_arrays(env, arr, calc_res, NULL);
    return NULL;
  }

  (*env)->SetIntArrayRegion(env, res, 0, len, calc_res);
  if ((*env)->ExceptionCheck(env)) {
    printf("Native code (thread %d): Cannot set array elements\n", (int)threadId);
    StackTest_free_arrays(env, arr, calc_res, NULL);
    return NULL;
  }

  if (cnt < maxCnt) {
    res2 = (*env)->CallObjectMethod(env, thisObject, mid, res, cnt + 1);
    if ((*env)->ExceptionCheck(env)) {
      StackTest_free_arrays(env, arr, calc_res, NULL);
      return NULL;
    }
  }
  StackTest_free_arrays(env, arr, calc_res, NULL);
  return res2;
}


text:
* [Command-line](https://github.com/HorvathLab/NGS/blob/master/SCReadCounts/docs/Examples.md#command-line)
* [Graphical User Interface](https://github.com/HorvathLab/NGS/blob/master/SCReadCounts/docs/Examples.md#graphical-user-interface)

## Command-line:

### Example: BAM files and single SNV file in TSV format.

    sh singlecell.sh

The above script runs SCReadCounts using the inputs from `SCReadCounts/data` (snv file = `singlecell_222_5_chr17.txt`, bam = `singlecell_chr17.bam`, output prefix = `singlecell-output.tsv`). Result files corresponding to this analysis are available [here](../data/output)

Example output files:
* [Counts](../data/output/singlecell-output.tsv)
* [Count matrix (Ref;Var)](../data/output/singlecell-output.cnt.matrix.tsv)
* [VAF matrix with minR=3](../data/output/singlecell-output.vaf-m3.matrix.tsv)
* [VAF matrix with minR=3](../data/output/singlecell-output.vaf-m5.matrix.tsv)

## Graphical User Interface

### Example 1: BAM files and single SNV file in `txt` format with default minR value (5).

1. Select the SNV file by clicking on the `Browse` button, navigating to `SCReadCounts/data`, selecting `singlecell_222_5_chr17.txt`, and clicking `OK`.

2. Select the BAM files by clicking on the `Browse` button, navigating to `SCReadCounts/data`, selecting `singlecell_chr17.bam` (multiple BAM files can be selected using shift-click or control-click as needed), and clicking `OK`.

3. Specify the [filtering option](https://github.com/HorvathLab/NGS/tree/master/ReadCounts/docs/filtering.md) by clicking on the `🠋` button.

   ![Filtering Options](SCReadCounts_filter.png)

4. Specify the output directory by clicking on the `Browse` button, navigating to `SCReadCounts/data`, clicking `Create Folder`, entering "new_output", entering the name as `singlecell_GUI.tsv` and clicking `Save`.

   ![Output name](SCReadCounts_output_options.png)

SCReadCounts will create the following files:
* Counts(singlecell_GUI.tsv)
* Count matrix (Ref;Var)(singlecell_GUI.cnt.matrix.tsv)
* VAF matrix with minR=5 (singlecell_GUI.vaf-m5.matrix.tsv)

5. Click `OK` to execute the program.

### Example 2: Re-running SCReadCounts with different minR value (10).

1. Select the SNV file by clicking on the `Browse` button, navigating to `SCReadCounts/data`, selecting `singlecell_222_5_chr17.txt`, and clicking `OK`.

2. Select the BAM files by clicking on the `Browse` button, navigating to `SCReadCounts/data`, selecting `singlecell_chr17.bam` (multiple BAM files can be selected using shift-click or control-click as needed), and clicking `OK`.

3. Specify the [filtering option](https://github.com/HorvathLab/NGS/tree/master/ReadCounts/docs/filtering.md) by clicking on the `🠋` button.

4. Specify the output directory by clicking on the `Browse` button, navigating to `SCReadCounts/data`, clicking `Create Folder`, entering "new_output", entering the name as `singlecell_GUI.tsv` and clicking `Save`. You will be prompted with a message `A file named "singlecell_GUI.tsv" already exists. Do you want to replace it?`. Click on the `Replace` button.

   ![Re-run](SCReadCounts_GUI_re-run.png)

5. Click `OK` to execute the program.

Since the output files: `singlecell_GUI.tsv and singlecell_GUI.cnt.matrix.tsv` already exists (it doesn't change with respect to the "advanced" option of minR), only one new file will be created i.e. VAF with minR of 10 (singlecell_GUI.vaf-m10.matrix.tsv)

## See Also

[SCReadCounts Home](..), [Usage](Usage.md), [Input Files](InputFiles.md), [Output Files](OutputFiles.md)


text:
FORMAT: 1A

# Test API Blueprint

Test API Blueprint for ```Bluth```.

Request and response payloads include data schemas, to the [JSON schema spec](http://json-schema.org/).

# Group Test resource

Authentication operations.

## Test [/test/{id}/something?niceParameter={niceParameter}]

+ Parameters

    + id (required, string) ... Test ```id```

### Retrieve [POST]

Retrieve test data.

+ Request

    + Body

            {
              "name": "G.O.B.",
              "noiseAChickenMakes": "Caw! Ca-caw!"
            }

    + Schema

            {
              "$schema": "http://json-schema.org/draft-04/schema#",
              "title": "/test/{id}/something POST request",
              "type": "object",
              "required": [
                "name",
                "noiseAChickenMakes"
              ],
              "properties": {
                "name": {
                  "description": "Name.",
                  "type": "string"
                },
                "noiseAChickenMakes": {
                  "description": "Valid chicken noise.",
                  "type": "string",
                  "enum": [ "Caw! Ca-caw!", "A-coodle-doodle-do!", "Chee-chaw!", "Coo-coo-ca-chaw!" ]
                }
              },
              "additionalProperties": false
            }

+ Response 201

    + Body

            {
              "name": "G.O.B.",
              "noiseAChickenMakes": "Caw! Ca-caw!"
            }

    + Schema

            {
              "$schema": "http://json-schema.org/draft-04/schema#",
              "title": "/test/{id}/something POST 201 response",
              "type": "object",
              "required": [
                "name",
                "noiseAChickenMakes"
              ],
              "properties": {
                "name": {
                  "description": "Name.",
                  "type": "string"
                },
                "noiseAChickenMakes": {
                  "description": "Valid chicken noise.",
                  "type": "string"
                }
              }
            }

+ Response 400

+ Response 500

    + Schema

            {
              "$schema": "http://json-schema.org/draft-04/schema#",
              "title": "/test/{id} POST 500 response",
              "type": "object",
              "required": [
                "stackTrace"
              ],
              "properties": {
                "stackTrace": {
                  "description": "Server stack trace.",
                  "type": "string"
                }
              }
            }


text:
@interface PodsDummy_Pods_SGPod_Tests : NSObject
@end
@implementation PodsDummy_Pods_SGPod_Tests
@end


text:
/**
 * Created by Samuel Gratzl on 27.12.2016.
 */
import { IPluginDesc, IRegistry, IPlugin } from '../base/plugin';
export declare class PluginRegistry implements IRegistry {
    private registry;
    push(type: string, idOrLoader: string | (() => any), descOrLoader: any, desc?: any): void;
    private knownPlugins;
    register(plugin: string, generator?: (registry: IRegistry) => void): void;
    /**
     * returns a list of matching plugin descs
     * @param filter
     * @returns {IPluginDesc[]}
     */
    listPlugins(filter?: (string | ((desc: IPluginDesc) => boolean))): IPluginDesc[];
    /**
     * returns an extension identified by type and id
     * @param type
     * @param id
     * @returns {IPluginDesc}
     */
    getPlugin(type: string, id: string): IPluginDesc;
    loadPlugin(desc: IPluginDesc[]): Promise<IPlugin[]>;
    /**
     * Helper function to simplify importing of  resource files (e.g., JSON).
     * The imported resource file is returned as it is.
     *
     * @param data Imported JSON file
     */
    asResource(data: any): {
        create: () => any;
    };
    /**
     * determines the factory method to use in case of the 'new ' syntax wrap the class constructor using a factory method
     */
    getFactoryMethod(instance: any, factory: string): any;
    private static instance;
    static getInstance(): PluginRegistry;
}


text:
import * as util from  "util";

export const MESSAGES = {
  tailCallReassignmentDeopt: "Function reference has been reassigned so it's probably be dereferenced so we can't optimise this with confidence",
  JSXNamespacedTags: "Namespace tags are not supported. ReactJSX is not XML.",
  classesIllegalBareSuper: "Illegal use of bare super",
  classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead",
  classesIllegalConstructorKind: "Illegal kind for constructor method",
  scopeDuplicateDeclaration: "Duplicate declaration $1",
  undeclaredVariable: "Reference to undeclared variable $1",
  undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
  settersInvalidParamLength: "Setters must have exactly one parameter",
  settersNoRest: "Setters aren't allowed to have a rest",
  noAssignmentsInForHead: "No assignments allowed in for-in/of head",
  expectedMemberExpressionOrIdentifier: "Expected type MemeberExpression or Identifier",
  invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue",
  readOnly: "$1 is read-only",
  modulesIllegalExportName: "Illegal export $1",
  unknownForHead: "Unknown node type $1 in ForStatement",
  didYouMean: "Did you mean $1?",
  codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",
  missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",
  unsupportedOutputType: "Unsupported output type $1",
  illegalMethodName: "Illegal method name $1",
  lostTrackNodePath: "We lost track of this nodes position, likely because the AST was directly manipulated",

  traverseNeedsParent: "Must pass a scope and parentPath unless traversing a Program/File got a $1 node",
  traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",
  traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",
  traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type",

  pluginIllegalKind: "Illegal kind $1 for plugin $2",
  pluginIllegalPosition: "Illegal position $1 for plugin $2",
  pluginKeyCollision: "The plugin $1 collides with another of the same name",
  pluginNotTransformer: "The plugin $1 didn't export a Transformer instance",
  pluginUnknown: "Unknown plugin $1",

  transformerNotFile: "Transformer $1 is resolving to a different Babel version to what is doing the actual transformation..."
};

export function get(key: String, ...args) {
  var msg = MESSAGES[key];
  if (!msg) throw new ReferenceError(`Unknown message ${JSON.stringify(key)}`);

  args = parseArgs(args);

  return msg.replace(/\$(\d+)/g, function (str, i) {
    return args[--i];
  });
}

export function parseArgs(args: Array<any>) {
  return args.map(function (val) {
    if (val != null && val.inspect) {
      return val.inspect();
    } else {
      try {
        return JSON.stringify(val) || val + "";
      } catch (e) {
        return util.inspect(val);
      }
    }
  });
}


text:
//
//  ARViewController.m
//  ARApp2
//
//  Disclaimer: IMPORTANT:  This Daqri software is supplied to you by Daqri
//  LLC ("Daqri") in consideration of your agreement to the following
//  terms, and your use, installation, modification or redistribution of
//  this Daqri software constitutes acceptance of these terms.  If you do
//  not agree with these terms, please do not use, install, modify or
//  redistribute this Daqri software.
//
//  In consideration of your agreement to abide by the following terms, and
//  subject to these terms, Daqri grants you a personal, non-exclusive
//  license, under Daqri's copyrights in this original Daqri software (the
//  "Daqri Software"), to use, reproduce, modify and redistribute the Daqri
//  Software, with or without modifications, in source and/or binary forms;
//  provided that if you redistribute the Daqri Software in its entirety and
//  without modifications, you must retain this notice and the following
//  text and disclaimers in all such redistributions of the Daqri Software.
//  Neither the name, trademarks, service marks or logos of Daqri LLC may
//  be used to endorse or promote products derived from the Daqri Software
//  without specific prior written permission from Daqri.  Except as
//  expressly stated in this notice, no other rights or licenses, express or
//  implied, are granted by Daqri herein, including but not limited to any
//  patent rights that may be infringed by your derivative works or by other
//  works in which the Daqri Software may be incorporated.
//
//  The Daqri Software is provided by Daqri on an "AS IS" basis.  DAQRI
//  MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
//  THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
//  FOR A PARTICULAR PURPOSE, REGARDING THE DAQRI SOFTWARE OR ITS USE AND
//  OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
//
//  IN NO EVENT SHALL DAQRI BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
//  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
//  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//  INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
//  MODIFICATION AND/OR DISTRIBUTION OF THE DAQRI SOFTWARE, HOWEVER CAUSED
//  AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
//  STRICT LIABILITY OR OTHERWISE, EVEN IF DAQRI HAS BEEN ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
//
//  Copyright 2015 Daqri LLC. All Rights Reserved.
//  Copyright 2010-2015 ARToolworks, Inc. All rights reserved.
//
//  Author(s): Philip Lamb
//

#import "ARViewController.h"
#import <AR/gsub_es.h>
#import "../ARAppCore/ARMarkerSquare.h"
#import "../ARAppCore/ARMarkerMulti.h"

#define VIEW_DISTANCE_MIN        5.0f          // Objects closer to the camera than this will not be displayed.
#define VIEW_DISTANCE_MAX        2000.0f        // Objects further away from the camera than this will not be displayed.

//
// ARViewController
//

@implementation ARViewController {

    BOOL            running;
    NSInteger       runLoopInterval;
    NSTimeInterval  runLoopTimePrevious;
    BOOL            videoPaused;

    // Video acquisition
    AR2VideoParamT *gVid;

    // Marker detection.
    ARHandle       *gARHandle;
    ARPattHandle   *gARPattHandle;
    long            gCallCountMarkerDetect;

    // Transformation matrix retrieval.
    AR3DHandle     *gAR3DHandle;

    // Markers.
    NSMutableArray *markers;

    // Drawing.
    ARParamLT      *gCparamLT;
    ARView         *glView;
    VirtualEnvironment *virtualEnvironment;
    ARGL_CONTEXT_SETTINGS_REF arglContextSettings;
}

@synthesize glView, virtualEnvironment, markers;
@synthesize arglContextSettings;
@synthesize running, runLoopInterval;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

- (void)loadView
{
    self.wantsFullScreenLayout = YES;

    // This will be overlaid with the actual AR view.
    NSString *irisImage = nil;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        irisImage = @"Iris-iPad.png";
    }  else { // UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone
        CGSize result = [[UIScreen mainScreen] bounds].size;
        if (result.height == 568) {
            irisImage = @"Iris-568h.png"; // iPhone 5, iPod touch 5th Gen, etc.
        } else { // result.height == 480
            irisImage = @"Iris.png";
        }
    }
    UIView *irisView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:irisImage]] autorelease];
    irisView.userInteractionEnabled = YES;
    self.view = irisView;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    // Init instance variables.
    glView = nil;
    virtualEnvironment = nil;
    markers = nil;
    gVid = NULL;
    gCparamLT = NULL;
    gARHandle = NULL;
    gARPattHandle = NULL;
    gCallCountMarkerDetect = 0;
    gAR3DHandle = NULL;
    arglContextSettings = NULL;
    running = FALSE;
    videoPaused = FALSE;
    runLoopTimePrevious = CFAbsoluteTimeGetCurrent();
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self start];
}

// On iOS 6.0 and later, we must explicitly report which orientations this view controller supports.
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (void)startRunLoop
{
    if (!running) {
        // After starting the video, new frames will invoke cameraVideoTookPicture:userData:.
        if (ar2VideoCapStart(gVid) != 0) {
            NSLog(@"Error: Unable to begin camera data capture.\n");
            [self stop];
            return;
        }
        running = TRUE;
    }
}

- (void)stopRunLoop
{
    if (running) {
        ar2VideoCapStop(gVid);
        running = FALSE;
    }
}

- (void) setRunLoopInterval:(NSInteger)interval
{
    if (interval >= 1) {
        runLoopInterval = interval;
        if (running) {
            [self stopRunLoop];
            [self startRunLoop];
        }
    }
}

- (BOOL) isPaused
{
    if (!running) return (NO);

    return (videoPaused);
}

- (void) setPaused:(BOOL)paused
{
    if (!running) return;

    if (videoPaused != paused) {
        if (paused) ar2VideoCapStop(gVid);
        else ar2VideoCapStart(gVid);
        videoPaused = paused;
#  ifdef DEBUG
        NSLog(@"Run loop was %s.\n", (paused ? "PAUSED" : "UNPAUSED"));
#  endif
    }
}

static void startCallback(void *userData);

- (IBAction)start
{
    // Open the video path.
    char *vconf = ""; // See http://www.artoolworks.com/support/library/Configuring_video_capture_in_ARToolKit_Professional#AR_VIDEO_DEVICE_IPHONE
    if (!(gVid = ar2VideoOpenAsync(vconf, startCallback, self))) {
        NSLog(@"Error: Unable to open connection to camera.\n");
        [self stop];
        return;
    }
}

static void startCallback(void *userData)
{
    ARViewController *vc = (ARViewController *)userData;

    [vc start2];
}

- (void) start2
{
    // Find the size of the window.
    int xsize, ysize;
    if (ar2VideoGetSize(gVid, &xsize, &ysize) < 0) {
        NSLog(@"Error: ar2VideoGetSize.\n");
        [self stop];
        return;
    }

    // Get the format in which the camera is returning pixels.
    AR_PIXEL_FORMAT pixFormat = ar2VideoGetPixelFormat(gVid);
    if (pixFormat == AR_PIXEL_FORMAT_INVALID) {
        NSLog(@"Error: Camera is using unsupported pixel format.\n");
        [self stop];
        return;
    }

    // Work out if the front camera is being used. If it is, flip the viewing frustum for
    // 3D drawing.
    BOOL flipV = FALSE;
    int frontCamera;
    if (ar2VideoGetParami(gVid, AR_VIDEO_PARAM_IOS_CAMERA_POSITION, &frontCamera) >= 0) {
        if (frontCamera == AR_VIDEO_IOS_CAMERA_POSITION_FRONT) flipV = TRUE;
    }

    // Tell arVideo what the typical focal distance will be. Note that this does NOT
    // change the actual focus, but on devices with non-fixed focus, it lets arVideo
    // choose a better set of camera parameters.
    ar2VideoSetParami(gVid, AR_VIDEO_PARAM_IOS_FOCUS, AR_VIDEO_IOS_FOCUS_0_3M); // Default is 0.3 metres. See <AR/sys/videoiPhone.h> for allowable values.

    // Load the camera parameters, resize for the window and init.
    ARParam cparam;
    if (ar2VideoGetCParam(gVid, &cparam) < 0) {
        char cparam_name[] = "Data2/camera_para.dat";
        NSLog(@"Unable to automatically determine camera parameters. Using default.\n");
        if (arParamLoad(cparam_name, 1, &cparam) < 0) {
            NSLog(@"Error: Unable to load parameter file %s for camera.\n", cparam_name);
            [self stop];
            return;
        }
    }
    if (cparam.xsize != xsize || cparam.ysize != ysize) {
#ifdef DEBUG
        fprintf(stdout, "*** Camera Parameter resized from %d, %d. ***\n", cparam.xsize, cparam.ysize);
#endif
        arParamChangeSize(&cparam, xsize, ysize, &cparam);
    }
#ifdef DEBUG
    fprintf(stdout, "*** Camera Parameter ***\n");
    arParamDisp(&cparam);
#endif
    if ((gCparamLT = arParamLTCreate(&cparam, AR_PARAM_LT_DEFAULT_OFFSET)) == NULL) {
        NSLog(@"Error: arParamLTCreate.\n");
        [self stop];
        return;
    }

    // AR init.
    if ((gARHandle = arCreateHandle(gCparamLT)) == NULL) {
        NSLog(@"Error: arCreateHandle.\n");
        [self stop];
        return;
    }
    if (arSetPixelFormat(gARHandle, pixFormat) < 0) {
        NSLog(@"Error: arSetPixelFormat.\n");
        [self stop];
        return;
    }
    if ((gAR3DHandle = ar3DCreateHandle(&gCparamLT->param)) == NULL) {
        NSLog(@"Error: ar3DCreateHandle.\n");
        [self stop];
        return;
    }

    // libARvideo on iPhone uses an underlying class called CameraVideo. Here, we
    // access the instance of this class to get/set some special types of information.
    CameraVideo *cameraVideo = ar2VideoGetNativeVideoInstanceiPhone(gVid->device.iPhone);
    if (!cameraVideo) {
        NSLog(@"Error: Unable to set up AR camera: missing CameraVideo instance.\n");
        [self stop];
        return;
    }

    // The camera will be started by -startRunLoop.
    [cameraVideo setTookPictureDelegate:self];
    [cameraVideo setTookPictureDelegateUserData:NULL];

    // Other ARToolKit setup.
    arSetMarkerExtractionMode(gARHandle, AR_USE_TRACKING_HISTORY_V2);
    //arSetMarkerExtractionMode(gARHandle, AR_NOUSE_TRACKING_HISTORY);
    //arSetLabelingThreshMode(gARHandle, AR_LABELING_THRESH_MODE_MANUAL); // Uncomment to use  manual thresholding.

    // Allocate the OpenGL view.
    glView = [[[ARView alloc] initWithFrame:[[UIScreen mainScreen] bounds] pixelFormat:kEAGLColorFormatRGBA8 depthFormat:kEAGLDepth16 withStencil:NO preserveBackbuffer:NO] autorelease]; // Don't retain it, as it will be retained when added to self.view.
    glView.arViewController = self;
    [self.view addSubview:glView];

    // Create the OpenGL projection from the calibrated camera parameters.
    // If flipV is set, flip.
    GLfloat frustum[16];
    arglCameraFrustumRHf(&gCparamLT->param, VIEW_DISTANCE_MIN, VIEW_DISTANCE_MAX, frustum);
    [glView setCameraLens:frustum];
    glView.contentFlipV = flipV;

    // Set up content positioning.
    glView.contentScaleMode = ARViewContentScaleModeFill;
    glView.contentAlignMode = ARViewContentAlignModeCenter;
    glView.contentWidth = gARHandle->xsize;
    glView.contentHeight = gARHandle->ysize;
    BOOL isBackingTallerThanWide = (glView.surfaceSize.height > glView.surfaceSize.width);
    if (glView.contentWidth > glView.contentHeight) glView.contentRotate90 = isBackingTallerThanWide;
    else glView.contentRotate90 = !isBackingTallerThanWide;
#ifdef DEBUG
    NSLog(@"[ARViewController start] content %dx%d (wxh) will display in GL context %dx%d%s.\n", glView.contentWidth, glView.contentHeight, (int)glView.surfaceSize.width, (int)glView.surfaceSize.height, (glView.contentRotate90 ? " rotated" : ""));
#endif

    // Setup ARGL to draw the background video.
    arglContextSettings = arglSetupForCurrentContext(&gCparamLT->param, pixFormat);

    arglSetRotate90(arglContextSettings, (glView.contentWidth > glView.contentHeight ? isBackingTallerThanWide : !isBackingTallerThanWide));
    if (flipV) arglSetFlipV(arglContextSettings, TRUE);
    int width, height;
    ar2VideoGetBufferSize(gVid, &width, &height);
    arglPixelBufferSizeSet(arglContextSettings, width, height);

    // Prepare ARToolKit to load patterns.
    if (!(gARPattHandle = arPattCreateHandle())) {
        NSLog(@"Error: arPattCreateHandle.\n");
        [self stop];
        return;
    }
    arPattAttach(gARHandle, gARPattHandle);

    // Load marker(s).
    NSString *markerConfigDataFilename = @"Data2/markers.dat";
    int mode;
    if ((markers = [ARMarker newMarkersFromConfigDataFile:markerConfigDataFilename arPattHandle:gARPattHandle arPatternDetectionMode:&mode]) == nil) {
        NSLog(@"Error loading markers.\n");
        [self stop];
        return;
    }
#ifdef DEBUG
    NSLog(@"Marker count = %d\n", [markers count]);
#endif
    // Set the pattern detection mode (template (pictorial) vs. matrix (barcode) based on
    // the marker types as defined in the marker config. file.
    arSetPatternDetectionMode(gARHandle, mode); // Default = AR_TEMPLATE_MATCHING_COLOR

    // Other application-wide marker options. Once set, these apply to all markers in use in the application.
    // If you are using standard ARToolKit picture (template) markers, leave commented to use the defaults.
    // If you are usign a different marker design (see http://www.artoolworks.com/support/app/marker.php )
    // then uncomment and edit as instructed by the marker design application.
    //arSetLabelingMode(gARHandle, AR_LABELING_BLACK_REGION); // Default = AR_LABELING_BLACK_REGION
    //arSetBorderSize(gARHandle, 0.25f); // Default = 0.25f
    //arSetMatrixCodeType(gARHandle, AR_MATRIX_CODE_3x3); // Default = AR_MATRIX_CODE_3x3

    // Set up the virtual environment.
    self.virtualEnvironment = [[[VirtualEnvironment alloc] initWithARViewController:self] autorelease];
    [self.virtualEnvironment addObjectsFromObjectListFile:@"Data2/models.dat" connectToARMarkers:markers];

    // Because in this example we're not currently assigning a world coordinate system
    // (we're just using local marker coordinate systems), set the camera pose now, to
    // the default (i.e. the identity matrix).
    float pose[16] = {1.0f, 0.0f, 0.0f, 0.0f,  0.0f, 1.0f, 0.0f, 0.0f,  0.0f, 0.0f, 1.0f, 0.0f,  0.0f, 0.0f, 0.0f, 1.0f};
    [glView setCameraPose:pose];

    // For FPS statistics.
    arUtilTimerReset();
    gCallCountMarkerDetect = 0;

     //Create our runloop timer
    [self setRunLoopInterval:2]; // Target 30 fps on a 60 fps device.
    [self startRunLoop];
}

- (void) cameraVideoTookPicture:(id)sender userData:(void *)data
{
    AR2VideoBufferT *buffer = ar2VideoGetImage(gVid);
    if (buffer) [self processFrame:buffer];
}

- (void) processFrame:(AR2VideoBufferT *)buffer
{
    if (buffer) {

        // Upload the frame to OpenGL.
        if (buffer->bufPlaneCount == 2) arglPixelBufferDataUploadBiPlanar(arglContextSettings, buffer->bufPlanes[0], buffer->bufPlanes[1]);
        else arglPixelBufferDataUpload(arglContextSettings, buffer->buff);

        gCallCountMarkerDetect++; // Increment ARToolKit FPS counter.
#ifdef DEBUG
        NSLog(@"video frame %ld.\n", gCallCountMarkerDetect);
#endif
#ifdef DEBUG
        if (gCallCountMarkerDetect % 150 == 0) {
            NSLog(@"*** Camera - %f (frame/sec)\n", (double)gCallCountMarkerDetect/arUtilTimer());
            gCallCountMarkerDetect = 0;
            arUtilTimerReset();
        }
#endif

        // Detect the markers in the video frame.
        if (arDetectMarker(gARHandle, buffer->buff) < 0) return;
        int markerNum = arGetMarkerNum(gARHandle);
        ARMarkerInfo *markerInfo = arGetMarker(gARHandle);
#ifdef DEBUG
        NSLog(@"found %d marker(s).\n", markerNum);
#endif

        // Update all marker objects with detected markers.
        for (ARMarker *marker in markers) {
            if ([marker isKindOfClass:[ARMarkerSquare class]]) {
                [(ARMarkerSquare *)marker updateWithDetectedMarkers:markerInfo count:markerNum ar3DHandle:gAR3DHandle];
            } else if ([marker isKindOfClass:[ARMarkerMulti class]]) {
                [(ARMarkerMulti *)marker updateWithDetectedMarkers:markerInfo count:markerNum ar3DHandle:gAR3DHandle];
            } else {
                [marker update];
            }
        }

        // Get current time (units = seconds).
        NSTimeInterval runLoopTimeNow;
        runLoopTimeNow = CFAbsoluteTimeGetCurrent();
        [virtualEnvironment updateWithSimulationTime:(runLoopTimeNow - runLoopTimePrevious)];

        // The display has changed.
        [glView drawView:self];

        // Save timestamp for next loop.
        runLoopTimePrevious = runLoopTimeNow;
    }
}

- (IBAction)stop
{
    [self stopRunLoop];

    self.virtualEnvironment = nil;

    [markers release];
    markers = nil;

    if (arglContextSettings) {
        arglCleanup(arglContextSettings);
        arglContextSettings = NULL;
    }
    [glView removeFromSuperview]; // Will result in glView being released.
    glView = nil;

    if (gARHandle) arPattDetach(gARHandle);
    if (gARPattHandle) {
        arPattDeleteHandle(gARPattHandle);
        gARPattHandle = NULL;
    }
    if (gAR3DHandle) ar3DDeleteHandle(&gAR3DHandle);
    if (gARHandle) {
        arDeleteHandle(gARHandle);
        gARHandle = NULL;
    }
    arParamLTFree(&gCparamLT);
    if (gVid) {
        ar2VideoClose(gVid);
        gVid = NULL;
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillDisappear:(BOOL)animated {
    [self stop];
    [super viewWillDisappear:animated];
}

- (void)dealloc {
    [super dealloc];
}

// ARToolKit-specific methods.
- (BOOL)markersHaveWhiteBorders
{
    int mode;
    arGetLabelingMode(gARHandle, &mode);
    return (mode == AR_LABELING_WHITE_REGION);
}

- (void)setMarkersHaveWhiteBorders:(BOOL)markersHaveWhiteBorders
{
    arSetLabelingMode(gARHandle, (markersHaveWhiteBorders ? AR_LABELING_WHITE_REGION : AR_LABELING_BLACK_REGION));
}

@end


text:
<?php

/**
 * DO NOT EDIT!
 * This file was automatically generated via bin/generate-validator-spec.php.
 */

namespace AmpProject\Validator\Spec\Tag;

use AmpProject\Extension;
use AmpProject\Format;
use AmpProject\Html\Attribute;
use AmpProject\Validator\Spec\AttributeList;
use AmpProject\Validator\Spec\Identifiable;
use AmpProject\Validator\Spec\SpecRule;
use AmpProject\Validator\Spec\Tag;

/**
 * Tag class AmpActionMacro.
 *
 * @package ampproject/amp-toolbox.
 *
 * @property-read string $tagName
 * @property-read array $attrs
 * @property-read array<string> $attrLists
 * @property-read string $specUrl
 * @property-read array<string> $htmlFormat
 * @property-read array<string> $requiresExtension
 */
final class AmpActionMacro extends Tag implements Identifiable
{
    /**
     * ID of the tag.
     *
     * @var string
     */
    const ID = 'AMP-ACTION-MACRO';

    /**
     * Array of spec rules.
     *
     * @var array
     */
    const SPEC = [
        SpecRule::TAG_NAME => Extension::ACTION_MACRO,
        SpecRule::ATTRS => [
            Attribute::ARGUMENTS => [],
            Attribute::EXECUTE => [
                SpecRule::MANDATORY => true,
            ],
        ],
        SpecRule::ATTR_LISTS => [
            AttributeList\MandatoryIdAttr::ID,
        ],
        SpecRule::SPEC_URL => 'https://amp.dev/documentation/components/amp-action-macro/',
        SpecRule::HTML_FORMAT => [
            Format::AMP,
        ],
        SpecRule::REQUIRES_EXTENSION => [
            Extension::ACTION_MACRO,
        ],
    ];
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name=viewport content=width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1>

        <link rel="apple-touch-icon" href="images/icon/apple-touch-icon.png" />
        <link rel="apple-touch-icon" sizes="57x57" href="images/icon/apple-touch-icon-57x57-precomposed.png"/>
        <link rel="apple-touch-icon" sizes="72x72" href="images/icon/apple-touch-icon-72x72-precomposed.png" />
        <link rel="apple-touch-icon" sizes="114x114" href="images/icon/apple-touch-icon-114x114-precomposed.png" />
        <link rel="apple-touch-icon" sizes="144x144" href="images/icon/apple-touch-icon-144x144-precomposed.png" />

        <link rel="stylesheet" href="stylesheets/main.css">

                        Article Name


text:
package com.automationrockstars.design.desktop.driver.internal;

import com.google.common.base.Joiner;
import org.openqa.selenium.interactions.Keyboard;
import org.sikuli.script.Region;

public class SikuliKeyboard implements Keyboard {

    private final Region region;

    public SikuliKeyboard(Region region) {
        this.region = region;
    }

    @Override
    public void sendKeys(CharSequence... keysToSend) {
        region.type(Joiner.on("").join(keysToSend));

    }

    @Override
    public void pressKey(CharSequence keyToPress) {
        region.keyDown(keyToPress.toString());

    }

    @Override
    public void releaseKey(CharSequence keyToRelease) {
        region.keyUp(keyToRelease.toString());

    }

}


text:
'use strict'
/* eslint-env mocha */

const ethereum = require('../src')
const expect = require('chai').expect
const parallel = require('run-parallel')
const Block = require('ethereumjs-block')
const thousand = require('./data/real-chain/first-1000-blocks.json')
const async = require('async')

describe('block', () => {
  let eth1
  let eth2

  before((done) => {
    eth1 = new ethereum.Node()
    eth2 = new ethereum.Node()

    parallel([
      eth1.start,
      eth2.start
    ], done)
  })

  after((done) => {
    parallel([
      eth1.stop,
      eth2.stop
    ], () => {
      setTimeout(done, 1000)
    })
  })

  it('connect both nodes', (done) => {
    // in the browser this will be idempotent due to wstar discovery
    eth1.libp2p.dialByPeerInfo(eth2.libp2p.peerInfo, done)
  })

  it('run through blockchain in first node', (done) => {
    async.eachSeries(thousand.slice(1, 3), eachBlock, next)

    function eachBlock (raw, cb) {
      let block
      try {
        block = new Block(new Buffer(raw.slice(2), 'hex'))

        eth1.blockchain.putBlock(block, (err) => {
          expect(err).to.not.exist
          cb()
        })
      } catch (err) { cb(err) }
    }

    function next (err) {
      expect(err).to.not.exist
      eth1.vm.runBlockchain(done)
    }
  })

  it('block.sync', (done) => {
    eth2.block.sync(done)
  })

  it('run through blockchain in the second', (done) => {
    eth2.vm.runBlockchain(done)
  })
})


text:
package org.apache.commons.collections4.set;

import java.util.Comparator;
import java.util.SortedSet;

import org.apache.commons.collections4.Transformer;

/**
 * Decorates another SortedSet to transform objects that are added.
 *

 * The add methods are affected by this class.
 * Thus objects must be removed or searched for using their transformed form.
 * For example, if the transformation converts Strings to Integers, you must
 * use the Integer form to remove objects.
 *

 * This class is Serializable from Commons Collections 3.1.
 *
 * @since 3.0
 * @version $Id$
 */
public class TransformedSortedSet<E> extends TransformedSet<E> implements SortedSet<E> {

    /** Serialization version */
    private static final long serialVersionUID = -1675486811351124386L;

    /**
     * Factory method to create a transforming sorted set.
     *

     * If there are any elements already in the set being decorated, they
     * are NOT transformed.
     * Contrast this with {@link #transformedSortedSet(SortedSet, Transformer)}.
     *
     * @param <E> the element type
     * @param set  the set to decorate, must not be null
     * @param transformer  the transformer to use for conversion, must not be null
     * @return a new transformed {@link SortedSet}
     * @throws IllegalArgumentException if set or transformer is null
     * @since 4.0
     */
    public static <E> TransformedSortedSet<E> transformingSortedSet(final SortedSet<E> set,
            final Transformer<? super E, ? extends E> transformer) {
        return new TransformedSortedSet<E>(set, transformer);
    }

    /**
     * Factory method to create a transforming sorted set that will transform
     * existing contents of the specified sorted set.
     *

     * If there are any elements already in the set being decorated, they
     * will be transformed by this method.
     * Contrast this with {@link #transformingSortedSet(SortedSet, Transformer)}.
     *
     * @param <E> the element type
     * @param set  the set to decorate, must not be null
     * @param transformer  the transformer to use for conversion, must not be null
     * @return a new transformed {@link SortedSet}
     * @throws IllegalArgumentException if set or transformer is null
     * @since 4.0
     */
    public static <E> TransformedSortedSet<E> transformedSortedSet(final SortedSet<E> set,
            final Transformer<? super E, ? extends E> transformer) {

        final TransformedSortedSet<E> decorated = new TransformedSortedSet<E>(set, transformer);
        if (transformer != null && set != null && set.size() > 0) {
            @SuppressWarnings("unchecked") // set is type E
            final E[] values = (E[]) set.toArray(); // NOPMD - false positive for generics
            set.clear();
            for (final E value : values) {
                decorated.decorated().add(transformer.transform(value));
            }
        }
        return decorated;
    }

    //-----------------------------------------------------------------------
    /**
     * Constructor that wraps (not copies).
     *

     * If there are any elements already in the set being decorated, they
     * are NOT transformed.
     *
     * @param set  the set to decorate, must not be null
     * @param transformer  the transformer to use for conversion, must not be null
     * @throws IllegalArgumentException if set or transformer is null
     */
    protected TransformedSortedSet(final SortedSet<E> set, final Transformer<? super E, ? extends E> transformer) {
        super(set, transformer);
    }

    /**
     * Gets the decorated set.
     *
     * @return the decorated set
     */
    protected SortedSet<E> getSortedSet() {
        return (SortedSet<E>) decorated();
    }

    //-----------------------------------------------------------------------
    public E first() {
        return getSortedSet().first();
    }

    public E last() {
        return getSortedSet().last();
    }

    public Comparator<? super E> comparator() {
        return getSortedSet().comparator();
    }

    //-----------------------------------------------------------------------
    public SortedSet<E> subSet(final E fromElement, final E toElement) {
        final SortedSet<E> set = getSortedSet().subSet(fromElement, toElement);
        return new TransformedSortedSet<E>(set, transformer);
    }

    public SortedSet<E> headSet(final E toElement) {
        final SortedSet<E> set = getSortedSet().headSet(toElement);
        return new TransformedSortedSet<E>(set, transformer);
    }

    public SortedSet<E> tailSet(final E fromElement) {
        final SortedSet<E> set = getSortedSet().tailSet(fromElement);
        return new TransformedSortedSet<E>(set, transformer);
    }

}


text:
require "spec_helper"

describe Wasabi::Document do
  context "with: inherited.xml" do

    subject { Wasabi::Document.new fixture(:inherited).read }

    describe '#type_definitions' do
      subject { super().type_definitions }
      it do
      should include([["Account", "Id"], "ID"])
      should include([["Account", "ProcessId"], "ID"])
      should include([["Account", "CreatedDate"], "dateTime"])
      should include([["Account", "Description"], "string"])
      should include([["Account", "fieldsToNull"], "string"])
    end
    end

    it "should position base class attributes before subclass attributes in :order! array" do
      account = subject.parser.types["Account"]
      expect(account[:order!]).to eq(["fieldsToNull", "Id", "Description", "ProcessId", "CreatedDate"])
    end

    it "should have each type's hash remember it's base type in :base_type element" do
      account = subject.parser.types["Account"]
      expect(account[:base_type]).to eq("baseObject")

      base_object = subject.parser.types["baseObject"]
      expect(base_object).not_to have_key(:base_type)
    end

    it "should have element's hash contain all these attributes (:nillable, :minOccurs, :maxOccurs) in addition to :type" do
      base_object = subject.parser.types["baseObject"]
      fields_to_null = base_object["fieldsToNull"]
      expect(fields_to_null[:nillable]).to eq("true")
      expect(fields_to_null[:minOccurs]).to eq("0")
      expect(fields_to_null[:maxOccurs]).to eq("unbounded")
    end
  end
end


text:
require "privy/version"

class Privy
  def initialize(object)
    @object = object
  end

  def method_missing(method, *args, &block)
    @object.__send__(method, *args, &block)
  end
end

Object.define_singleton_method(:privy!) do
  Privy.new(self)
end

Object.__send__(:define_method, :privy!) do
  Privy.new(self)
end