text:
Test Friendly Format (TEFF)
===========================

Copyright © 2014-2015 Hǎiliàng Wáng.

This specification is licensed under the [Creative Commons Attribution 4.0
International License](http://creativecommons.org/licenses/by/4.0/).

Introduction
------------
TEFF (TEst Friendly Format) is an extensible data format with testing purpose in
mind. It is friendly to read, write and compare, and can be extended to represent
rich set of data types.

In general, TEFF are organized into two layers, core and extensions. The
[core](#core) of TEFF represents a tree with annotated nodes, which forms
an extensible foundation with minimal constraints. The [extensions](#extensions)
of TEFF define encodings of major data types and allow custom encoding of user
defined types. The encodings of extensions are only constrained by the core, i.e.
any two extensions may have the same representation without causing any conflict.

This specification is a follow-up work of [OGDL 2.0](https://github.com/ogdl)
([OGDL](http://ogdl.org/) was invented by Rolf Veen, and we cooperated in
writing its 2.0 spec).

Notation
--------
The syntax is specified using a variant of Extended Backus-Naur Form, based on
[W3C XML EBNF](http://www.w3.org/TR/xml11/#sec-notation),
which is extended with the following definitions:
* Escape sequences defined in section [Escape sequences](#escape-sequences).
* Regular expressions defined in section [Regular expression](#regular-expression).
* Text enclosed by <> is a description.

Core
----

### Characters

A TEFF file is a sequence of [Unicode](http://unicode.org/) code points encoded
in [UTF-8](http://www.unicode.org/versions/latest/ch03.pdf).

Only `char_valid`, i.e. `\t` (U+0009), `\n` (U+000A), `\r` (U+000D) and code
points larger or equal to U+0020 (space) are considered valid in a TEFF file.

    char_valid     ::= char_inline | char_break
    char_inline    ::= char_visible | char_space
    char_visible   ::= [^\x00-\x20]
    char_space     ::= [ \t]
    char_break     ::= [\r\n]

### Lines

A TEFF file is also a sequence of lines separated by `newline`.

    line           ::= empty_line | content_line
    empty_line     ::= char_space* newline
    newline        ::= char_break | "\r\n" | EOF
    EOF            ::= <end of file>
    content_line   ::= indent_space (annotation | reference | value) newline
    indent_space   ::= char_space*
    annotation     ::= "#" char_inline*
    reference      ::= "^" char_inline*
    value          ::= [^\x00-\x20#^] char_inline*

### Indents

    start          ::= indent
    end            ::= unindent

Tokens `indent` and `unindent` are emitted by the rules described below:

1. A stack is used to store `indent_space` and controls the emission of
   `indent` & `unindent` tokens.
2. Initially, an empty value is pushed onto the stack, and then the TEFF file is
   scanned line by line to get the `indent_space` of each line.
3. When the top of the stack is the same as the `indent_space` of the current
   line, neither `indent` nor `unindent` is emitted.
4. When the top of the stack is a prefix of the `indent_space` of the current
   line, the `indent_space` is pushed onto the stack, and an `indent` token is
   emitted.
5. When the `indent_space` of the current line is the same as one of the non-top
   elements of the stack, the top of the stack is popped and an `unindent` token
   is emitted until the non-top element becomes the top. The number of `unindent`
   tokens emitted is the same as the number of elements popped.
6. If none of 3 to 5 happens, a syntax error occurs.
7. When `EOF` is emitted but the length of the stack is larger than 1, the top of
   the stack is popped and an `unindent` token is emitted until the length of
   the stack becomes 1.

### Grammar

    teff_file    ::= list EOF
    list         ::= node*
    node         ::= annotation* (value_list | reference)
    value_list   ::= value (start list end)?

Extensions
----------
In this section, extensions for `annotation`, `reference`, `list` and `value`
are defined to represent major data types, including almost all built-in types
and some of the important types in the standard libraries.

### Type annotation

TEFF can optionally specify data types by type annotations.

    type_annotation ::= "#" spaces? type_label
    ---------------     --- ------------------
        ↓                ↓       ↓
    ----------          --- ------------
    annotation      ::= "#" char_inline*

    type_label      ::= "<" letter_digit+ ">"
    unicode_letter  ::= <a Unicode code point classified as "Letter">
    unicode_digit   ::= <a Unicode code point classified as "Decimal Digit">
    letter_digit    ::= unicode_letter | unicode_digit | "_"

### Reference

TEFF can represent a cyclic graph by references. A reference is an absolute path
from the root node to one of its descendants.

The reference of the root object is `^` itself.

Each level of path is represented with `ref_segment` that depends on the type of
the parent object of the `seg_segment`.

    reference      ::= "^" (ref_segment)*
    ---------          --- --------------
        ↓               ↓       ↓
    ---------          --- ------------
    reference      ::= "^" char_inline*

And the specific definition of `ref_segment` depends on the parent type, e.g.
`array` or `map`.

### Array

An array is represented as a list.

    array         ::= array_element*
    -----             --------------
     ↓                  ↓
    ----              -----
    list          ::= node*

To represent an array of array, the anonymous symbol `_` is introduced to
represent the anonymous parent of a child array.

    array_element ::= "_"    start array end
    -------------     ---    ----- ----- ---
     ↓                 ↓       ↓    ↓     ↓
    ----------        -----  ----- ----  ---
    value_list    ::= value (start list  end)?

e.g.

    -
        1
        2
        3
    -
        4
        5

The `ref_segment` for a child of an array is defined as below:

    ref_segment   ::= "[" array_index "]"
    array_index   ::= decimals

### Map
A map is represented with a list of key-value pairs. Each pair is represented as
a node.

    map        ::= key_value*
    ---            ----------
     ↓               ↓
    ----           -----
    list       ::= node*

The key in a key-value pair is encoded a `value` suffixed by a `:`, and the
value in a key-value pair is encoded as a `list`.

    key_value  ::= map_key ":" start map_value end
    ---------      ----------- ----- --------- ---
     ↓               ↓           ↓      ↓       ↓
    ----------     -----       -----   ----    ---
    value_list ::= value      (start   list    end)?

Encoding of `map_key`:

* identifier: [`raw_string`](#string)
* string: [`interpreted_string`](#string)
* boolean: [`boolean`](#boolean-value)
* numeric: [`numeric`](#numeric-value)
* others: implementation specific, as long as the encoding satisfies `value` and
the ending of the encoding is recognized without relying on the `:`.

The `ref_segment` for a child of a map depends on its `map_key`.

When the `map_key` is an identifier:

    ref_segment   ::= "[" array_index "]"
    array_index   ::= decimals

### Nil

The special `value` nil is used to represent an uninitialized nullable node.

    nil   ::= "nil"
    ---       -----
     ↓          ↓
    -----     ---------------------------
    value ::= [^\x00-\x20#^] char_inline*

### String
A string is represented as either a `raw_string` or an `interpreted_string` (double
quoted).

    string             ::= raw_string | interpreted_string
    ------                 -------------------------------
      ↓                               ↓
    -----                  ---------------------------
    value              ::= [^\x00-\x20#^] char_inline*

A string value can be represented as a `raw_string` if and only if:

* It is not empty.
* It does not starts with `char_space`, `#` or `^`.
* It only contains `char_inline`.

    raw_string         ::= value

An `interpreted_string` is quoted with double quotes `"` and can contain any
bytes by escape sequences.

    quoted_char        ::= (char_inline - '"') | '\\"'

    interpreted_string ::= '"' quoted_char* '"'
    ------------------     --------------------
      ↓                             ↓
    -----                  ---------------------------
    value              ::= [^\x00-\x20#^] char_inline*

#### Escape sequences

    \a    U+0007 alert or bell
    \b    U+0008 backspace
    \t    U+0009 horizontal tab
    \n    U+000A line feed or newline
    \v    U+000B vertical tab
    \f    U+000C form feed
    \r    U+000D carriage return
    \\    U+005C backslash
    \"    U+0022 double quote "
    \x    Any byte represented with two hexadecimal digits followed by \x
    \u    Unicode code point represented with exactly 4 hexadecimal digits followed by \u
    \U    Unicode code point represented with exactly 8 hexadecimal digits followed by \U

### Regular expression
A regular expression is a `value`. The syntax of regular expressions are
defined by [Golang Regexp](http://golang.org/pkg/regexp/syntax/).

### Boolean value
Boolean value is a `value` of either true of false.

    boolean ::= "true" | "false"
    -------     ----------------
      ↓                ↓
    -----       ---------------------------
    value   ::= [^\x00-\x20#^] char_inline*

### Numeric value
Numeric value is a `value` that encode a number.

    sign       ::= "+" | "-"
    decimals   ::= "0" | [1-9] [0-9]*

#### Integer
    integer    ::= sign? decimals
    -------        --------------
       ↓                 ↓
    -----          ---------------------------
    value      ::= [^\x00-\x20#^] char_inline*

#### Float
Float value is a `value` that encode a floating point number:

    exponent   ::= ( "e" | "E" ) ( "+" | "-" )? decimals
    float_base ::= (decimals "." decimal* exponent?) |
                   (decimals exponent) |
                   ("." decimals exponent?)

    float      ::= sign? float_base
    -----          ----------------
      ↓                   ↓
    -----          ---------------------------
    value      ::= [^\x00-\x20#^] char_inline*

#### Complex
    int_float  ::= decimals | float_base

    complex    ::= sign? int_float sign int_float "i"
    -------        ----------------------------------
      ↓                        ↓
    -----          ---------------------------
    value      ::= [^\x00-\x20#^] char_inline*

### Date/time (TODO: use a shorter representation)
A date/time value is an `value` encoded with
[RFC3339](http://www.rfc-editor.org/rfc/rfc3339.txt)

    date_time ::= rfc3339_date_time
    ---------     -----------------
      ↓                   ↓
    -----         ---------------------------
    value     ::= [^\x00-\x20#^] char_inline*

e.g.

    2006-01-02T15:04:05.999999999Z07:00

### IP address
An IP address is either an IPv4 or IPv6 address.

    ip    ::= ipv4 | ipv6

An IPv4 address value is an `value` encoded with dot-decimal notation:

    ipv4  ::= decimals "." decimals "." decimals "." decimals
    ----      -----------------------------------------------
     ↓                    ↓
    -----     ---------------------------
    value ::= [^\x00-\x20#^] char_inline*

e.g.

    74.125.19.99

An IPv6 address value is an `value` encoded with
[RFC5952](http://www.rfc-editor.org/rfc/rfc5952.txt).

    ipv6  ::= rfc5952_ipv6_address
    ----      --------------------
     ↓                 ↓
    -----     ---------------------------
    value ::= [^\x00-\x20#^] char_inline*

e.g.

    2001:4860:0:2001::68

### Multi-line String (TODO)

### Multi-line Regular Expressions (TODO)

### URL

### Custom extensions (TODO)
Custom encoding can be implemented as long as it does not conflict with the
built-in encodings.


text:
namespace ca {

OpenGLTimer::OpenGLTimer(const std::string& title, int queries) :
    title_(title), query_count_(queries), current_index_(0) {
    queries_ = new GLuint[queries];
    glGenQueries(query_count_, queries_);
}

OpenGLTimer::~OpenGLTimer() {
    glDeleteQueries(query_count_, queries_);
    delete queries_;
}

void OpenGLTimer::Begin(const std::string& label) {
    glBeginQuery(GL_TIME_ELAPSED, queries_[current_index_]);
    labels_.push_back(label);
}

void OpenGLTimer::End() {
    glEndQuery(GL_TIME_ELAPSED);
    current_index_++;
}

void OpenGLTimer::WaitForResults() {
    if (current_index_ == 0) return;
    GLint ready = 0;
    while (!ready) {
        glGetQueryObjectiv(queries_[current_index_ - 1],
                           GL_QUERY_RESULT_AVAILABLE,
                           &ready);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

GLuint OpenGLTimer::GetElapsedTime(int index) const {
    if (index < 0 || index >= current_index_) {
        return 0;
    }
    GLuint elapsed_time;
    glGetQueryObjectuiv(queries_[index], GL_QUERY_RESULT, &elapsed_time);
    return elapsed_time;
}

std::string OpenGLTimer::Report() {
    std::stringstream ss;
    GLuint total = 0;
    ss << "OpenGLTimer Report: " << title_ << std::endl;
    for (int i = 0; i < current_index_; i++) {
        const GLuint elapsed_time = GetElapsedTime(i);
        const std::string& label = labels_[i];
        ss << label << " : " << elapsed_time/1000 << " ms" << std::endl;
        total += elapsed_time;
    }
    ss << "Total elapsed: " << total/1000 << " ms" << std::endl;
    return ss.str();
}

}  // namespace ca

redpajama_set_name: RedPajamaGithub


text:
/*
 * vRouter Interfaces tab
 */
monitorInfraComputeInterfacesClass = (function() {

    var paginationInfo = {};
    /*
     * var vRouterInterfacesDS = new ContrailDataView();
     * function populatevRouterInterfacesDS(obj) {
     *     var transportCfg = {
     *         url:contrail.format(monitorInfraUrls['VROUTER_INTERFACES'], getIPOrHostName(obj),obj['introspectPort'])
     *     }
     *     getOutputByPagination(vRouterInterfacesDS, {
     *         transportCfg: transportCfg,
     *         paginationServer: 'introspect',
     *         parseFn: self.parseInterfaceData
     *     });
     * }
     */
    this.parseInterfaceData = function(response) {
        var retArray = [];
        var sandeshData = jsonPath(response,'$..ItfSandeshData');
        paginationInfo = getIntrospectPaginationInfo(response);
        updateGridTitleWithPagingInfo($('#gridComputeInterfaces'),paginationInfo);
        var sdata = [];
        if(sandeshData != null){
            $.each(sandeshData,function(idx,obj){
                if(!(obj instanceof Array)){
                    sdata = sdata.concat([obj]);
                } else {
                    sdata = sdata.concat(obj)
                }
            });

            $.each(sdata, function (idx, obj) {
                var rawJson = obj;
                obj['vn_name'] = ifNullOrEmptyObject(obj['vn_name'],noDataStr);
                obj['vm_uuid'] = ifNullOrEmptyObject(obj['vm_uuid'],noDataStr);
                obj['vm_name'] = ifNullOrEmptyObject(obj['vm_name'],noDataStr);

                var parts = obj['vn_name'].split(":"), dispVNName=obj['vn_name'];
                if(parts.length == 3){
                    if(parts[2] != null) {dispVNName = parts[2];}
                    if(parts[1] != null) {dispVNName += " ("+parts[1]+")";}
                }
                var dispVMName = obj['vm_uuid'] + ' / ' + obj['vm_name'];
                if(obj['vm_uuid'] == "" && obj['vm_name'] == "") {
                    dispVMName = '';
                }
                obj['dispName'] = obj['name'];
                if(new RegExp(/remote-physical-port/).test(obj['type'])) {
                    var parts = obj['name'].split(":");
                    if(parts.length == 3) {
                        if(parts[0] == 'default-global-system-config') {
                            obj['dispName'] = contrail.format('{0}
 ({1})',parts[2],parts[1]);
                        } else {
                        obj['dispName'] = contrail.format('{0}
 ({1}:{2})',parts[2],parts[0],parts[1]);
                        }
                    }
                }
                if(new RegExp(/logical-port/).test(obj['type'])) {
                    var parts = obj['name'].split(":");
                    if(parts.length == 4) {
                        if(parts[0] == 'default-global-system-config') {
                            obj['dispName'] = contrail.format('{0}
 ({1}:{2})',parts[3],parts[1],parts[2]);
                        } else {
                        obj['dispName'] = contrail.format('{0}
 ({1}:{2}:{3})',parts[3],parts[0],parts[1],parts[2]);
                        }
                    }
                }
                if(new RegExp(/vport|logical-port|remote-physical-port/).test(obj['type'])) {
                    if(obj.fip_list != null) {
                        var fipList = [];
                        fipList = ifNull(jsonPath(obj,"$..FloatingIpSandeshList")[0],[]);
                        obj['disp_fip_list'] = floatingIPCellTemplate(fipList);
                    }
                    retArray.push({uuid:obj['uuid'],name:obj['name'],label:obj['label'],active:obj['active'],
                        dispName: obj['dispName'],
                        type:obj['type'],
                        vn_name:obj['vn_name'],disp_vn_name:dispVNName,vm_uuid:obj['vm_uuid'],
                        vm_name:obj['vm_name'],disp_vm_name:dispVMName,ip_addr:obj['ip_addr'],
                        disp_fip_list:obj['disp_fip_list'],raw_json:rawJson});
                }
            });
        }
        return retArray;
    }

    function getPaginationInfo() {
        return paginationInfo;
    }

    function resetForm() {
        $('#gridComputeInterfaces').parent().find("[name='itfMac']").val('');
        $('#gridComputeInterfaces').parent().find("[name='itfNetwork']").val('');
        $('#gridComputeInterfaces').parent().find("[name='itfName']").val('');
        $('#gridComputeInterfaces').parent().find("[name='itfNetwork']").val('');
        if($('#itfType').length > 0 && $('#itfType').data('contrailDropdown') != null) {
            $('#itfType').data('contrailDropdown').value('');
        }
    }

    function constructvRouterIntfUrl(obj) {
        var vRouterIntfURL = monitorInfraUrls['VROUTER_INTERFACES'];
        var urlParams = {
            ip : getIPOrHostName(obj),
            introspectPort : obj['introspectPort'],
            name:'',
            type:'',
            uuid:'',
            vn:'',
            mac:'',
            ipv4_address:'',
            ipv6_address:'',
            parent_uuid:''
        }
        var itfMacFilter = $('#gridComputeInterfaces').parent().find("[name='itfMac']").val();
        if(itfMacFilter != null) {
            urlParams['mac'] = itfMacFilter.trim();
        }
        var itfNetworkFilter = $('#gridComputeInterfaces').parent().find("[name='itfNetwork']").val();
        if(itfNetworkFilter != null) {
            urlParams['vn'] = itfNetworkFilter.trim();
        }
        var itfNameFilter = $('#gridComputeInterfaces').parent().find("[name='itfName']").val();
        if(itfNameFilter != null) {
            urlParams['name'] = itfNameFilter.trim();
        }
        var itfTypeFilter = $('#gridComputeInterfaces').parent().find("[name='itfType']").val();
        if(itfTypeFilter != null) {
            if(itfTypeFilter == 'any') {
                urlParams['type'] = '';
            } else {
                urlParams['type'] = itfTypeFilter.trim();
            }
        }

        var itfIPFilter = $('#gridComputeInterfaces').parent().find("[name='itfIP']").val();
        if(isIPv4(itfIPFilter)) {
            urlParams['ipv4_address'] = itfIPFilter.trim();
        }
        if(isIPv6(itfIPFilter)) {
            urlParams['ipv6_address'] = itfIPFilter.trim();
        }
        return {
            url: vRouterIntfURL,
            params:urlParams
        }
    }

    this.populateInterfaceTab = function (obj) {
        //Push only tab & node parameter in URL
        layoutHandler.setURLHashParams({tab:'interfaces',node:obj['name']},{triggerHashChange:false});

        if (!isGridInitialized('#gridComputeInterfaces')) {
            $('#itfType').contrailDropdown({
                data: [{
                    id:'any',
                    text:'Any'
                },{
                    id:'vmi',
                    text:'vport'
                },{
                    id:'physical',
                    text:'remote-physical-port'
                },{
                    id:'logical',
                    text:'logical-port'
                }]
            });
            $('#itfType').select2('val','any');
            $('#gridComputeInterfaces').contrailGrid({
                header : {
                    title : {
                        text : 'Interfaces'
                    },
                    customControls: [
                                    '',
                                    '',
                                    '',
                                    '',
                            ]
                },
                columnHeader: {
                   columns:[
                       {
                           field:"dispName",
                           name:"Name",
                           minWidth:125,
                           formatter:function(r,c,v,cd,dc) {
                               return v;
                           },
                           searchFn:function(d){
                               return d['dispName'];
                           }
                       },
                       {
                           field:"label",
                           name:"Label",
                           minWidth:50
                       },
                       {
                           field:"active",
                           name:"Status",
                           minWidth:50,
                           //template:cellTemplate({cellText:'#= (active == "Active")? "Up": "Down"#', tooltip:false}),
                           formatter: function(r,c,v,cd,dc) {
                              if(dc['active'] == 'Active')
                                 return 'Up';
                              else
                                 return 'Down'
                           },
                           searchFn:function(d){
                               var status = 'Down';
                               if(d['active'] == 'Active')
                                   status = 'Up';
                               return status;
                           }
                       },
                       {
                           field:"type",
                           name:"Type",
                           minWidth:130
                       },
                       {
                           field:"disp_vn_name",
                           name:"Network",
                           cssClass: 'cell-hyperlink-blue',
                           events: {
                               onClick: function(e,dc){
                                   var tabIdx = $.inArray("networks", computeNodeTabs);
                                   selectTab(computeNodeTabStrip,tabIdx);
                               }
                            },
                           minWidth:120
                       },
                       {
                           field:"ip_addr",
                           name:"IP Address",
                           minWidth:100,
                           formatter:function(r,c,v,cd,dc) {
                               var ipColumnContent = '',breakStmt = false;
                               if(dc['ip_addr'] != '0.0.0.0') {
                                   ipColumnContent = getLabelValueForIP(dc['ip_addr']);
                                   breakStmt = true;
                               }
                               if(dc['raw_json']['ip6_active'] == 'Active') {
                                   if(breakStmt)
                                       ipColumnContent += "
"+getLabelValueForIP(dc['raw_json']['ip6_addr']);
                                   else
                                       ipColumnContent += getLabelValueForIP(dc['raw_json']['ip6_addr']);
                               }
                               return ipColumnContent;
                           }
                       },
                       {
                           field:"disp_fip_list",
                           name:"Floating IP",
                           minWidth:100
                       },
                       {
                           field:"disp_vm_name",
                           name:"Instance",
                           cssClass: 'cell-hyperlink-blue',
                           //template:cellTemplate({cellText:'#= disp_vm_name #', name:'instance', tooltip:true}),
                           formatter:function(r,c,v,cd,dc) {
                              return cellTemplateLinks({cellText:'disp_vm_name',name:'name',rowData:dc});
                           },
                           events: {
                              onClick: function(e,dc) {
                                if(dc['vm_name'] != null && dc['vm_name'].trim() != '') {
                                  setInstanceURLHashParams(null, dc['vn_name'], dc['vm_uuid'], true);
                                  //layoutHandler.setURLHashParams({vmName:dc['vm_name'],fqName:dc['vm_uuid'],srcVN:dc['vn_name']},{p:'mon_networking_instances',merge:false,triggerHashChange:true});
                                }
                              }
                           },
                           minWidth:200
                       }
                   ],
                },
                body: {
                   options: {
                      forceFitColumns: true,
                      detail: {
                         template: $('#gridsTemplateJSONDetails').html()
                      },
                      actionCell: [
                                   {
                                       title: 'Start Packet Capture',
                                       //iconClass: 'icon-cog',
                                       onClick: function(rowIndex){
                                           var rowData = intfGrid._dataView.getItem(rowIndex);
                                           startPacketCapture4Interface(rowData['uuid'],rowData['vn_name'],rowData['vm_name']);
                                       }
                                   }
                               ]
                   },
                    dataSource : {
                        remote: {
                            ajaxConfig: {
                                url: monitorInfraUrls['VROUTER_INTERFACES']  + '?' + $.param({
                                      ip: getIPOrHostName(obj),
                                      introspectPort: obj['introspectPort']}),
                                type: 'GET'
                            },
                            dataParser: self.parseInterfaceData
                        },
                        events: {
                            onDataBoundCB: function() {
                                intfGrid.removeGridMessage('loading');
                            }
                        }
                    },
                    statusMessages: {
                        loading: {
                            text: 'Loading Interfaces..',
                        },
                        empty: {
                            text: 'No Interfaces to display'
                        },
                        errorGettingData: {
                            type: 'error',
                            iconClasses: 'icon-warning',
                            text: 'Error in getting Data.'
                        }
                    }
                },
                footer : false
                //change:onIntfChange,
            })
            intfGrid = $('#gridComputeInterfaces').data('contrailGrid');
            intfGrid.showGridMessage('loading');
            bindGridPrevNextListeners({
                gridSel: $('#gridComputeInterfaces'),
                resetFn: resetForm,
                paginationInfoFn:getPaginationInfo,
                obj: obj,
                getUrlFn: function() {
                    return constructvRouterIntfUrl(obj);
                }
            });
            var interfaceGridObj = $("#gridComputeInterfaces").data('contrailGrid');
            function adjustInterfaceGridRowHeight() {
                if($('#gridComputeInterfaces').find('.input-searchbox input').val() != null && interfaceGridObj != null)
                    interfaceGridObj.adjustAllRowHeight();
            }
            if(interfaceGridObj != null) {
                interfaceGridObj._dataView.onDataUpdate.unsubscribe(adjustInterfaceGridRowHeight);
                interfaceGridObj._dataView.onDataUpdate.subscribe(adjustInterfaceGridRowHeight);
            }
            //applyGridDefHandlers(intfGrid, {noMsg:'No interfaces to display'});
        } else {
            reloadGrid(intfGrid);
        }
    }
    return {populateInterfaceTab:populateInterfaceTab,
        parseInterfaceData:parseInterfaceData};
})();


text:
/*	$OpenBSD: isp_sbus.c,v 1.7 1999/03/25 22:58:37 mjacob Exp $	*/
/* release_03_25_99 */
/*
 * SBus specific probe and attach routines for Qlogic ISP SCSI adapters.
 *
 * Copyright (c) 1997 by Matthew Jacob
 * NASA AMES Research Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice immediately at the beginning of the file, without modification,
 *    this list of conditions, and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/queue.h>

#include <machine/autoconf.h>
#include <machine/cpu.h>
#include <machine/param.h>
#include <machine/vmparam.h>
#include <sparc/sparc/cpuvar.h>

#include <dev/ic/isp_openbsd.h>
#include <dev/microcode/isp/asm_sbus.h>

static u_int16_t isp_sbus_rd_reg __P((struct ispsoftc *, int));
static void isp_sbus_wr_reg __P((struct ispsoftc *, int, u_int16_t));
static int isp_sbus_mbxdma __P((struct ispsoftc *));
static int isp_sbus_dmasetup __P((struct ispsoftc *, struct scsi_xfer *,
	ispreq_t *, u_int8_t *, u_int8_t));
static void isp_sbus_dmateardown __P((struct ispsoftc *, struct scsi_xfer *,
	u_int32_t));

static struct ispmdvec mdvec = {
	isp_sbus_rd_reg,
	isp_sbus_wr_reg,
	isp_sbus_mbxdma,
	isp_sbus_dmasetup,
	isp_sbus_dmateardown,
	NULL,
	NULL,
	NULL,
	ISP_RISC_CODE,
	ISP_CODE_LENGTH,
	ISP_CODE_ORG,
	ISP_CODE_VERSION,
	BIU_BURST_ENABLE,
	0
};

struct isp_sbussoftc {
	struct ispsoftc	sbus_isp;
	sdparam		sbus_dev;
	struct intrhand sbus_ih;
	volatile u_char *sbus_reg;
	int		sbus_node;
	int		sbus_pri;
	struct ispmdvec	sbus_mdvec;
	vm_offset_t	sbus_kdma_allocs[MAXISPREQUEST];
	int16_t		sbus_poff[_NREG_BLKS];
};

static int isp_match __P((struct device *, void *, void *));
static void isp_sbus_attach __P((struct device *, struct device *, void *));
struct cfattach isp_sbus_ca = {
	sizeof (struct isp_sbussoftc), isp_match, isp_sbus_attach
};

static int
isp_match(parent, cfarg, aux)
        struct device *parent;
	void *cfarg;
        void *aux;
{
	int rv;
	struct cfdata *cf = cfarg;
#ifdef DEBUG
	static int oneshot = 1;
#endif
	struct confargs *ca = aux;
	register struct romaux *ra = &ca->ca_ra;

	rv = (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0 ||
		strcmp("PTI,ptisp", ra->ra_name) == 0 ||
		strcmp("ptisp", ra->ra_name) == 0 ||
		strcmp("SUNW,isp", ra->ra_name) == 0 ||
		strcmp("QLGC,isp", ra->ra_name) == 0);
	if (rv == 0)
		return (rv);
#ifdef DEBUG
	if (rv && oneshot) {
		oneshot = 0;
		printf("Qlogic ISP Driver, NetBSD (sbus) Platform Version "
		    "%d.%d Core Version %d.%d\n",
		    ISP_PLATFORM_VERSION_MAJOR, ISP_PLATFORM_VERSION_MINOR,
		    ISP_CORE_VERSION_MAJOR, ISP_CORE_VERSION_MINOR);
	}
#endif
	if (ca->ca_bustype == BUS_SBUS)
		return (1);
	ra->ra_len = NBPG;
	return (probeget(ra->ra_vaddr, 1) != -1);
}

static void
isp_sbus_attach(parent, self, aux)
        struct device *parent, *self;
        void *aux;
{
	int freq;
	struct confargs *ca = aux;
	struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) self;
	struct ispsoftc *isp = &sbc->sbus_isp;
	ISP_LOCKVAL_DECL;

	if (ca->ca_ra.ra_nintr != 1) {
		printf(": expected 1 interrupt, got %d\n", ca->ca_ra.ra_nintr);
		return;
	}

	printf("\n");

	sbc->sbus_pri = ca->ca_ra.ra_intr[0].int_pri;
	sbc->sbus_mdvec = mdvec;

	if (ca->ca_ra.ra_vaddr) {
		sbc->sbus_reg = (volatile u_char *) ca->ca_ra.ra_vaddr;
	} else {
		sbc->sbus_reg = (volatile u_char *)
			mapiodev(ca->ca_ra.ra_reg, 0, ca->ca_ra.ra_len);
	}
	sbc->sbus_node = ca->ca_ra.ra_node;

	freq = getpropint(ca->ca_ra.ra_node, "clock-frequency", 0);
	if (freq) {
		/*
		 * Convert from HZ to MHz, rounding up.
		 */
		freq = (freq + 500000)/1000000;
#if	0
		printf("%s: %d MHz\n", self->dv_xname, freq);
#endif
	}
	sbc->sbus_mdvec.dv_clock = freq;

	/*
	 * XXX: Now figure out what the proper burst sizes, etc., to use.
	 */
	sbc->sbus_mdvec.dv_conf1 |= BIU_SBUS_CONF1_FIFO_8;

	/*
	 * Some early versions of the PTI SBus adapter
	 * would fail in trying to download (via poking)
	 * FW. We give up on them.
	 */
	if (strcmp("PTI,ptisp", ca->ca_ra.ra_name) == 0 ||
	    strcmp("ptisp", ca->ca_ra.ra_name) == 0) {
		sbc->sbus_mdvec.dv_fwlen = 0;
	}

	isp->isp_mdvec = &sbc->sbus_mdvec;
	isp->isp_bustype = ISP_BT_SBUS;
	isp->isp_type = ISP_HA_SCSI_UNKNOWN;
	isp->isp_param = &sbc->sbus_dev;
	bzero(isp->isp_param, sizeof (sdparam));

	sbc->sbus_poff[BIU_BLOCK >> _BLK_REG_SHFT] = BIU_REGS_OFF;
	sbc->sbus_poff[MBOX_BLOCK >> _BLK_REG_SHFT] = SBUS_MBOX_REGS_OFF;
	sbc->sbus_poff[SXP_BLOCK >> _BLK_REG_SHFT] = SBUS_SXP_REGS_OFF;
	sbc->sbus_poff[RISC_BLOCK >> _BLK_REG_SHFT] = SBUS_RISC_REGS_OFF;
	sbc->sbus_poff[DMA_BLOCK >> _BLK_REG_SHFT] = DMA_REGS_OFF;

	/* Establish interrupt channel */
	sbc->sbus_ih.ih_fun = (void *) isp_intr;
	sbc->sbus_ih.ih_arg = sbc;
	intr_establish(sbc->sbus_pri, &sbc->sbus_ih);

	ISP_LOCK(isp);
	isp_reset(isp);
	if (isp->isp_state != ISP_RESETSTATE) {
		ISP_UNLOCK(isp);
		return;
	}
	isp_init(isp);
	if (isp->isp_state != ISP_INITSTATE) {
		isp_uninit(isp);
		ISP_UNLOCK(isp);
		return;
	}
	/*
	 * do generic attach.
	 */
	isp_attach(isp);
	if (isp->isp_state != ISP_RUNSTATE) {
		isp_uninit(isp);
	}
	ISP_UNLOCK(isp);
}

static u_int16_t
isp_sbus_rd_reg(isp, regoff)
	struct ispsoftc *isp;
	int regoff;
{
	struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
	int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT];
	offset += (regoff & 0xff);
	return (*((u_int16_t *) &sbc->sbus_reg[offset]));
}

static void
isp_sbus_wr_reg (isp, regoff, val)
	struct ispsoftc *isp;
	int regoff;
	u_int16_t val;
{
	struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
	int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT];
	offset += (regoff & 0xff);
	*((u_int16_t *) &sbc->sbus_reg[offset]) = val;
}

static int
isp_sbus_mbxdma(isp)
	struct ispsoftc *isp;
{
	size_t len;

	/*
	 * NOTE: Since most Sun machines aren't I/O coherent,
	 * map the mailboxes through kdvma space to force them
	 * to be uncached.
	 */

	/*
	 * Allocate and map the request queue.
	 */
	len = ISP_QUEUE_SIZE(RQUEST_QUEUE_LEN);
	isp->isp_rquest = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT);
	if (isp->isp_rquest == 0)
		return (1);
	isp->isp_rquest_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_rquest,
	    len, 0);
	if (isp->isp_rquest_dma == 0)
		return (1);

	/*
	 * Allocate and map the result queue.
	 */
	len = ISP_QUEUE_SIZE(RESULT_QUEUE_LEN);
	isp->isp_result = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT);
	if (isp->isp_result == 0)
		return (1);
	isp->isp_result_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_result,
	    len, 0);
	if (isp->isp_result_dma == 0)
		return (1);

	return (0);
}

/*
 * TODO: If kdvma_mapin fails, try using multiple smaller chunks..
 */

static int
isp_sbus_dmasetup(isp, xs, rq, iptrp, optr)
	struct ispsoftc *isp;
	struct scsi_xfer *xs;
	ispreq_t *rq;
	u_int8_t *iptrp;
	u_int8_t optr;
{
	struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
	vm_offset_t kdvma;
	int dosleep = (xs->flags & SCSI_NOSLEEP) != 0;

	if (xs->datalen == 0) {
		rq->req_seg_count = 1;
		return (CMD_QUEUED);
	}

	if (rq->req_handle > RQUEST_QUEUE_LEN ||
	    rq->req_handle < 1) {
		panic("%s: bad handle (%d) in isp_sbus_dmasetup\n",
			isp->isp_name, rq->req_handle);
		/* NOTREACHED */
	}
	if (CPU_ISSUN4M) {
		kdvma = (vm_offset_t)
			kdvma_mapin((caddr_t)xs->data, xs->datalen, dosleep);
		if (kdvma == (vm_offset_t) 0) {
			XS_SETERR(xs, HBA_BOTCH);
			return (CMD_COMPLETE);
		}
	} else {
		kdvma = (vm_offset_t) xs->data;
	}

	if (sbc->sbus_kdma_allocs[rq->req_handle - 1] != (vm_offset_t) 0) {
		panic("%s: kdma handle already allocated\n", isp->isp_name);
		/* NOTREACHED */
	}
	sbc->sbus_kdma_allocs[rq->req_handle - 1] = kdvma;
	if (xs->flags & SCSI_DATA_IN) {
		rq->req_flags |= REQFLAG_DATA_IN;
	} else {
		rq->req_flags |= REQFLAG_DATA_OUT;
	}
	rq->req_dataseg[0].ds_count = xs->datalen;
	rq->req_dataseg[0].ds_base =  (u_int32_t) kdvma;
	rq->req_seg_count = 1;
	return (CMD_QUEUED);
}

static void
isp_sbus_dmateardown(isp, xs, handle)
	struct ispsoftc *isp;
	struct scsi_xfer *xs;
	u_int32_t handle;
{
	struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
	vm_offset_t kdvma;

	if (xs->flags & SCSI_DATA_IN) {
		cpuinfo.cache_flush(xs->data, xs->datalen - xs->resid);
	}
	if (handle >= RQUEST_QUEUE_LEN) {
		panic("%s: bad handle (%d) in isp_sbus_dmateardown\n",
			isp->isp_name, handle);
		/* NOTREACHED */
	}
	if (sbc->sbus_kdma_allocs[handle] == (vm_offset_t) 0) {
		panic("%s: kdma handle not already allocated\n", isp->isp_name);
		/* NOTREACHED */
	}
	kdvma = sbc->sbus_kdma_allocs[handle];
	sbc->sbus_kdma_allocs[handle] = (vm_offset_t) 0;
	if (CPU_ISSUN4M) {
		dvma_mapout(kdvma, (vm_offset_t) xs->data, xs->datalen);
	}
}


text:
"use strict";

import chai, { expect } from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);
const assert = chai.assert;

import { uuid } from 'utils';

import { serialize, deserialize } from 'src/client/serialize.js';

describe('simple serialization with JSON.{parse,stringify}', () => {

  it('exports defined', () => {
    expect(serialize).to.be.defined;
    expect(deserialize).to.be.defined;
  });

  it('simple case', () => {
    const o = { prop: 42 };
    const o2 = deserialize(serialize(o));

    assert.notStrictEqual(o, o2);
    assert.strictEqual(o.prop, o2.prop);
  });

  it('empty key', () => {
    const o = { '': 42 };
    const o2 = deserialize(serialize(o));

    assert.notStrictEqual(o, o2);
    assert.strictEqual(o[''], o2['']);
  });

  it('2 ref on 1 object', () => {
    const referredObject = {};
    const o = {
      a: referredObject,
      b: referredObject
    };
    const o2 = deserialize(serialize(o));

    assert.strictEqual(o2.a, o2.b);
  });

  it('cyclic inclusion', () => {
    const o = {
      prop: 42
    };
    o.recursive = o;
    const o2 = deserialize(serialize(o));

    assert.notStrictEqual(o, o2);
    assert.strictEqual(o.prop, o2.prop);
    assert.strictEqual(o2, o2.recursive);
  });

  it('double cyclic inclusion', () => {
    const a = {};
    const b = { a };
    a.b = b;
    const a2 = deserialize(serialize(a));

    assert.strictEqual(a2.b.a, a2);
    assert.strictEqual(a2.b, a2.b.a.b);
  });

  it('clean $id and $ref', () => {
    const o = {
      prop: 42
    };
    o.recursive = o;
    const o2 = deserialize(serialize(o));

    expect(o).not.to.have.property('$id');
    expect(o).not.to.have.property('$ref');
    expect(o2).not.to.have.property('$id');
    expect(o2).not.to.have.property('$ref');
  });

  it('restore classes and clean up $class', () => {
    class A {
      get foo() {
        return 42;
      }
    }
    class B {
      get foo() {
        return 42;
      }
    }
    const a = new A();
    a.b = new B();
    a.b.a = a;
    const a2 = deserialize(serialize(a), { A, B });

    expect(a).not.to.have.property('$class');
    expect(a2).not.to.have.property('$class');
    expect(a2 instanceof A).to.be.true;
    expect(a2.b instanceof B).to.be.true;
  });

  it('restore Arrays', () => {
    const o = {
      arr: [1, 2, 3]
    };
    const o2 = deserialize(serialize(o));

    expect(o.arr).not.to.have.property('$class');
    expect(o2.arr).not.to.have.property('$class');
    expect(o).not.to.have.property('$isArray');
    expect(o2).not.to.have.property('$isArray');
    expect(o).not.to.have.property('$array');
    expect(o2).not.to.have.property('$array');

    expect(Array.isArray(o2.arr)).to.be.true;
    expect(o2.arr).to.deep.equal(o.arr);
    expect(o2.arr).to.not.equal(o.arr);
  });

  it('top-level array', () => {
    const a = [1, 2, 3];
    const a2 = deserialize(serialize(a));

    expect(Array.isArray(a2)).to.be.true;
    expect(a2).to.deep.equal(a);
  });

  it('nested arrays', () => {
    const a = [1, 2, [3, 4]];
    a[2].push(a);
    a.push(a[2]);

    const a2 = deserialize(serialize(a));
    expect(a2).to.deep.equal(a);
  });

  it('arrays with cyclic dependencies', () => {
    class A {}
    const a = [1, 2, new A()];
    a.push(a);
    const a2 = deserialize(serialize(a), { A });

    expect(a2).to.deep.equal(a);
    expect(a2[2] instanceof A).to.be.true;
  });

  describe('outerReplacer/outerReviver', () => {

    it('custom $external reference', () => {
      class MyObject {}
      const o1 = new MyObject();
      const o2 = new MyObject();

      o1.o2 = o2;
      o1.o1 = o1;
      const o = { o1, o2 };
      const refIdToObj = new Map();
      const objToRef = new Map();
      let refId = 0;
      class Reference {
        static for(obj) {
          const ref = objToRef.getOrCreate(obj, () => new Reference());
          refIdToObj.set(ref.id, obj);
          return ref;
        }
        constructor() {
          this.id = refId++;
        }
        restore() {
          return refIdToObj.get(this.id);
        }
      }

      function outerReplacer(key, value) {
        if (value instanceof MyObject) {
          value = Reference.for(value);
        }
        return value;
      }
      function outerReviver(key, value) {
        if (value instanceof Reference) {
          value = value.restore();
        }
        return value;
      }
      const revivedO = deserialize(serialize(o, outerReplacer), { Reference }, outerReviver);

      expect(revivedO).to.deep.equal(o);
      expect(revivedO).to.not.be.equal(o);
      expect(revivedO === o).to.be.false;
      expect(revivedO.o1 === o.o1).to.be.true;
      expect(revivedO.o2 === o.o2).to.be.true;
    });

    it('implementing a reference class', () => {
      class Battler {
        constructor() {
          this.id = uuid();
        }
      }
      const o1 = new Battler();
      const o2 = new Battler();

      o1.o2 = o2;
      o1.o1 = o1;
      const o = { o1, sub: { o2 } };
      class BattlerReference {
        static get refToObj() {
          return this._refToObj = this._refToObj || new Map();
        }
        static for(obj) {
          BattlerReference.refToObj.set(obj.id, obj);
          return new BattlerReference(obj);
        }
        constructor(o) {
          this.id = o.id;
        }
        restore() {
          return BattlerReference.refToObj.get(this.id);
        }
      }

      function outerReplacer(key, value) {
        if (value instanceof Battler) {
          const ref = BattlerReference.for(value);
          return ref;
        }
        return value;
      }
      function outerReviver(key, value) {
        if (value instanceof BattlerReference) {
          value = value.restore();
        }
        return value;
      }
      const revivedO = deserialize(serialize(o, outerReplacer), { BattlerReference }, outerReviver);

      expect(revivedO).to.deep.equal(o);
      expect(revivedO).to.not.be.equal(o);
      expect(revivedO === o).to.be.false;
      expect(revivedO.o1 === o.o1).to.be.true;
      expect(revivedO.sub.o2 === o.sub.o2).to.be.true;
    });
  });
});


text:
package org.apache.sling.scripting.sightly.impl.engine;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.scripting.sightly.extension.RuntimeExtension;
import org.osgi.framework.Constants;

/**
 * Aggregator for all runtime extensions.
 */
@Component
@Service(ExtensionRegistryService.class)
@Reference(
        policy = ReferencePolicy.DYNAMIC,
        referenceInterface = RuntimeExtension.class,
        name = "extensionService",
        cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE
)
public class ExtensionRegistryService {

    private volatile Map<String, RuntimeExtension> mapping = new HashMap<String, RuntimeExtension>();
    private Map<String, Integer> mappingPriorities = new HashMap<String, Integer>(10, 0.9f);

    public Map<String, RuntimeExtension> extensions() {
        return mapping;
    }

    @SuppressWarnings("UnusedDeclaration")
    protected synchronized void bindExtensionService(RuntimeExtension extension, Map<String, Object> properties) {
        Integer newPriority = PropertiesUtil.toInteger(properties.get(Constants.SERVICE_RANKING), 0);
        String extensionName = PropertiesUtil.toString(properties.get(RuntimeExtension.NAME), "");
        Integer priority = PropertiesUtil.toInteger(mappingPriorities.get(extensionName), 0);
        if (newPriority > priority) {
                mapping = Collections.unmodifiableMap(add(mapping, extension, extensionName));
                mappingPriorities.put(extensionName, newPriority);
        } else {
            if (!mapping.containsKey(extensionName)) {
                mapping = Collections.unmodifiableMap(add(mapping, extension, extensionName));
                mappingPriorities.put(extensionName, newPriority);
            }
        }

    }

    @SuppressWarnings("UnusedDeclaration")
    protected synchronized void unbindExtensionService(RuntimeExtension extension, Map<String, Object> properties) {
        String extensionName = PropertiesUtil.toString(properties.get(RuntimeExtension.NAME), "");
        mappingPriorities.remove(extensionName);
        mapping = Collections.unmodifiableMap(remove(mapping, extensionName));
    }

    private Map<String, RuntimeExtension> add(Map<String, RuntimeExtension> oldMap, RuntimeExtension extension, String extensionName) {
        HashMap<String, RuntimeExtension> newMap = new HashMap<String, RuntimeExtension>(oldMap);
        newMap.put(extensionName, extension);
        return newMap;
    }

    private Map<String, RuntimeExtension> remove(Map<String, RuntimeExtension> oldMap, String extensionName) {
        HashMap<String, RuntimeExtension> newMap = new HashMap<String, RuntimeExtension>(oldMap);
        newMap.remove(extensionName);
        return newMap;
    }
}


text:
// Type definitions for react-native-calendar v1.7.0
// Typescript version: 3.0

type ISODateString = string;
export type AuthorizationStatus =
  | "denied"
  | "restricted"
  | "authorized"
  | "undetermined";
export type RecurrenceFrequency = "daily" | "weekly" | "monthly" | "yearly";

/** iOS ONLY - GeoFenced alarm location */
interface AlarmStructuredLocation {
  /** The title of the location. */
  title: string;
  /** A value indicating how a location-based alarm is triggered. */
  proximity: "enter" | "leave" | "none";
  /** A minimum distance from the core location that would trigger the calendar event's alarm. */
  radius: number;
  /** The geolocation coordinates, as an object with latitude and longitude properties. */
  coords: { latitude: number; longitude: number };
}

export interface Options {
  /** The start date of a recurring event's exception instance. Used for updating single event in a recurring series. */
  exceptionDate?: ISODateString;
  /** iOS ONLY - If true the update will span all future events. If false it only update the single instance. */
  futureEvents?: boolean;
  /** ANDROID ONLY - If true, can help avoid syncing issues */
  sync?: boolean;
}

interface Alarm<D = ISODateString | number> {
  /** When saving an event, if a Date is given, an alarm will be set with an absolute date. If a Number is given, an alarm will be set with a relative offset (in minutes) from the start date. When reading an event this will always be an ISO Date string */
  date: D;
  /** iOS ONLY - The location to trigger an alarm. */
  structuredLocation?: AlarmStructuredLocation;
}

interface RecurrenceRule {
  /** Event recurring frequency. */
  frequency: RecurrenceFrequency;
  /** Event recurring end date. This overrides occurrence. */
  endDate: ISODateString;
  /** Number of event occurrences */
  occurrence: number;
  /** The interval between events of this recurrence. */
  interval: number;
}

interface Attendee {
  /** The name of the attendee. */
  name: string;
  /** The email address of the attendee. */
  email: string;
  /** iOS ONLY - The The phone number of the attendee. */
  phone?: string;
}

interface Calendar {
  /** Unique calendar ID. */
  id: string;
  /** The calendar's title. */
  title: string;
  /** The calendar's type. */
  type: string;
  /** The source object representing the account to which this calendar belongs. */
  source: string;
  /** Indicates if the calendar is assigned as primary. */
  isPrimary: boolean;
  /** Indicates if the calendar allows events to be written, edited or removed. */
  allowsModifications: boolean;
  /** The color assigned to the calendar represented as a hex value. */
  color: string;
  /** The event availability settings supported by the calendar. */
  allowedAvailabilities: string[];
}

interface CalendarEventBase {
  /** The start date of the calendar event in ISO format */
  startDate: ISODateString;
  /** The end date of the calendar event in ISO format. */
  endDate?: ISODateString;
  /** Unique id for the calendar where the event will be saved. Defaults to the device's default  calendar. */
  calendarId?: string;
  /** Indicates whether the event is an all-day event. */
  allDay?: boolean;
  /** The simple recurrence frequency of the calendar event. */
  recurrence?: RecurrenceFrequency;
  /** The location associated with the calendar event. */
  location?: string;
  /** iOS ONLY - The location with coordinates. */
  structuredLocation?: AlarmStructuredLocation;
  /** iOS ONLY - Indicates whether an event is a detached instance of a repeating event. */
  isDetached?: boolean;
  /** iOS ONLY - The url associated with the calendar event. */
  url?: string;
  /** iOS ONLY - The notes associated with the calendar event. */
  notes?: string;
  /** ANDROID ONLY - The description associated with the calendar event. */
  description?: string;
  /** iOS ONLY - The time zone associated with the event */
  timeZone?: string;
}

export interface CalendarEventReadable extends CalendarEventBase {
  /** Unique id for the calendar event */
  id: string;
  /** The title for the calendar event. */
  title: string;
  /** The attendees of the event, including the organizer. */
  attendees?: Attendee[];
  /** The calendar containing the event */
  calendar?: Calendar;
  /** iOS ONLY - The original occurrence date of an event if it is part of a recurring series. */
  occurrenceDate?: ISODateString;
  /** The alarms associated with the calendar event, as an array of alarm objects. */
  alarms?: Array<Alarm<ISODateString>>;
}

export interface CalendarEventWritable extends CalendarEventBase {
  /** Unique id for the calendar event, used for updating existing events */
  id?: string;
  /** The event's recurrence settings */
  recurrenceRule?: RecurrenceRule;
  /** The alarms associated with the calendar event, as an array of alarm objects. */
  alarms?: Array<Alarm<ISODateString | number>>;
}

export interface CalendarOptions {
  /** The calendar title */
  title: string;
  /** The calendar color */
  color: string;
  /** iOS ONLY - Entity type for the calendar */
  entityType: CalendarEntityTypeiOS;
  /** Android ONLY - The calendar name */
  name: string;
  /** Android ONLY - Defines how the event shows up for others when the calendar is shared */
  accessLevel: CalendarAccessLevelAndroid;
  /** Android ONLY - The owner account for this calendar, based on the calendar feed */
  ownerAccount: string;
  /** Android ONLY - The calendar Account source */
  source: CalendarAccountSourceAndroid;
}

export type CalendarEntityTypeiOS = "event" | "reminder";

export type CalendarAccessLevelAndroid =
  | "contributor"
  | "editor"
  | "freebusy"
  | "override"
  | "owner"
  | "read"
  | "respond"
  | "root";

export type CalendarAccountSourceAndroid =
  | {
      /** The Account name */
      name: string;
      /** The Account type */
      type: string;
    }
  | {
      /** The Account name */
      name: string;
      /** The source (required if source.type is not used) */
      isLocalAccount: boolean;
    };

export default class ReactNativeCalendarEvents {
  /**
   * Get calendar authorization status.
   * @param readOnly - optional, default false, use true to check for calendar read-only vs calendar read/write. Android-specific, iOS is always read/write
   */
  static checkPermissions(readOnly?: boolean): Promise<AuthorizationStatus>;
  /**
   * Request calendar authorization. Authorization must be granted before accessing calendar events.
   * @param readOnly - optional, default false, use true to request for calendar read-only vs calendar read/write. Android-specific, iOS is always read/write
   */
  static requestPermissions(readOnly?: boolean): Promise<AuthorizationStatus>;

  /** Finds all the calendars on the device. */
  static findCalendars(): Promise<Calendar[]>;
  /** Create a calendar.
   * @param calendar - Calendar to create
   */
  static saveCalendar(calendar: CalendarOptions): Promise<string>;
  /**
   * Removes a calendar.
   * @param id - The calendar id
   * @returns - Promise resolving to boolean to indicate if removal succeeded.
   */
  static removeCalendar(id: string): Promise<boolean>;
  /**
   * Find calendar  by id.
   * @param id - Calendar ID
   */
  static findEventById(id: string): Promise<CalendarEventReadable | null>;
  /**
   * Fetch all calendar events.
   * @param startDate - Date string in ISO format
   * @param endDate - Date string in ISO format
   * @param [calendarIds] - List of calendar id strings to specify calendar events. Defaults to all calendars if empty.
   */
  static fetchAllEvents(
    startDate: ISODateString,
    endDate: ISODateString,
    calendarIds?: string[]
  ): Promise<CalendarEventReadable[]>;
  /**
   * Creates or updates a calendar event. To update an event, the event id must be defined.
   * @param title - The title of the event
   * @param details - Event details
   * @param [options] - Options specific to the saved event.
   * @returns - Promise resolving to saved event's ID.
   */
  static saveEvent(
    title: string,
    details: CalendarEventWritable,
    options?: Options
  ): Promise<string>;
  /**
   * Removes calendar event.
   * @param id - The event id
   * @param [options] - Options specific to the saved event.
   * @returns - Promise resolving to boolean to indicate if removal succeeded.
   */
  static removeEvent(id: string, options?: Options): Promise<boolean>;
}


text:
/*
 * client.c
 *
 *  Created on: Nov 22, 2011
 *      Author: victor
 */
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <time.h>
#include "RSAChat.h"
#include "client.h"
#include "server.h"
#include "utils.h"

// Global variable
client_session *cs;
server_session *ss;

/**
 * Start a new client
 *
 * @param host hostname of server
 * @param port port number
 */
void chat_client_start(prog_args *args) {
	int server_socket_fd = -1;
	struct thread_info *tinfo;
	pthread_t threadID;

	// Init sessions
	if((cs = malloc(sizeof(client_session))) == NULL)
		M_EXIT_ON_ERROR("Can't allocate memory");

	if ((ss = malloc(sizeof(server_session))) == NULL)
		M_EXIT_ON_ERROR("Can't allocate memory");

	cs->nickname = args->nick;

	// Get keys from DB
	cs->rsa_priv_key = key_get_private_key(args->db, args->nick);
	cs->rsa_pub_key  = key_get_public_key(args->db, args->nick);
	M_PRINT_STATUS("Got own RSA key from DB\n");

	// Allocate mem for struct thread_info
	if ((tinfo = malloc(sizeof(struct thread_info))) == NULL)
		M_EXIT_ON_ERROR("Can't allocate memory");

	server_socket_fd = chat_client_connect(args->host, args->port);
	tinfo->socket_fd = server_socket_fd;

	// Send public key to server and receive server's public key
	chat_client_exchange_keys_and_nicknames(server_socket_fd);

	// 2 Threads: One for receiving data from server, one for sending data
	pthread_create(&threadID, NULL, chat_client_receive, tinfo);
	chat_client_read_and_send(server_socket_fd);

	pthread_exit(NULL);
}

/**
 * Connect to given host and port number
 *
 * @param host hostname of server
 * @param port port number
 * @return server socket fd
 */
int chat_client_connect(char *host, int port) {
	struct sockaddr_in sock;
	struct hostent *server;
	int server_socket_fd, ret;

	if ((server_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
		M_EXIT_ON_ERROR("Can't create socket");

	// Zero sock structure
	memset((char *) &sock, 0, sizeof(sock));

	// Get host by name
	if ((server = gethostbyname(host)) == NULL)
		M_EXIT_ON_ERROR("No such host");

	// Connect to server
	sock.sin_family = AF_INET;
	sock.sin_port   = ntohs(port);
	bcopy((char *)server->h_addr, (char *)&sock.sin_addr.s_addr, server->h_length);

	if ((ret = connect(server_socket_fd,
					  (struct sockaddr *) &sock, sizeof(sock))) < 0 )
		M_EXIT_ON_ERROR("Error connecting to server");

	M_PRINT_STATUS("Connected to server!\n");
	return server_socket_fd;
}

/**
 * Reads data from server
 * @param socket_fd servers socket
 * @param buf data buffer
 * @param buflen length of data buffer
 *
 */
int chat_client_read(int socket_fd, char buf[], int buflen) {
	int ret;

	if ((ret = read(socket_fd, buf, buflen)) < 0) {
		M_PRINT_ERROR("Error reading from socket");
		return -1;
	} else {
		return ret;
	}
}

/**
 * Sends data to server
 *
 * @param socket_fd servers socket
 * @param buf data buffer
 * @param buflen length of data buffer
 * @return -1 if error, 0 otherwise
 */
int chat_client_write(int socket_fd, char buf[], int buflen) {
	int ret;

	if ((ret = write(socket_fd, buf, buflen)) != buflen)
		return -1;
	else
		return 0;

}

/**
 * Reads from stdin and sends data to server
 *
 * @param server_socket_fd socket to server
 */
void chat_client_read_and_send(int server_socket_fd) {
	char buf[BUFSIZE];

	// Read input and send it to server
	while (1) {
		memset(buf, 0, BUFSIZE);

		if(!(mygetline(buf, BUFSIZE)))
			M_PRINT_ERROR("fgets error");

		// Encrypt line with servers public key
		int encryptedLen = encryptedSize(ss->rsa_pub_key, strlen(buf)+1);
		char *encryptedBuffer = malloc(encryptedLen);
		encrypt(ss->rsa_pub_key, buf, strlen(buf)+1, encryptedBuffer);

		// Send to server
		chat_client_write(server_socket_fd, encryptedBuffer,BUFSIZE);
	}
}

/**
 * Thread to receive from server
 */
void *chat_client_receive(void *arg) {
	struct thread_info *tinfo = (struct thread_info *) arg;
	int server_fd = tinfo->socket_fd;
	char buf[BUFSIZE];
	int buflen = 0;

	while (1) {
		memset(buf, 0, BUFSIZE);
		buflen = chat_client_read(server_fd, buf, BUFSIZE);

		// Check if server closed the connection
		if (buflen == 0) {
			M_PRINT_ERROR("Lost server connection");
			close(server_fd);
			exit(EXIT_FAILURE);
		} else {
			// Decrypt message
			int decryptedLen = decryptedSize(cs->rsa_priv_key, buflen);
			char *decryptedBuffer = malloc(decryptedLen);
			decrypt(cs->rsa_priv_key, buf, buflen, decryptedBuffer);

			printf("<%s> %s\n", ss->nickname, decryptedBuffer);
			free(decryptedBuffer);
		}
	}

	return NULL;
}

/**
 * Exchange public keys (between client and server)
 *
 * @param server_fd server's fd
 */
void chat_client_exchange_keys_and_nicknames(int server_fd) {
	char *hello_message_to_server;			/* consists of: <nickname>HELLO_MSG_DELIM<public key> */
	char *hello_message_from_server;
	char *own_public_key = key_key2str(cs->rsa_pub_key);

	// Allocate memory
	if((hello_message_to_server = malloc(BUFSIZE)) == NULL)
		M_PRINT_ERROR("Can't allocate memory");

	if((hello_message_from_server = malloc(BUFSIZE)) == NULL)
		M_PRINT_ERROR("Can't allocate memory");

	// Send hello message to server
	sprintf(hello_message_to_server, "%s%s%s", cs->nickname, HELLO_MSG_DELIM, own_public_key);
	if(chat_client_write(server_fd, hello_message_to_server, BUFSIZE))
		M_PRINT_ERROR("Error on sending hello message to server");

	// Get server's hello message
	if(chat_client_read(server_fd, hello_message_from_server, BUFSIZE) < 0) {
		M_PRINT_ERROR("Error receiving hello message from server");
	} else {
		char *saveptr = NULL;

		// Save nickname
		ss->nickname = strtok_r(hello_message_from_server, HELLO_MSG_DELIM, &saveptr);

		// Save public key
		ss->rsa_pub_key = key_str2key(strtok_r(NULL, HELLO_MSG_DELIM, &saveptr));
	}
}


text:
package org.springframework.boot.autoconfigure.jdbc;

import java.util.UUID;

import org.apache.commons.dbcp2.BasicDataSource;

/**
 * {@link BasicDataSource} used for testing.
 *
 * @author Phillip Webb
 * @author Kazuki Shimizu
 * @author Stephane Nicoll
 */
public class TestDataSource extends BasicDataSource {

	/**
	 * Create an in-memory database with the specified name.
	 * @param name the name of the database
	 */
	public TestDataSource(String name) {
		setDriverClassName("org.hsqldb.jdbcDriver");
		setUrl("jdbc:hsqldb:mem:" + name);
		setUsername("sa");
	}

	/**
	 * Create an in-memory database with a random name.
	 */
	public TestDataSource() {
		this(UUID.randomUUID().toString());
	}

}


text:
namespace http = process::http;

using process::DataDecoder;
using process::Future;
using process::Owned;
using process::ResponseDecoder;
using process::StreamingRequestDecoder;
using process::StreamingResponseDecoder;

using std::deque;
using std::string;

// TODO(anand): Parameterize the response decoder tests.

template <typename T>
class RequestDecoderTest : public ::testing::Test {};

typedef ::testing::Types<DataDecoder, StreamingRequestDecoder>
  RequestDecoderTypes;

// The request decoder tests are parameterized by the type of request decoder.
TYPED_TEST_CASE(RequestDecoderTest, RequestDecoderTypes);

TYPED_TEST(RequestDecoderTest, Request)
{
  TypeParam decoder;

  const string data =
    "GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress, gzip\r\n"
    "\r\n";

  deque<http::Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1u, requests.size());

  Owned<http::Request> request(requests[0]);
  EXPECT_EQ("GET", request->method);

  EXPECT_EQ("/path/file.json", request->url.path);
  EXPECT_SOME_EQ("fragment", request->url.fragment);
  EXPECT_EQ(2u, request->url.query.size());
  EXPECT_SOME_EQ("value1", request->url.query.get("key1"));
  EXPECT_SOME_EQ("value2", request->url.query.get("key2"));

  Future<string> body = [&request]() -> Future<string> {
    if (request->type == http::Request::BODY) {
      return request->body;
    }

    return request->reader->readAll();
  }();

  AWAIT_EXPECT_EQ(string(""), body);
  EXPECT_FALSE(request->keepAlive);

  EXPECT_EQ(3u, request->headers.size());
  EXPECT_SOME_EQ("localhost", request->headers.get("Host"));
  EXPECT_SOME_EQ("close", request->headers.get("Connection"));
  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
}

TYPED_TEST(RequestDecoderTest, HeaderContinuation)
{
  TypeParam decoder;

  const string data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress,"
    "                 gzip\r\n"
    "\r\n";

  deque<http::Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1u, requests.size());

  Owned<http::Request> request(requests[0]);
  EXPECT_SOME_EQ("compress,                 gzip",
                 request->headers.get("Accept-Encoding"));
}

TYPED_TEST(RequestDecoderTest, HeaderCaseInsensitive)
{
  TypeParam decoder;

  const string data =
    "GET /path/file.json HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "cOnnECtioN: close\r\n"
    "accept-ENCODING: compress, gzip\r\n"
    "\r\n";

  deque<http::Request*> requests = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1u, requests.size());

  Owned<http::Request> request(requests[0]);
  EXPECT_FALSE(request->keepAlive);

  EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
}

TYPED_TEST(RequestDecoderTest, InvalidQueryArgs)
{
  TypeParam decoder;

  const string data =
    "GET /path/file.json?%x=%y&key2=value2#fragment HTTP/1.1\r\n"
    "Host: localhost\r\n"
    "Connection: close\r\n"
    "Accept-Encoding: compress, gzip\r\n"
    "\r\n";

  deque<http::Request*> requests = decoder.decode(data.data(), data.length());
  EXPECT_TRUE(decoder.failed());
}

TEST(DecoderTest, Response)
{
  ResponseDecoder decoder;

  const string data =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 2\r\n"
    "\r\n"
    "hi";

  deque<http::Response*> responses = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1u, responses.size());

  Owned<http::Response> response(responses[0]);

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(http::Response::BODY, response->type);
  EXPECT_EQ("hi", response->body);

  EXPECT_EQ(3u, response->headers.size());
}

TEST(DecoderTest, ResponseWithUnspecifiedLength)
{
  ResponseDecoder decoder;

  const string data =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "\r\n"
    "hi";

  deque<http::Response*> responses = decoder.decode(data.data(), data.length());
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(0u, responses.size());

  responses = decoder.decode("", 0);
  ASSERT_FALSE(decoder.failed());
  ASSERT_EQ(1u, responses.size());

  Owned<http::Response> response(responses[0]);

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(http::Response::BODY, response->type);
  EXPECT_EQ("hi", response->body);

  EXPECT_EQ(2u, response->headers.size());
}

TEST(DecoderTest, StreamingResponse)
{
  StreamingResponseDecoder decoder;

  const string headers =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 2\r\n"
    "\r\n";

  const string body = "hi";

  deque<http::Response*> responses =
    decoder.decode(headers.data(), headers.length());

  EXPECT_FALSE(decoder.failed());
  EXPECT_TRUE(decoder.writingBody());
  ASSERT_EQ(1u, responses.size());

  Owned<http::Response> response(responses[0]);

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(3u, response->headers.size());

  ASSERT_EQ(http::Response::PIPE, response->type);
  ASSERT_SOME(response->reader);

  http::Pipe::Reader reader = response->reader.get();
  Future<string> read = reader.read();
  EXPECT_TRUE(read.isPending());

  decoder.decode(body.data(), body.length());
  EXPECT_FALSE(decoder.failed());
  EXPECT_FALSE(decoder.writingBody());

  // Feeding EOF to the decoder should be ok.
  decoder.decode("", 0);
  EXPECT_FALSE(decoder.failed());
  EXPECT_FALSE(decoder.writingBody());

  EXPECT_TRUE(read.isReady());
  EXPECT_EQ("hi", read.get());

  // Response should be complete.
  read = reader.read();
  EXPECT_TRUE(read.isReady());
  EXPECT_EQ("", read.get());
}

TEST(DecoderTest, StreamingResponseFailure)
{
  StreamingResponseDecoder decoder;

  const string headers =
    "HTTP/1.1 200 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 2\r\n"
    "\r\n";

  // The body is shorter than the content length!
  const string body = "1";

  deque<http::Response*> responses =
    decoder.decode(headers.data(), headers.length());

  EXPECT_FALSE(decoder.failed());
  EXPECT_TRUE(decoder.writingBody());

  ASSERT_EQ(1u, responses.size());
  Owned<http::Response> response(responses[0]);

  EXPECT_EQ("200 OK", response->status);
  EXPECT_EQ(3u, response->headers.size());

  ASSERT_EQ(http::Response::PIPE, response->type);
  ASSERT_SOME(response->reader);

  http::Pipe::Reader reader = response->reader.get();
  Future<string> read = reader.read();
  EXPECT_TRUE(read.isPending());

  decoder.decode(body.data(), body.length());
  EXPECT_FALSE(decoder.failed());
  EXPECT_TRUE(decoder.writingBody());

  EXPECT_TRUE(read.isReady());
  EXPECT_EQ("1", read.get());

  // Body is not yet complete.
  read = reader.read();
  EXPECT_TRUE(read.isPending());

  // Feeding EOF to the decoder should trigger a failure!
  decoder.decode("", 0);
  EXPECT_TRUE(decoder.failed());
  EXPECT_FALSE(decoder.writingBody());

  EXPECT_TRUE(read.isFailed());
  EXPECT_EQ("failed to decode body", read.failure());
}

TEST(DecoderTest, StreamingResponseInvalidHeader)
{
  StreamingResponseDecoder decoder;

  const string headers =
    "HTTP/1.1 999 OK\r\n"
    "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
    "Content-Type: text/plain\r\n"
    "\r\n";

  deque<http::Response*> responses =
    decoder.decode(headers.data(), headers.length());

  EXPECT_TRUE(decoder.failed());
}


text:
var books = Alloy.Collections.book = Alloy.createCollection("book");
books.reset([
	{title:'Moby Dick',author:'Herman Melville'},
	{title:'The Count of Monte Cristo',author:'Alexandre Dumas'},
]);


text:
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);


text:
using UnityEngine;
using System.Collections;

public class DeactivateLever : MonoBehaviour
{

    public GameObject leverObj;
    Lever objLeverCom;

    Lever thisLeverCom;

    // Use this for initialization
    void Start()
    {
        objLeverCom = leverObj.GetComponent<Lever>();
        thisLeverCom = GetComponent<Lever>();

    }

    // Update is called once per frame
    void Update()
    {

        if (thisLeverCom.activated)
        {
            objLeverCom.activated = !objLeverCom.activated;
        }

    }
}


text:
package com.android.hotspot2.utils;

import android.util.Base64;
import android.util.Log;

import com.android.hotspot2.osu.OSUManager;

import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class HTTPResponse implements HTTPMessage {
    private final int mStatusCode;
    private final Map<String, String> mHeaders = new LinkedHashMap<>();
    private final ByteBuffer mBody;

    private static final String csIndicator = "charset=";

    public HTTPResponse(InputStream in) throws IOException {
        int expected = Integer.MAX_VALUE;
        int offset = 0;
        int body = -1;
        byte[] input = new byte[RX_BUFFER];

        int statusCode = -1;
        int bodyPattern = 0;

        while (offset < expected) {
            int amount = in.read(input, offset, input.length - offset);
            Log.d(OSUManager.TAG, String.format("Reading into %d from %d, amount %d -> %d",
                    input.length, offset, input.length - offset, amount));
            if (amount < 0) {
                throw new EOFException();
            }
            //Log.d("ZXZ", "HTTP response: '"
            // + new String(input, 0, offset + amount, StandardCharsets.ISO_8859_1));

            if (body < 0) {
                for (int n = offset; n < offset + amount; n++) {
                    bodyPattern = (bodyPattern << 8) | (input[n] & 0xff);
                    if (bodyPattern == 0x0d0a0d0a) {
                        body = n + 1;
                        statusCode = parseHeader(input, body, mHeaders);
                        expected = calculateLength(body, mHeaders);
                        if (expected > input.length) {
                            input = Arrays.copyOf(input, expected);
                        }
                        break;
                    }
                }
            }
            offset += amount;
            if (offset < expected && offset == input.length) {
                input = Arrays.copyOf(input, input.length * 2);
            }
        }
        mStatusCode = statusCode;
        mBody = ByteBuffer.wrap(input, body, expected - body);
    }

    private static int parseHeader(byte[] input, int body, Map<String, String> headers)
            throws IOException {
        String headerText = new String(input, 0, body - BODY_SEPARATOR_LENGTH,
                StandardCharsets.ISO_8859_1);
        //System.out.println("Received header: " + headerText);
        Iterator<String> headerLines = Arrays.asList(headerText.split(CRLF)).iterator();
        if (!headerLines.hasNext()) {
            throw new IOException("Bad HTTP Request");
        }

        int statusCode;
        String line0 = headerLines.next();
        String[] status = line0.split(" ");
        if (status.length != 3 || !"HTTP/1.1".equals(status[0])) {
            throw new IOException("Bad HTTP Result: " + line0);
        }
        try {
            statusCode = Integer.parseInt(status[1].trim());
        } catch (NumberFormatException nfe) {
            throw new IOException("Bad HTTP header line: '" + line0 + "'");
        }

        while (headerLines.hasNext()) {
            String line = headerLines.next();
            int keyEnd = line.indexOf(':');
            if (keyEnd < 0) {
                throw new IOException("Bad header line: '" + line + "'");
            }
            String key = line.substring(0, keyEnd).trim();
            String value = line.substring(keyEnd + 1).trim();
            headers.put(key, value);
        }
        return statusCode;
    }

    private static int calculateLength(int body, Map<String, String> headers) throws IOException {
        String contentLength = headers.get(LengthHeader);
        if (contentLength == null) {
            throw new IOException("No " + LengthHeader);
        }
        try {
            return body + Integer.parseInt(contentLength);
        } catch (NumberFormatException nfe) {
            throw new IOException("Bad " + LengthHeader + ": " + contentLength);
        }
    }

    public int getStatusCode() {
        return mStatusCode;
    }

    @Override
    public Map<String, String> getHeaders() {
        return Collections.unmodifiableMap(mHeaders);
    }

    public String getHeader(String key) {
        return mHeaders.get(key);
    }

    @Override
    public InputStream getPayloadStream() {
        return new ByteArrayInputStream(mBody.array(), mBody.position(),
                mBody.limit() - mBody.position());
    }

    @Override
    public ByteBuffer getPayload() {
        return mBody.duplicate();
    }

    @Override
    public ByteBuffer getBinaryPayload() {
        byte[] data = new byte[mBody.remaining()];
        mBody.duplicate().get(data);
        byte[] binary = Base64.decode(data, Base64.DEFAULT);
        return ByteBuffer.wrap(binary);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Status: ").append(mStatusCode).append(CRLF);
        for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
            sb.append(entry.getKey()).append(": ").append(entry.getValue()).append(CRLF);
        }
        sb.append(CRLF);
        Charset charset;
        try {
            charset = Charset.forName(getCharset());
        } catch (IllegalArgumentException iae) {
            charset = StandardCharsets.ISO_8859_1;
        }
        sb.append(new String(mBody.array(), mBody.position(),
                mBody.limit() - mBody.position(), charset));
        return sb.toString();
    }

    public String getCharset() {
        String contentType = mHeaders.get(ContentTypeHeader);
        if (contentType == null) {
            return null;
        }
        int csPos = contentType.indexOf(csIndicator);
        return csPos < 0 ? null : contentType.substring(csPos + csIndicator.length()).trim();
    }

    private static boolean equals(byte[] b1, int offset, byte[] pattern) {
        for (int n = 0; n < pattern.length; n++) {
            if (b1[n + offset] != pattern[n]) {
                return false;
            }
        }
        return true;
    }
}


text:
package jsettlers.ai.highlevel.pioneers.target;

import jsettlers.ai.highlevel.AiPositions;
import jsettlers.ai.highlevel.AiStatistics;
import jsettlers.common.position.ShortPoint2D;

/**
 * @author codingberlin
 */
public class ConnectPartitionsTargetFinder extends AbstractPioneerTargetFinder {

	public ConnectPartitionsTargetFinder(AiStatistics aiStatistics, byte playerId, int searchDistance) {
		super(aiStatistics, playerId, searchDistance);
	}

	@Override
	public ShortPoint2D findTarget(AiPositions playerBorder, ShortPoint2D center) {
		AiPositions otherPartitionBorder = aiStatistics.getOtherPartitionBorderOf(playerId);
		if (otherPartitionBorder.isEmpty()) {
			return null;
		}

		ShortPoint2D nearestOtherPartitionBorderPoint = otherPartitionBorder.getNearestPoint(
				center, aiStatistics.getMainGrid().getWidth(), new SameBlockedPartitionLikePlayerFilter(aiStatistics, playerId));
		if (nearestOtherPartitionBorderPoint == null) {
			return null;
		}

		int searchDistance = nearestOtherPartitionBorderPoint.getOnGridDistTo(center) + 10;
		return playerBorder.getNearestPoint(nearestOtherPartitionBorderPoint, searchDistance);
	}
}


text:
package java.security;

/**
 * Legacy security code; do not use.
 */

public abstract class BasicPermission extends Permission
implements java.io.Serializable
{

    public BasicPermission(String name) { super(""); }

    public BasicPermission(String name, String actions) { super(""); }

    public boolean implies(Permission p) { return true; }

    public String getActions()
    {
        return "";
    }
}


text:
#ifndef CODE_NASHOLD_H
#define CODE_NASHOLD_H

#include <Code.h>
#include "LayerState_NAS.h"

/* Code_NASHold is similar to Code_LayerHold
*/
class Code_NASHold : public Code
{
    private:
        LayerState_NAS& refLayerState_NAS;
    public:
        Code_NASHold(LayerState_NAS& refLayerState_NAS)
            : refLayerState_NAS(refLayerState_NAS) {}
        virtual void press();
        virtual void release();
};
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<QBXML>
  <QBXMLMsgsRs>
    <VendorQueryRs statusCode="0" statusSeverity="Info" statusMessage="Status OK">
      <VendorRet>
        <ListID>80000001-1403289728</ListID>
        <TimeCreated>2014-06-20T11:42:08-08:00</TimeCreated>
        <TimeModified>2014-06-20T11:42:08-08:00</TimeModified>
        <EditSequence>1403289728</EditSequence>
        <Name>Valente Construction</Name>
        <IsActive>true</IsActive>
        <CompanyName>Valente Construction</CompanyName>
        <FirstName>Joe</FirstName>
        <LastName>Valente</LastName>
        <VendorAddress>
          <Addr1>Valente Construction</Addr1>
          <Addr2>1111 Carpinteria Ave.</Addr2>
          <Addr3>2222 Carpinteria Ave.</Addr3>
          <Addr4>3333 Carpinteria Ave.</Addr4>
          <City>Santa Barbara</City>
          <State>CA</State>
          <PostalCode>93108</PostalCode>
        </VendorAddress>
        <VendorAddressBlock>
          <Addr1>Valente Construction</Addr1>
          <Addr2>1111 Carpinteria Ave.</Addr2>
          <Addr3>Santa Barbara, CA, 93108</Addr3>
        </VendorAddressBlock>
        <Phone>8055665777</Phone>
        <AltPhone>8055665666</AltPhone>
        <Fax>8055655555</Fax>
        <Email>joe@foo.com</Email>
        <Contact>Missy Valero</Contact>
        <IsVendorEligibleFor1099>false</IsVendorEligibleFor1099>
        <Balance>0.00</Balance>
      </VendorRet>
    </VendorQueryRs>
  </QBXMLMsgsRs>
</QBXML>


text:
module GeoConcerns
  module Discovery
    class DocumentBuilder
      class DocumentHelper
        include Rails.application.routes.url_helpers
        include ActionDispatch::Routing::PolymorphicRoutes
      end
    end
  end
end


text:
from __future__ import absolute_import
import click

from collections import namedtuple
from botocore.exceptions import ClientError

from .aws import get_client

ApplicationVersion = namedtuple('ApplicationVersion', ['label', 'date_created'])

@click.command()
@click.argument('app_name')
@click.option('--keep', default=20)
@click.option('--dry-run', default=False, is_flag=True)
def app_versions(app_name, keep, dry_run):
    beanstalk = get_client('elasticbeanstalk')

    response = beanstalk.describe_application_versions(
        ApplicationName=app_name)

    versions = response.get('ApplicationVersions', [])
    if not versions:
        click.secho('No versions found for Beanstalk '
                    'App: {}'.format(app_name),
                    fg='red')
        return

    app_versions = []
    for version_dict in versions:
        version = ApplicationVersion(version_dict.get('VersionLabel'),
                                     version_dict.get('DateCreated'))
        app_versions.append(version)

    app_versions = sorted(app_versions,
                          key=lambda n: n.date_created,
                          reverse=True)

    delete_versions = app_versions[keep:]

    if dry_run:
        click.secho('Dry Run: no changes will be made', fg='yellow')

    for version in delete_versions:
        click.echo('Delete {} created: {}'.format(version.label,
                                                  version.date_created))

        if not dry_run:
            try:
                response = beanstalk.delete_application_version(
                    ApplicationName=app_name,
                    VersionLabel=version.label,
                    DeleteSourceBundle=True)
            except ClientError as exc:
                msg = unicode(exc)
                if 'source bundle: Not Found' in msg:
                    pass
                else:
                    click.ClickException(
                        'Could not delete version {}: {}'.format(version.label,
                                                                 msg))

            status_code = response.get('ResponseMetadata', {}).get('HTTPStatusCode', 500)  # noqa

            if status_code != 200:
                click.secho('Deleting version {} failed.'.format(version.label),
                            fg='red')
            else:
                click.secho('Deleted version {}.'.format(version.label), fg='green')


text:
goog.module('test_files.import_equals.exporter');

exports.Exported = class {};
exports.Exported.Nested = class {};
/** @enum {number} */
exports.Exported.Nested.Thing = {
  ITEM: 1
};