text:
.. _ref_eql_statements_insert:

Insert
======

:eql-statement:
:eql-haswith:

``insert`` -- create a new object in a database

.. eql:synopsis::

    [ with <with-spec> [ ,  ... ] ]
    insert <expression> [ <insert-shape> ]
    [ unless conflict
        [ on <property-expr> [ else <alternative> ] ]
    ] ;

Description
-----------

``insert`` inserts a new object into a database.

When evaluating an ``insert`` statement, *expression* is used solely to
determine the *type* of the inserted object and is not evaluated in any
other way.

If a value for a *required* link is evaluated to an empty set, an error is
raised.

It is possible to insert multiple objects by putting the ``insert``
into a :eql:stmt:`for` statement.

See :ref:`ref_eql_forstatement` for more details.

:eql:synopsis:`with`
    Alias declarations.

    The ``with`` clause allows specifying module aliases as well
    as expression aliases that can be referenced by the :eql:stmt:`update`
    statement.  See :ref:`ref_eql_statements_with` for more information.

:eql:synopsis:`<expression>`
    An arbitrary expression returning a set of objects to be updated.

    .. eql:synopsis::

        insert <expression>
        [ "{" <link> := <insert-value-expr> [, ...]  "}" ]

.. _ref_eql_statements_conflict:

:eql:synopsis:`unless conflict [ on <property-expr> ]`
    :index: unless conflict

    Handler of conflicts.

    This clause allows to handle specific conflicts arising during
    execution of ``insert`` without producing an error.  If the
    conflict arises due to exclusive constraints on the properties
    specified by *property-expr*, then instead of failing with an
    error the ``insert`` statement produces an empty set (or an
    alternative result).

    The exclusive constraint on ``<property-expr>`` cannot be defined on a
    parent type.

    The specified *property-expr* may be either a reference to a
    property (or link) or a tuple of references to properties (or
    links).

    A caveat, however, is that ``unless conflict`` will not prevent
    conflicts caused between multiple DML operations in the same
    query; inserting two conflicting objects (through use of ``for``
    or simply with two ``insert`` statements) will cause a constraint
    error.

    Example:

    .. code-block:: edgeql

        insert User { email := 'user@example.org' }
        unless conflict on .email

    .. code-block:: edgeql

        insert User { first := 'Jason', last := 'Momoa' }
        unless conflict on (.first, .last)

:eql:synopsis:`else <alternative>`
    Alternative result in case of conflict.

    This clause can only appear after ``unless conflict`` clause. Any
    valid expression can be specified as the *alternative*. When a
    conflict arises, the result of the ``insert`` becomes the
    *alternative* expression (instead of the default ``{}``).

    In order to refer to the conflicting object in the *alternative*
    expression, the name used in the ``insert`` must be used (see
    :ref:`example below <ref_eql_statements_insert_unless>`).

Outputs
-------

The result of an ``insert`` statement used as an *expression* is a
singleton set containing the inserted object.

Examples
--------

Here's a simple example of an ``insert`` statement creating a new user:

.. code-block:: edgeql

    with module example
    insert User {
        name := 'Bob Johnson'
    };

``insert`` is not only a statement, but also an expression and as such
is has a value of the set of objects that has been created.

.. code-block:: edgeql

    with module example
    insert Issue {
        number := '100',
        body := 'Fix errors in insert',
        owner := (
            select User filter User.name = 'Bob Johnson'
        )
    };

It is possible to create nested objects in a single ``insert``
statement as an atomic operation.

.. code-block:: edgeql

    with module example
    insert Issue {
        number := '101',
        body := 'Nested insert',
        owner := (
            insert User {
                name := 'Nested User'
            }
        )
    };

The above statement will create a new ``Issue`` as well as a new
``User`` as the owner of the ``Issue``. It will also return the new
``Issue`` linked to the new ``User`` if the statement is used as an
expression.

It is also possible to create new objects based on some existing data
either provided as an explicit list (possibly automatically generated
by some tool) or a query. A ``for`` statement is the basis for this
use-case and ``insert`` is simply the expression in the ``union``
clause.

.. code-block:: edgeql

    # example of a bulk insert of users based on explicitly provided
    # data
    with module example
    for x in {'Alice', 'Bob', 'Carol', 'Dave'}
    union (insert User {
        name := x
    });

    # example of a bulk insert of issues based on a query
    with
        module example,
        Elvis := (select User filter .name = 'Elvis'),
        Open := (select Status filter .name = 'Open')

    for Q in (select User filter .name ilike 'A%')

    union (insert Issue {
        name := Q.name + ' access problem',
        body := 'This user was affected by recent system glitch',
        owner := Elvis,
        status := Open
    });

.. _ref_eql_statements_insert_unless:

There's an important use-case where it is necessary to either insert a
new object or update an existing one identified with some key. This is
what the ``unless conflict`` clause allows:

.. code-block:: edgeql

    with module people
    select (
        insert Person {
            name := "Łukasz Langa", is_admin := true
        }
        unless conflict on .name
        else (
            update Person
            set { is_admin := true }
        )
    ) {
        name,
        is_admin
    };

.. note::

    Statements in EdgeQL represent an atomic interaction with the
    database. From the point of view of a statement all side-effects
    (such as database updates) happen after the statement is executed.
    So as far as each statement is concerned, it is some purely
    functional expression evaluated on some specific input (database
    state).

.. list-table::
  :class: seealso

  * - **See also**
  * - :ref:`EdgeQL > Insert <ref_eql_insert>`
  * - :ref:`Cheatsheets > Inserting data <ref_cheatsheet_insert>`


text:
package com.alibaba.dubbo.common.serialize.support.proto;

import java.io.IOException;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;

/**
 *
 * @author surlymo
 *
 */
public class ProtostuffUtils {

    public static <T> byte[] toByteArray(T message, Schema<T> schema, LinkedBuffer buffer) {
        return ProtobufIOUtil.toByteArray(message, schema, buffer);
    }

    public static <T> void mergeFrom(byte[] in, T message, Schema<T> schema) throws IOException {
        ProtobufIOUtil.mergeFrom(in, message, schema);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ru.tsibrovskii.examples;

import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Тестовый класс.
 */
public class HelloWorldTest {

    /**
     * Тестовый метод.
     */
    @Test
    public void whenRunShouldPrintHelloWorld() {
        // Система использует собственный поток.
        // класс HelloWorld печатает в объект out.
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        HelloWorld.main(null);
        assertThat(out.toString(), is("Hello, World!!!!!"));
    }
}


text:
package tikv

import (
	"github.com/insionng/yougam/libraries/golang/protobuf/proto"
	"github.com/insionng/yougam/libraries/juju/errors"
	"github.com/insionng/yougam/libraries/ngaut/log"
	pb "github.com/insionng/yougam/libraries/pingcap/kvproto/pkg/kvrpcpb"
	"github.com/insionng/yougam/libraries/pingcap/tidb/kv"
	"github.com/insionng/yougam/libraries/pingcap/tidb/terror"
)

var (
	_ kv.Snapshot = (*tikvSnapshot)(nil)
)

const (
	scanBatchSize = 100
	maxGetCount   = 3
	batchGetSize  = 100
)

// tikvSnapshot implements MvccSnapshot interface.
type tikvSnapshot struct {
	store   *tikvStore
	version kv.Version
}

// newTiKVSnapshot creates a snapshot of an TiKV store.
func newTiKVSnapshot(store *tikvStore, ver kv.Version) *tikvSnapshot {
	return &tikvSnapshot{
		store:   store,
		version: ver,
	}
}

// makeBatchGetReqs splits each key into corresponding region.
func (s *tikvSnapshot) makeBatchGetReqs(keys []kv.Key) (map[RegionVerID]*batchGetRegion, error) {
	startTS := s.version.Ver
	multiBatchGet := map[RegionVerID]*batchGetRegion{}
	for _, k := range keys {
		region, err := s.store.regionCache.GetRegion(k)
		if err != nil {
			return nil, errors.Trace(err)
		}
		regionID := region.VerID()
		singleBatchGet, ok := multiBatchGet[regionID]
		if !ok {
			singleBatchGet = &batchGetRegion{
				CmdBatchGetRequest: &pb.CmdBatchGetRequest{
					Version: proto.Uint64(startTS),
				},
				region: regionID,
			}
			multiBatchGet[regionID] = singleBatchGet
		}
		cmdBatchGetReq := singleBatchGet.CmdBatchGetRequest
		cmdBatchGetReq.Keys = append(cmdBatchGetReq.Keys, k)
	}
	return multiBatchGet, nil
}

// doBatchGet sends BatchGet RPC request. If any key is locked, use tikvSnapshot.Get() to retry.
func (s *tikvSnapshot) doBatchGet(singleBatchGet *batchGetRegion) (map[string][]byte, error) {
	cmdBatchGetReq := singleBatchGet.CmdBatchGetRequest
	keys := cmdBatchGetReq.GetKeys()
	if len(keys) == 0 {
		return nil, nil
	}
	req := &pb.Request{
		Type:           pb.MessageType_CmdBatchGet.Enum(),
		CmdBatchGetReq: cmdBatchGetReq,
	}
	resp, err := s.store.SendKVReq(req, singleBatchGet.region)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if regionErr := resp.GetRegionError(); regionErr != nil {
		//TODO: retry internally
		return nil, errors.Annotate(errors.New(regionErr.String()), txnRetryableMark)
	}
	cmdBatchGetResp := resp.GetCmdBatchGetResp()
	if cmdBatchGetResp == nil {
		return nil, errors.Trace(errBodyMissing)
	}
	pairs := cmdBatchGetResp.GetPairs()
	m := make(map[string][]byte, len(pairs))
	for _, pair := range pairs {
		keyErr := pair.GetError()
		if keyErr == nil {
			if val := pair.GetValue(); len(val) > 0 {
				m[string(pair.GetKey())] = val
			}
			continue
		}
		lockInfo, err := extractLockInfoFromKeyErr(keyErr)
		if err != nil {
			return nil, errors.Trace(err)
		}
		val, err := s.Get(lockInfo.GetKey())
		if err != nil {
			if terror.ErrorEqual(err, kv.ErrNotExist) {
				continue
			}
			return nil, errors.Trace(err)
		}
		m[string(lockInfo.GetKey())] = val
	}
	return m, nil
}

// BatchGet gets all the keys' value from kv-server and returns a map contains key/value pairs.
// The map will not contain nonexistent keys.
func (s *tikvSnapshot) BatchGet(keys []kv.Key) (map[string][]byte, error) {
	m := make(map[string][]byte, len(keys))

	multiBatchGet, err := s.makeBatchGetReqs(keys)
	if err != nil {
		return nil, errors.Trace(err)
	}
	for _, singleBatchGet := range multiBatchGet {
		keys := singleBatchGet.GetKeys()
		for startIdx := 0; startIdx < len(keys); startIdx += batchGetSize {
			endIdx := startIdx + batchGetSize
			if endIdx > len(keys) {
				endIdx = len(keys)
			}
			newSingleBatchGet := &batchGetRegion{
				CmdBatchGetRequest: &pb.CmdBatchGetRequest{
					Keys:    keys[startIdx:endIdx],
					Version: proto.Uint64(singleBatchGet.GetVersion()),
				},
				region: singleBatchGet.region,
			}
			res, err := s.doBatchGet(newSingleBatchGet)
			if err != nil {
				return nil, errors.Trace(err)
			}
			m, err = mergeResult(m, res)
			if err != nil {
				return nil, errors.Trace(err)
			}
		}
	}

	return m, nil
}

// Get gets the value for key k from snapshot.
func (s *tikvSnapshot) Get(k kv.Key) ([]byte, error) {
	req := &pb.Request{
		Type: pb.MessageType_CmdGet.Enum(),
		CmdGetReq: &pb.CmdGetRequest{
			Key:     k,
			Version: proto.Uint64(s.version.Ver),
		},
	}

	var (
		backoffErr    error
		regionBackoff = regionMissBackoff()
		txnBackoff    = txnLockBackoff()
	)
	for backoffErr == nil {
		region, err := s.store.regionCache.GetRegion(k)
		if err != nil {
			return nil, errors.Trace(err)
		}
		resp, err := s.store.SendKVReq(req, region.VerID())
		if err != nil {
			return nil, errors.Trace(err)
		}
		if regionErr := resp.GetRegionError(); regionErr != nil {
			backoffErr = regionBackoff()
			continue
		}
		cmdGetResp := resp.GetCmdGetResp()
		if cmdGetResp == nil {
			return nil, errors.Trace(errBodyMissing)
		}
		val := cmdGetResp.GetValue()
		if keyErr := cmdGetResp.GetError(); keyErr != nil {
			val, err = s.handleKeyError(keyErr)
			if err != nil {
				if terror.ErrorEqual(err, errInnerRetryable) {
					backoffErr = txnBackoff()
					continue
				}
				return nil, errors.Trace(err)
			}
		}
		if len(val) == 0 {
			return nil, kv.ErrNotExist
		}
		return val, nil
	}
	return nil, errors.Annotate(backoffErr, txnRetryableMark)
}

// Seek return a list of key-value pair after `k`.
func (s *tikvSnapshot) Seek(k kv.Key) (kv.Iterator, error) {
	scanner, err := newScanner(s, k, scanBatchSize)
	return scanner, errors.Trace(err)
}

// SeekReverse creates a reversed Iterator positioned on the first entry which key is less than k.
func (s *tikvSnapshot) SeekReverse(k kv.Key) (kv.Iterator, error) {
	return nil, kv.ErrNotImplemented
}

// Release unimplement.
func (s *tikvSnapshot) Release() {
}

func extractLockInfoFromKeyErr(keyErr *pb.KeyError) (*pb.LockInfo, error) {
	if locked := keyErr.GetLocked(); locked != nil {
		return locked, nil
	}
	if keyErr.Retryable != nil {
		err := errors.Errorf("tikv restarts txn: %s", keyErr.GetRetryable())
		log.Warn(err)
		return nil, errors.Annotate(err, txnRetryableMark)
	}
	if keyErr.Abort != nil {
		err := errors.Errorf("tikv aborts txn: %s", keyErr.GetAbort())
		log.Warn(err)
		return nil, errors.Trace(err)
	}
	return nil, errors.Errorf("unexpected KeyError: %s", keyErr.String())
}

// handleKeyError tries to resolve locks then retry to get value.
func (s *tikvSnapshot) handleKeyError(keyErr *pb.KeyError) ([]byte, error) {
	lockInfo, err := extractLockInfoFromKeyErr(keyErr)
	if err != nil {
		return nil, errors.Trace(err)
	}
	lock := newLock(s.store, lockInfo.GetPrimaryLock(), lockInfo.GetLockVersion(), lockInfo.GetKey(), s.version.Ver)
	val, err := lock.cleanup()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return val, nil
}

// mergeResult Merge d2 into d1. If d1 and d2 are overlap, it returns error.
func mergeResult(d1, d2 map[string][]byte) (map[string][]byte, error) {
	if d1 == nil {
		d1 = make(map[string][]byte)
	}
	for k2, v2 := range d2 {
		if v1, ok := d1[k2]; ok {
			// Because compare []byte takes too much time,
			// if conflict return error directly even their values are same.
			return nil, errors.Errorf("add dict conflict key[%s] v1[%q] v2[%q]",
				k2, v1, v2)
		}
		d1[k2] = v2
	}
	return d1, nil
}

type batchGetRegion struct {
	*pb.CmdBatchGetRequest
	region RegionVerID
}


text:
require 'spec_helper'
require 'aruba/platform'

RSpec.describe '.simple_table' do
  context 'when valid hash' do
    let(:hash) do
      {
        key1: 'value',
        key2: 'value'
      }
    end
    let(:rows) { ['# key1 => value', '# key2 => value'] }

    it { expect(Aruba.platform.simple_table(hash).to_s).to eq rows.join("\n") }
  end

  context 'when empty hash' do
    let(:hash) { {} }
    let(:rows) { [] }

    it { expect(Aruba.platform.simple_table(hash).to_s).to eq rows.join("\n") }
  end
end


text:
import { Operation } from "express-openapi";
import * as api from "../api";
import { Status } from "../../../api";
import status from "../status";
import _ from "../_";

const pkg = require("../../../package.json");

export const get: Operation = (req, res) => {

    res.setHeader("Content-Type", "application/json; charset=utf-8");
    res.status(200);

    res.end(JSON.stringify(getStatus(), null, 2));
};

get.apiDoc = {
    tags: ["status"],
    summary: "Get Status",
    operationId: "getStatus",
    responses: {
        200: {
            description: "OK",
            schema: {
                $ref: "#/definitions/Status"
            }
        },
        default: {
            description: "Unexpected Error",
            schema: {
                $ref: "#/definitions/Error"
            }
        }
    }
};

export function getStatus(): Status {

    const ret: Status = {
        time: Date.now(),
        version: pkg.version,
        process: {
            arch: process.arch,
            platform: process.platform,
            versions: process.versions,
            env: {
                PATH: process.env.PATH,
                DOCKER: process.env.DOCKER,
                DOCKER_NETWORK: process.env.DOCKER_NETWORK,
                pm_uptime: process.env.pm_uptime,
                USING_WINSER: process.env.USING_WINSER,
                NODE_ENV: process.env.NODE_ENV,
                SERVER_CONFIG_PATH: process.env.SERVER_CONFIG_PATH,
                TUNERS_CONFIG_PATH: process.env.TUNERS_CONFIG_PATH,
                CHANNELS_CONFIG_PATH: process.env.CHANNELS_CONFIG_PATH,
                SERVICES_DB_PATH: process.env.SERVICES_DB_PATH,
                PROGRAMS_DB_PATH: process.env.PROGRAMS_DB_PATH,
                LOGO_DATA_DIR_PATH: process.env.LOGO_DATA_DIR_PATH
            },
            pid: process.pid,
            memoryUsage: process.memoryUsage()
        },
        epg: {
            gatheringNetworks: [],
            storedEvents: _.program.itemMap.size
        },
        rpcCount: status.rpcCount,
        streamCount: {
            tunerDevice: _.tuner.devices.filter(td => td.isUsing === true).length,
            tsFilter: status.streamCount.tsFilter,
            decoder: status.streamCount.decoder
        },
        errorCount: status.errorCount,
        timerAccuracy: {
            // ns → μs
            last: status.timerAccuracy.last / 1000,
            m1: {
                avg: (status.timerAccuracy.m1.reduce((a, b) => a + b) / status.timerAccuracy.m1.length) / 1000,
                min: Math.min.apply(null, status.timerAccuracy.m1) / 1000,
                max: Math.max.apply(null, status.timerAccuracy.m1) / 1000
            },
            m5: {
                avg: (status.timerAccuracy.m5.reduce((a, b) => a + b) / status.timerAccuracy.m5.length) / 1000,
                min: Math.min.apply(null, status.timerAccuracy.m5) / 1000,
                max: Math.max.apply(null, status.timerAccuracy.m5) / 1000
            },
            m15: {
                avg: (status.timerAccuracy.m15.reduce((a, b) => a + b) / status.timerAccuracy.m15.length) / 1000,
                min: Math.min.apply(null, status.timerAccuracy.m15) / 1000,
                max: Math.max.apply(null, status.timerAccuracy.m15) / 1000
            }
        }
    };

    for (const nid in status.epg) {
        if (status.epg[nid] === true) {
            ret.epg.gatheringNetworks.push(parseInt(nid, 10));
        }
    }

    return ret;
}


text:
from polaris.mysql8 import mysqlBase
from dev_global.env import VIEWER_HEADER

class data_view_base(object):
    def __init__(self):
        self.mysql = mysqlBase(VIEWER_HEADER)

    def get_data(self):
        raise Exception

    def visualize(self):
        raise Exception

class profit_growth_rate(data_view_base):
    def get_data(self, stock_code):
        from datetime import date
        import pandas
        import copy
        result = self.mysql.condition_select(
            'income_statement','report_date,float_c40',f"char_stock_code='{stock_code}'")
        if not result.empty:
            result.columns = ['report_date', 'net_profit']
            result.set_index('report_date', inplace=True)
            #print(result)
            result2 = copy.deepcopy(result)
            for index, row in result2.iterrows():
                if index.month == 6:
                    index_key = date(index.year, 3, 31)
                    for col in result.columns:
                        try:
                            row[col] = row[col] - result.loc[index_key, col]
                        except Exception as e:
                            pass
                elif index.month == 9:
                    index_key = date(index.year, 6, 30)
                    for col in result.columns:
                        try:
                            row[col] = row[col] - result.loc[index_key, col]
                        except Exception as e:
                            pass
                elif index.month == 12:
                    index_key = date(index.year, 9, 30)
                    for col in result.columns:
                        try:
                            row[col] = row[col] - result.loc[index_key, col]
                        except Exception as e:
                            pass
            #x = pandas.concat([result,result2], axis=1 )
            #print(x)
            result2['last_period'] = result2['net_profit'].shift(4)
            result2['growth_rate'] = result2['net_profit']/result2['last_period'] - 1
            result2.dropna(axis=0, how='any', inplace=True)

            result2.drop(['net_profit','last_period'], axis=1, inplace=True)
            result2.columns = [f"{stock_code}"]
            return result2
        else:
            return pandas.DataFrame()

    def get_stock_list(self):
        result = self.mysql.condition_select('stock_manager', 'stock_code', "flag='t'")
        return list(result[0])

def profit_growth_analysis():
    import pandas
    # import xlwt
    from datetime import date
    from jupiter import calendar
    event = profit_growth_rate()
    stock_list = event.get_stock_list()
    profit_data = pandas.DataFrame()
    for stock in stock_list:
        df = event.get_data(stock)
        if not df.empty:
            profit_data = pandas.concat([profit_data, df], axis=1)
    result = profit_data.T
    trade_period = calendar.TradeDay(2020)
    result = result.loc[:,[trade_period.period(trade_period.today, 3-i) for i in range(3)]]
    result.dropna(axis=0, inplace=True)
    temp = result[[trade_period.period(trade_period.today, 3-i) for i in range(3)]]
    result['mean'] = temp.mean(axis=1)
    result = result.sort_values(by='mean',ascending=False)
    result = result.applymap(lambda x: format(x, '.2%'))

    result.insert(0, 'stock_name', result.index)
    for index,row in result.iterrows():
        stock_name = event.mysql.select_one('stock_manager', 'stock_name', f"stock_code='{index}'")
        row['stock_name'] = stock_name[0]

    result.to_excel('/home/friederich/Downloads/stock_data_3.xls')
    #print(result)

if __name__ == "__main__":
    profit_growth_analysis()


text:
package com.qd.clock.utils;

import android.content.Context;

import com.umeng.analytics.MobclickAgent;

public class GKStatics {
	public static String event_main = "event_main";

	public static void onEvent(Context context, String event) {
		MobclickAgent.onEvent(context, event);
	}

}


text:
  Romain est
       un village
       localisé dans le département de Jura en Franche-Comté. Elle totalisait 189 habitants en 2008.

Le parc de logements, à Romain, se décomposait en 2011 en cinq appartements et 87 maisons soit
 un marché relativement équilibré.

À proximité de Romain sont positionnées géographiquement les communes de
Chassal localisée à 2 km, 497 habitants,
Larrivoire à 3 km, 100 habitants,
Lavans-lès-Saint-Claude localisée à 3 km, 1 878 habitants,
Vaux-lès-Saint-Claude à 1 km, 703 habitants,
Jeurre située à 3 km, 257 habitants,
Molinges située à 1 km, 683 habitants,
 entre autres. De plus, Romain est située à seulement treize km de Oyonnax.

Si vous envisagez de demenager à Romain, vous pourrez facilement trouver une maison à vendre.


text:
module MainHelper
  def check_user
    if cookies.signed[:user_id]
      @current_user = User.find_by(:user_id, cookies.signed[:user_id])
      if params[:viewer_id]
        if params[:viewer_id].to_i == User.find(cookies.signed[:user_id])[:n_vk_id]
          return @authorized = true
        else
          cookies.signed[:user_id] = nil
          return @reload = true
        end
      else

        @authorized ||= true
      end
    elsif params[:viewer_id]

      if valid_user_info?
        user = User.find_by(:n_vk_id, (params[:viewer_id]))

        unless user
          user = User.new(params)
          user.save
        end

        @current_user = user

        cookies.signed[:user_id] = user[:user_id]
        @authorized = true
      else
        @authorized = false
      end
    else
      @authorized = false
    end
  end

  def valid_user_info?
    auth_parameters = Parameter.filter.split(',').join('|')
    auth_regex = Regexp.new(auth_parameters)
    university = JSON.parse(params['api_result'])['response'].first['university_name']
    university = university[auth_regex] if university
    schools = JSON.parse(params['api_result'])['response'].first['schools']
    school = schools.find{|school| school['name'][auth_regex]} if schools.any?
    !!(school || university)
  end
end


text:
local class = require("joueur.utilities.class")
local BaseGame = require("joueur.baseGame")

-- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
-- you can add additional require(s) here
-- <<-- /Creer-Merge: requires -->>

--- There's an infestation of enemy spiders challenging your queen broodmother spider! Protect her and attack the other broodmother in this turn based, node based, game.
-- @classmod Game
local Game = class(BaseGame)

-- initializes a Game with basic logic as provided by the Creer code generator
function Game:init(...)
    BaseGame.init(self, ...)

    --- The name of this game, "{game_name}".
    -- @field[string] self.name
    -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has.

    --- The player whose turn it is currently. That player can send commands. Other players cannot.
    self.currentPlayer = nil
    --- The current turn number, starting at 0 for the first player's turn.
    self.currentTurn = 0
    --- The speed at which Cutters work to do cut Webs.
    self.cutSpeed = 0
    --- Constant used to calculate how many eggs BroodMothers get on their owner's turns.
    self.eggsScalar = 0
    --- A mapping of every game object's ID to the actual game object. Primarily used by the server and client to easily refer to the game objects via ID.
    self.gameObjects = Table()
    --- The starting strength for Webs.
    self.initialWebStrength = 0
    --- The maximum number of turns before the game will automatically end.
    self.maxTurns = 100
    --- The speed at which Spiderlings move on Webs.
    self.movementSpeed = 0
    --- Every Nest in the game.
    self.nests = Table()
    --- List of all the players in the game.
    self.players = Table()
    --- A unique identifier for the game instance that is being played.
    self.session = ""
    --- The speed at which Spitters work to spit new Webs.
    self.spitSpeed = 0
    --- How much web strength is added or removed from Webs when they are weaved.
    self.weavePower = 0
    --- The speed at which Weavers work to do strengthens and weakens on Webs.
    self.weaveSpeed = 0
    --- Every Web in the game.
    self.webs = Table()

    self.name = "Spiders"

    self._gameObjectClasses = {
        BroodMother = require("games.spiders.broodMother"),
        Cutter = require("games.spiders.cutter"),
        GameObject = require("games.spiders.gameObject"),
        Nest = require("games.spiders.nest"),
        Player = require("games.spiders.player"),
        Spider = require("games.spiders.spider"),
        Spiderling = require("games.spiders.spiderling"),
        Spitter = require("games.spiders.spitter"),
        Weaver = require("games.spiders.weaver"),
        Web = require("games.spiders.web"),
    }
end

-- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
-- if you want to add any client side logic this is where you can add them
-- <<-- /Creer-Merge: functions -->>

return Game


text:
void test_parse_pes_input(void);
void test_parse_pes_data(void);

int main(int argc, char **argv)
{
    test_parse_pes_input();
    test_parse_pes_data();
    return 0;
}

void test_parse_pes_input(void)
{
    test_start("tsd_parse_pes input");

    TSDemuxContext ctx;
    TSDPESPacket pkt;
    TSDCode res;

    tsd_context_init(&ctx);

    char buffer[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };

    res = tsd_parse_pes(NULL, NULL, 0, NULL);
    test_assert_equal(TSD_INVALID_CONTEXT, res, "invalid context");
    res = tsd_parse_pes(&ctx, NULL, 0, &pkt);
    test_assert_equal(TSD_INVALID_DATA, res, "invalid data");
    res = tsd_parse_pes(&ctx, buffer, 5, &pkt);
    test_assert_equal(TSD_INVALID_DATA_SIZE, res, "invalid data size");
    res = tsd_parse_pes(&ctx, buffer, sizeof(buffer), NULL);
    test_assert_equal(TSD_INVALID_ARGUMENT, res, "invlaid TSDPESPacket");

    TSDPESPacket pes;
    res = tsd_parse_pes(&ctx, buffer, sizeof(buffer), &pes);
    test_assert_not_equal(TSD_OK, res, "invalid pes data");

    test_end();
}

void test_parse_pes_data(void)
{
    test_start("tsd_parse_pes data");

    TSDemuxContext ctx;
    TSDPESPacket pkt;
    TSDCode res;

    tsd_context_init(&ctx);

    char buffer[] = {
        0x00, 0x00, 0x01, // start code prefix
        0xE0,   // stream id
        0x00, 0x3C, // packet length
        0b10000010, // '10', scrmabling(2), priority(1), data alignment(1), copyright(1), original or copy(1)
        0b11101011, // pts dts(2), escr(1), es rate(1), dsm trick play(1), add copy info(1), crc (1), ext (1)
        0x49, // pes header data length
        0b00100001, 0x00, 0x01, 0x00, 0x01, // '0010', pts 4,3,1,15,1,15,1
        0b00011001, 0x00, 0x01, 0x00, 0x01, // '0001', dts 4,3,1,15,1,15,1
        0b11000100, 0x00, 0b00000100, 0x00, 0b00000100, 0x01, // ESCR, reserved(2), 3,1,15,1,15,1 ext 9,1
        0b01101000, // dsm trick play mode(3), field id(2), intra slice(1), freq trunc(2)
        0xAB, 0xBA, // crc flag
        // Extension
        0b01101111, //flags ,prv data(1), pack header(1), prog pk counter(1), pstd buffer(1), reserved(3), pes ext.2(1)
        0x19, // Pack header length
            // Pack header
            0x00, 0x00, 0x01, 0xBA, // pack start code
            0b01000100, // '01' scr base(3), marker(1), scr(2)
            0x00, 0b00000100, // scr(8), scr(5), marker(1), scr(2)
            0x00, 0b00000100, // scr(8), scr(5), marker(1), scr ext(2)
            0x01, // scr ext(7), marker(1)
            0xAB, 0xCD, 0xE3, // mux rate(22), marker(2)
            0b11111011, // reserved(5), pack stuffing length(3)
            0xFF, 0xFF, 0xFF, // stuffing bytes
                // system headers
                0x00, 0x00, 0x01, 0xBB, // sys header start code
                0x00, 0x0C, // header length
                0b10000000, 0x00, 0b00000001, // marker(1), rate bound(22), marker(1)
                0b11110010, // audio bound(6), fixed(1), csps(1)
                0b10100110, // sys audio lock(1), sys video lock(1), marker(1), video bound(5)
                0b11111111, // packet rate restriction(1), reserved(7)
                    0b11110000, // stream id
                    0b11100000, 0xBC, // '11', buffer bound scale(1), buffer bound size(13)
                    0b11000001, // stream id
                    0b11010001, 0x04, // '11', buffer bound scale(1), buffer bound size(13)
            // Pack header end
        0b10001101, 0b11000011, // marker(1), packet seq counter(7), marker(1), mpeg1/2 id(1), orig stuff len(6)
        0b10000010, // marker(1), pes ext field length(7)
        0xFF, 0xFF, // reserved (pes ext field)
        0xFF, 0xFF,// stuffing bytes
        0xAB, 0xBC, 0xDE, 0xF1, 0x23, // pes packet bytes
    };

    TSDPESPacket pes;
    res = tsd_parse_pes(&ctx, buffer, sizeof(buffer), &pes);
    test_assert_equal(TSD_OK, res, "valid pes parsing");

    test_assert_equal(pes.start_code, 0x01, "pes start code prefix");
    test_assert_equal(pes.stream_id, 0xE0, "stream id");
    test_assert_equal(pes.packet_length, 0x3C, "packet length");
    test_assert_equal(pes.scrambling_control, 0x00, "scrambling control");
    test_assert_equal(pes.flags & TSD_PPF_PES_PRIORITY, 0x00, "priority");
    test_assert_equal(pes.flags & TSD_PPF_DATA_ALIGNMENT_INDICATOR, 0x00, "data alignment");
    test_assert_equal(pes.flags & TSD_PPF_COPYRIGHT, TSD_PPF_COPYRIGHT, "copyright");
    test_assert_equal(pes.flags & TSD_PPF_ORIGINAL_OR_COPY, 0x00, "original or copy");
    test_assert_equal(pes.flags & TSD_PPF_PTS_FLAG, TSD_PPF_PTS_FLAG, "pts flag");
    test_assert_equal(pes.flags & TSD_PPF_DTS_FLAG, TSD_PPF_DTS_FLAG, "dts flag");
    test_assert_equal(pes.flags & TSD_PPF_ESCR_FLAG, TSD_PPF_ESCR_FLAG, "escr flag");
    test_assert_equal(pes.flags & TSD_PPF_ES_RATE_FLAG, 0x00, "es rate flag");
    test_assert_equal(pes.flags & TSD_PPF_DSM_TRICK_MODE_FLAG, TSD_PPF_DSM_TRICK_MODE_FLAG, "dsm trick play");
    test_assert_equal(pes.flags & TSD_PPF_ADDITIONAL_COPY_INFO_FLAG, 0x00, "additional copy info flag");
    test_assert_equal(pes.flags & TSD_PPF_PES_CRC_FLAG, TSD_PPF_PES_CRC_FLAG, "CRC flag");
    test_assert_equal(pes.flags & TSD_PPF_PES_EXTENSION_FLAG, TSD_PPF_PES_EXTENSION_FLAG, "PES extension flag");
    test_assert_equal(pes.header_data_length, 0x49, "header data length");
    test_assert_equal(pes.pts, 0x00000000, "pts");
    test_assert_equal(pes.dts, 0x00000000, "dts");
    test_assert_equal(pes.escr, 0x00000000, "escr");
    test_assert_equal(pes.escr_extension, 0x00000000, "escr extension");
    test_assert_equal(pes.trick_mode.control, TSD_TMC_FAST_REVERSE, "trick mode control");
    test_assert_equal(pes.trick_mode.field_id, 0x01, "field id");
    test_assert_equal(pes.trick_mode.intra_slice_refresh, 0x00, "intra slice refresh");
    test_assert_equal(pes.trick_mode.frequency_truncation, 0x00, "frequency truncation");
    test_assert_equal(pes.previous_pes_packet_crc, 0xABBA, "crc");
    test_assert_equal(pes.extension.flags & TSD_PEF_PES_PRIVATE_DATA_FLAG, 0x00, "pes private data");
    test_assert_equal(pes.extension.flags & TSD_PEF_PACK_HEADER_FIELD_FLAG, TSD_PEF_PACK_HEADER_FIELD_FLAG, "pack header");
    test_assert_equal(pes.extension.flags & TSD_PEF_PROGRAM_PACKET_SEQUENCE_COUNTER_FLAG, TSD_PEF_PROGRAM_PACKET_SEQUENCE_COUNTER_FLAG, "program packet seq counter");
    test_assert_equal(pes.extension.flags & TSD_PEF_PSTD_BUFFER_FLAG, 0x00, "p-std buffer");
    test_assert_equal(pes.extension.flags & TSD_PEF_PES_EXTENSION_FLAG_2, TSD_PEF_PES_EXTENSION_FLAG_2, "ext. flag 2");
    test_assert_equal(pes.extension.pack_header.length, 0x19, "pack header length");
    test_assert_equal(pes.extension.pack_header.start_code, 0x1BA, "pack header start code");
    test_assert_equal(pes.extension.pack_header.system_clock_ref_base, 0x00, "system clock ref base");
    test_assert_equal(pes.extension.pack_header.system_clock_ref_ext, 0x00, "system clock red ext.");
    test_assert_equal(pes.extension.pack_header.program_mux_rate, 0x2AF378, "program mux rate");
    test_assert_equal(pes.extension.pack_header.stuffing_length, 0x03, "pack stuffing length");
    TSDSystemHeader *syshdr = &pes.extension.pack_header.system_header;
    test_assert_equal(syshdr->start_code, 0x1BB, "system header start code");
    test_assert_equal(syshdr->length, 0x0C, "system header length");
    test_assert_equal(syshdr->rate_bound, 0x00, "system header rate bound");
    test_assert_equal(syshdr->audio_bound, 0x3C, "system header audio bound");
    test_assert_equal(syshdr->flags & TSD_SHF_FIXED_FLAG, TSD_SHF_FIXED_FLAG, "system header fixed flag");
    test_assert_equal(syshdr->flags & TSD_SHF_CSPS_FLAG, 0x00, "system header cspd flag");
    test_assert_equal(syshdr->flags & TSD_SHF_SYSTEM_AUDIO_LOCK_FLAG, TSD_SHF_SYSTEM_AUDIO_LOCK_FLAG, "system header audio lock");
    test_assert_equal(syshdr->flags & TSD_SHF_SYSTEM_VIDEO_LOCK_FLAG, 0x00, "system header video lock");
    test_assert_equal(syshdr->video_bound, 0x06, "system header video bound");
    test_assert_equal(syshdr->flags & TSD_SHF_PACKET_RATE_RESTICTION_FLAG, TSD_SHF_PACKET_RATE_RESTICTION_FLAG, "system header packet rate restriction");
    test_assert_equal(syshdr->stream_count, 0x02, "system header stream count");
    test_assert_equal(syshdr->streams[0].stream_id, 0xF0, "system header stream id 0");
    test_assert_equal(syshdr->streams[0].pstd_buffer_bound_scale, 0x01, "system header bound scale 0");
    test_assert_equal(syshdr->streams[0].pstd_buffer_size_bound, 0xBC, "system header bound size 0");
    test_assert_equal(syshdr->streams[1].stream_id, 0xC1, "system header stream id 1");
    test_assert_equal(syshdr->streams[1].pstd_buffer_bound_scale, 0x00, "system header bound scale 1");
    test_assert_equal(syshdr->streams[1].pstd_buffer_size_bound, 0x1104, "system header bound size 1");
    test_assert_equal(pes.extension.program_packet_sequence_counter, 0x0D, "sequence counter");
    test_assert_equal(pes.extension.mpeg1_mpeg2_identifier, 0x01, "mpeg1 mpeg2 indentifier");
    test_assert_equal(pes.extension.original_stuff_length, 0x03, "original stuff length");
    test_assert_equal(pes.extension.pes_extension_field_length, 0x02, "pes extension field length");
    test_assert_equal(pes.data_bytes_length, 0x05, "pes data length");
    char tmp_data[] = {0xAB, 0xBC, 0xDE, 0xF1, 0x23};
    test_assert_equal(memcmp(pes.data_bytes, tmp_data, 5), 0x00, "pes data");

    test_end();
}


text:
module AstronomyEngine
  VERSION = '0.3.0'
end


text:
<?php

require_once __DIR__.'/../../vendor/autoload.php';

$testsDir = '/tmp/wordpress-tests-lib';

require_once "{$testsDir}/includes/functions.php";

tests_add_filter('plugins_loaded', function() {
    require_once __DIR__.'/../../wp-tweaks.php';
});
tests_add_filter('muplugins_loaded', function() {
    // Require main mu-plugin files here
});

require_once "{$testsDir}/includes/bootstrap.php";


text:
package io.datty.spring.converter.name;

import org.junit.Assert;
import org.junit.Test;

import io.datty.api.DattyRecord;
import io.datty.spring.support.DattyConverterUtil;
import io.netty.buffer.ByteBuf;

/**
 * NamedEntityTest
 *
 * @author Alex Shvid
 *
 */

public class NamedEntityTest {

	@Test
	public void testNames() {

		NamedEntity entity = new NamedEntity();
		entity.setId(123L);
		entity.setName("Alex");

		DattyRecord rec = new DattyRecord();
		DattyConverterUtil.write(entity, rec);

		ByteBuf bb = rec.get("id").asByteBuf();
		Assert.assertNotNull(bb);

		bb = rec.get("first").asByteBuf();
		Assert.assertNotNull(bb);

		NamedMigratedEntity actual = DattyConverterUtil.read(NamedMigratedEntity.class, rec);
		Assert.assertEquals(entity.getId(), actual.getId());
		Assert.assertEquals(entity.getName(), actual.getName());

		rec = new DattyRecord();
		DattyConverterUtil.write(actual, rec);

		bb = rec.get("id").asByteBuf();
		Assert.assertNotNull(bb);

		Assert.assertNull(rec.get("first"));

		bb = rec.get("last").asByteBuf();
		Assert.assertNotNull(bb);

		//System.out.println(Arrays.toString(ByteBufUtil.getBytes(bb)));

		actual = DattyConverterUtil.read(NamedMigratedEntity.class, rec);
		Assert.assertEquals(entity.getId(), actual.getId());
		Assert.assertEquals(entity.getName(), actual.getName());

	}

}


text:
package org.apache.sis.internal.book;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Apply syntax colorization on Java code. This class is different than most other colorization tools
 * since its apply different colors depending on whether a word is known to be defined in an OGC/ISO
 * standard, in GeoAPI or in Apache SIS.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @since   0.7
 * @version 0.7
 * @module
 */
public final class CodeColorizer {
    /**
     * Lists of Java keywords.
     */
    public static final Set<String> JAVA_KEYWORDS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
        "abstract", "continue", "for",        "new",        "switch",
        "assert",   "default",  "goto",       "package",    "synchronized",
        "boolean",  "do",       "if",         "private",    "this",
        "break",    "double",   "implements", "protected",  "throw",
        "byte",     "else",     "import",     "public",     "throws",
        "case",     "enum",     "instanceof", "return",     "transient",
        "catch",    "extends",  "int",        "short",      "try",
        "char",     "final",    "interface",  "static",     "void",
        "class",    "finally",  "long",       "strictfp",   "volatile",
        "const",    "float",    "native",     "super",      "while",
        /* literals: */ "true", "false", "null")));

    /**
     * Returns all nodes in the given list as an array. This method is used for getting a snapshot
     * of the list before to modify it (for example before the elements are moved to another node).
     */
    static Node[] toArray(final NodeList nodes) {
        final Node[] children = new Node[nodes.getLength()];
        for (int i=0; i<children.length; i++) {
            children[i] = nodes.item(i);
        }
        return children;
    }

    /**
     * The specifier of an identifier.
     */
    private static enum Specifier {
        OGC("OGC"), GEOAPI("GeoAPI"), SIS("SIS"), XML_PREFIX(null);

        /** The value to put in the {@code class} attribute of {@code } or elements, or {@code null} if none. */
        final String style;

        /** Creates a new enum to be rendered with the given style. */
        private Specifier(final String style) {
            this.style = style;
        }
    };

    /**
     * Map of pre-defined identifiers and the authority who defined them.
     */
    private final Map<String,Specifier> identifierSpecifiers;

    /**
     * The object to use for creating nodes.
     */
    private final Document document;

    /**
     * Creates a new color colorizer.
     *
     * @param document the object to use for creating nodes.
     * @throws IOException if an error occurred while reading the list of pre-defined identifiers.
     * @throws BookException if an identifier is defined twice.
     */
    public CodeColorizer(final Document document) throws IOException, BookException {
        this.document = document;
        identifierSpecifiers = new HashMap<>(1000);
        for (final Specifier specifier : Specifier.values()) {
            final String filename = specifier.name() + ".lst";
            final InputStream in = CodeColorizer.class.getResourceAsStream(filename);
            if (in == null) {
                throw new FileNotFoundException(filename);
            }
            try (final BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
                String line;
                while ((line = r.readLine()) != null) {
                    if (identifierSpecifiers.put(line, specifier) != null) {
                        throw new BookException(line + " is defined twice in " + specifier);
                    }
                }
            }
        }
    }

    /**
     * Returns {@code true} if the given string starts with the given prefix,
     * and the character following the prefix is not an identifier character.
     */
    private static boolean startsWithWord(final String string, final String prefix) {
        return string.startsWith(prefix) && (string.length() <= prefix.length() ||
                !Character.isJavaIdentifierPart(string.codePointAt(prefix.length())));
    }

    /**
     * Returns {@code true} if the given string from {@code i} inclusive to {@code upper} exclusive
     * is a Java identifier.
     */
    private static boolean isJavaIdentifier(final String identifier, int i, final int upper) {
        if (upper <= i) {
            return false;
        }
        int c = identifier.codePointAt(i);
        if (!Character.isJavaIdentifierStart(c)) {
            return false;
        }
        while ((i += Character.charCount(c)) < upper) {
            c = Character.codePointAt(identifier, i);
            if (!Character.isJavaIdentifierPart(c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Returns the value to put inside in {@code class} attribute of a {@code } element
     * encompassing the given identifier.
     *
     *
This method differs from {@link #highlight(Node, String)} in that it is used for applying
     * a single style on the whole string. By contrast, {@code highlight(…)} parses the text and may
     * apply different styles for different words.

     */
    final String styleForSingleIdentifier(String word) {
        if (word.isEmpty()) {
            return null;
        }
        /*
         * If the given identifier is wrapped by some syntatic characters (e.g. "@Foo" for Java annotation,
         * or <Foo> for XML elements), remove the wrapper characters so we can get the identifier itelf.
         */
        switch (word.charAt(0)) {
            case '@': {
                word = word.substring(1);
                break;
            }
            case '<': {
                final int upper = word.length() - 1;
                if (word.charAt(upper) == '>') {
                    word = word.substring(1, upper);
                }
                break;
            }
        }
        /*
         * Check if the keyword is a known one. The 'identifierOrigins' map contains only simple name
         * without package name or XML prefix. Fully qualified names are less commons but easier to
         * check since the package/prefix name is sufficient.
         */
        Specifier specifier = identifierSpecifiers.get(word);
        if (specifier == null) {
            if (startsWithWord(word, "org.opengis") || startsWithWord(word, "geoapi")) {
                specifier = Specifier.GEOAPI;
            } else if (startsWithWord(word, "org.apache.sis") || startsWithWord(word, "sis")) {
                specifier = Specifier.SIS;
            } else {
                /*
                 * For more elaborated analysis than the above easy check, we need the Specifier enum of the
                 * first word. It may be a GeoAPI or SIS class name (e.g. "Citation" in "Citation.title"),
                 * or a XML prefix (e.g. "gmd" in "gmd:CI_Citation").
                 */
                int c, i=0;
                while (Character.isJavaIdentifierPart((c = word.charAt(i)))) {
                    i += Character.charCount(c);
                    if (i >= word.length()) {
                        return null;
                    }
                }
                specifier = identifierSpecifiers.get(word.substring(0, i));
                switch (c) {
                    default: {
                        return null;
                    }
                    case '.': {
                        if (specifier != null && specifier.style != null) {
                            int s = word.lastIndexOf('(');
                            if (s < 0) s = word.length();
                            if (isJavaIdentifier(word, i+1, s)) {
                                break;
                            }
                        }
                        return null;
                    }
                    case ':': {
                        if (specifier == Specifier.XML_PREFIX) {
                            break;
                        }
                        return null;
                    }
                }
            }
        }
        /*
         * Found the specifier. The XML prefix case is handle in a special way because
         * we do not highlight the "gmd", "gml", etc. prefixes in highlitht(…) method.
         */
        if (specifier == Specifier.XML_PREFIX) {
            specifier = Specifier.OGC;
        }
        return specifier.style;
    }

    /**
     * Applies emphasing on the words found in all text node of the given node.
     *
     * @param  parent the root element where to put Java keywords in bold characters.
     *         This is typically a {@code
} or {@code } element.
     * @param  type {@code "xml"} if the element to process is XML rather than Java code.
     * @throws BookException if an element can not be processed.
     */
    public void highlight(final Node parent, final String type) throws BookException {
        final boolean isXML = "xml".equals(type);
        final boolean isJava = !isXML;   // Future version may add more choices.
        Element syntaticElement = null;  // E.g. comment block or a String.
        String  stopCondition   = null;  // Identify 'syntaticElement' end.
        for (final Node node : toArray(parent.getChildNodes())) {
            /*
             * The following condition happen only if a quoted string or a comment started in a previous
             * node and is continuing in the current node. In such case we need to transfer everything we
             * found into the 'syntaticElement' node, until we found the 'stopCondition'.
             */
            if (stopCondition != null) {
                if (node.getNodeType() != Node.TEXT_NODE) {
                    syntaticElement.appendChild(node);          // Also remove from its previous position.
                    continue;
                }
                final String text = node.getTextContent();
                int lower = text.indexOf(stopCondition);
                if (lower >= 0) {
                    lower += stopCondition.length();
                    stopCondition = null;
                } else {
                    lower = text.length();
                }
                syntaticElement.appendChild(document.createTextNode(text.substring(0, lower)));
                node.setTextContent(text.substring(lower));
                // Continue below in case there is some remaining characters to analyse.
            }
            /*
             * The following is the usual code path where we search for Java keywords, OGC/ISO, GeoAPI and SIS
             * identifiers, and where the quoted strings and the comments are recognized.
             */
            switch (node.getNodeType()) {
                case Node.ELEMENT_NODE: {
                    highlight(node, type);
                    break;
                }
                case Node.TEXT_NODE: {
                    final String text = node.getTextContent();
                    int nextSubstringStart = 0, lower = 0;
                    while (lower < text.length()) {
                        int c = text.codePointAt(lower);
                        if (!Character.isJavaIdentifierStart(c)) {
                            if (c == '"') {
                                stopCondition = "\"";
                                syntaticElement = document.createElement("i");
                            } else if (isJava && text.regionMatches(lower, "/*", 0, 2)) {
                                stopCondition = "*/";
                                syntaticElement = document.createElement("code");
                                syntaticElement.setAttribute("class", "comment");
                            } else if (isJava && text.regionMatches(lower, "//", 0, 2)) {
                                stopCondition = "\n";
                                syntaticElement = document.createElement("code");
                                syntaticElement.setAttribute("class", "comment");
                            } else if (isXML && text.regionMatches(lower, "";
                                syntaticElement = document.createElement("code");
                                syntaticElement.setAttribute("class", "comment");
                            } else {
                                lower += Character.charCount(c);
                                continue;  // "Ordinary" character: scan next characters.
                            }
                            /*
                             * Found the begining of a comment block or a string. Search where that block ends
                             * (it may be in another node) and store all text between the current position and
                             * the end into 'syntaticElement'.
                             */
                            if (nextSubstringStart != lower) {
                                parent.insertBefore(document.createTextNode(text.substring(nextSubstringStart, lower)), node);
                            }
                            nextSubstringStart = lower;
                            lower = text.indexOf(stopCondition, lower+1);
                            if (lower >= 0) {
                                lower += stopCondition.length();
                                stopCondition = null;
                            } else {
                                lower = text.length();
                                // Keep stopCondition; we will need to search for it in next nodes.
                            }
                            syntaticElement.setTextContent(text.substring(nextSubstringStart, lower));
                            parent.insertBefore(syntaticElement, node);
                            nextSubstringStart = lower;
                        } else {
                            /*
                             * Found the beginning of a Java identifier. Search where it ends.
                             */
                            int upper = lower;
                            while (Character.isJavaIdentifierPart(c)) {
                                upper += Character.charCount(c);
                                if (upper >= text.length()) {
                                    break;
                                }
                                c = text.codePointAt(upper);
                            }
                            /*
                             * The following code is executed for each word which is a valid Java identifier.
                             * Different kind of emphase may be applied: bold for Java keywords, some colors
                             * for OGC/ISO classes, other colors for SIS classes, etc.
                             */
                            final String word = text.substring(lower, upper);
                            Element emphase = null;
                            if (JAVA_KEYWORDS.contains(word)) {
                                emphase = document.createElement("b");
                            } else if (isJava) {
                                final Specifier origin = identifierSpecifiers.get(word);
                                if (origin != null) {
                                    emphase = document.createElement("code");
                                    emphase.setAttribute("class", origin.style);
                                }
                            }
                            if (emphase != null) {
                                emphase.setTextContent(word);
                                if (nextSubstringStart != lower) {
                                    parent.insertBefore(document.createTextNode(text.substring(nextSubstringStart, lower)), node);
                                }
                                parent.insertBefore(emphase, node);
                                nextSubstringStart = upper;
                            }
                            lower = upper;
                        }
                    }
                    node.setTextContent(text.substring(nextSubstringStart));
                }
            }
        }
    }
}


text:
An open-source family of assemblies (MIT license) that targets and complements the Microsoft .NET platform (.NET 7, .NET 6, .NET Core 3.1, .NET Standard 2, Universal Windows Platform and .NET Framework 4.6.1 and newer) by providing vast ways of possibilities for all breeds of coders, programmers, developers and the likes thereof.

It is, by heart, free, flexible and built to extend and boost your agile codebelt.

## **Cuemon.Extensions.AspNetCore.Authentication.AwsSignature4** for .NET

The `Cuemon.Extensions.AspNetCore.Authentication.AwsSignature4` namespace complements the Cuemon.AspNetCore.Authentication namespace while providing a way making and signing HTTP requests in the context of specific AWS services using Signature Version 4.

More documentation available at [Cuemon for .NET documentation](https://docs.cuemon.net/api/extensions/awssignature4/Cuemon.Extensions.AspNetCore.Authentication.AwsSignature4.html).

### CSharp Example
```csharp
using var mw = MiddlewareTestFactory.Create();
var context = mw.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;

var timestamp = DateTime.Parse("2022-07-10T12:50:42.2737531Z"); // <-- change this to valid date/time

context.Request.Headers.Add(HttpHeaderNames.Host, "cuemon.s3.amazonaws.com");
context.Request.Headers.Add("x-amz-date", timestamp.ToAwsDateTimeString());
context.Request.Headers.Add("x-amz-content-sha256", UnkeyedHashFactory.CreateCryptoSha256().ComputeHash("").ToHexadecimalString());
context.Request.QueryString = QueryString.Create("list-type", "2");

var headerBuilder = new Aws4HmacAuthorizationHeaderBuilder()
    .AddFromRequest(context.Request)
    .AddClientId("AKIAIOSFODNN7EXAMPLE") // <-- change this to valid access key
    .AddClientSecret("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY") // <-- change this to valid secret
    .AddCredentialScope(timestamp);

var header = headerBuilder.Build().ToString(); // <-- send this AWS
```

### cURL Example
```powershell
curl --location --request GET 'https://cuemon.s3.amazonaws.com/?list-type=2' --header 'Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20220710/eu-west-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=feeb4c8ba41733fadc73cba6631ddfc9a729f371206bbaa77f216a69dd5299c5' --header 'x-amz-date: 20220710T145042Z' --header 'x-amz-content-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
```

## Related Packages

* [Cuemon.AspNetCore](https://www.nuget.org/packages/Cuemon.AspNetCore/) 📦
* [Cuemon.AspNetCore.App](https://www.nuget.org/packages/Cuemon.AspNetCore.App/) 🏭
* [Cuemon.AspNetCore.Authentication](https://www.nuget.org/packages/Cuemon.AspNetCore.Authentication/) 📦
* [Cuemon.AspNetCore.Mvc](https://www.nuget.org/packages/Cuemon.AspNetCore.Mvc/) 📦
* [Cuemon.AspNetCore.Razor.TagHelpers](https://www.nuget.org/packages/Cuemon.AspNetCore.Razor.TagHelpers/) 📦
* [Cuemon.Core](https://www.nuget.org/packages/Cuemon.Core/) 📦
* [Cuemon.Core.App](https://www.nuget.org/packages/Cuemon.Core.App/) 🏭
* [Cuemon.Data](https://www.nuget.org/packages/Cuemon.Data/) 📦
* [Cuemon.Data.Integrity](https://www.nuget.org/packages/Cuemon.Data.Integrity/) 📦
* [Cuemon.Data.SqlClient](https://www.nuget.org/packages/Cuemon.Data.SqlClient/) 📦
* [Cuemon.Diagnostics](https://www.nuget.org/packages/Cuemon.Diagnostics/) 📦
* [Cuemon.Extensions.Globalization](https://www.nuget.org/packages/Cuemon.Extensions.Globalization/) 📦
* [Cuemon.Extensions.AspNetCore](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore/) 📦
* [Cuemon.Extensions.AspNetCore.Authentication](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Authentication/) 📦
* [Cuemon.Extensions.AspNetCore.Authentication.AwsSignature4](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Authentication.AwsSignature4/) 📦
* [Cuemon.Extensions.AspNetCore.Mvc](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Mvc/) 📦
* [Cuemon.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json/) 📦
* [Cuemon.Extensions.AspNetCore.Mvc.Formatters.Text.Json](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Mvc.Formatters.Text.Json/) 📦
* [Cuemon.Extensions.AspNetCore.Mvc.Formatters.Xml](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Mvc.Formatters.Xml/) 📦
* [Cuemon.Extensions.AspNetCore.Mvc.RazorPages](https://www.nuget.org/packages/Cuemon.Extensions.AspNetCore.Mvc.RazorPages/) 📦
* [Cuemon.Extensions.Collections.Generic](https://www.nuget.org/packages/Cuemon.Extensions.Collections.Generic/) 📦
* [Cuemon.Extensions.Collections.Specialized](https://www.nuget.org/packages/Cuemon.Extensions.Collections.Specialized/) 📦
* [Cuemon.Extensions.Core](https://www.nuget.org/packages/Cuemon.Extensions.Core/) 📦
* [Cuemon.Extensions.Data](https://www.nuget.org/packages/Cuemon.Extensions.Data/) 📦
* [Cuemon.Extensions.Data.Integrity](https://www.nuget.org/packages/Cuemon.Extensions.Data.Integrity/) 📦
* [Cuemon.Extensions.DependencyInjection](https://www.nuget.org/packages/Cuemon.Extensions.DependencyInjection/) 📦
* [Cuemon.Extensions.Diagnostics](https://www.nuget.org/packages/Cuemon.Extensions.Diagnostics/) 📦
* [Cuemon.Extensions.Asp.Versioning](https://www.nuget.org/packages/Cuemon.Extensions.Asp.Versioning/) 📦
* [Cuemon.Extensions.Hosting](https://www.nuget.org/packages/Cuemon.Extensions.Hosting/) 📦
* [Cuemon.Extensions.IO](https://www.nuget.org/packages/Cuemon.Extensions.IO/) 📦
* [Cuemon.Extensions.Net](https://www.nuget.org/packages/Cuemon.Extensions.Net/) 📦
* [Cuemon.Extensions.Newtonsoft.Json](https://www.nuget.org/packages/Cuemon.Extensions.Newtonsoft.Json/) 📦
* [Cuemon.Extensions.Newtonsoft.Json.App](https://www.nuget.org/packages/Cuemon.Extensions.Newtonsoft.Json.App/) 🏭
* [Cuemon.Extensions.Reflection](https://www.nuget.org/packages/Cuemon.Extensions.Reflection/) 📦
* [Cuemon.Extensions.Runtime.Caching](https://www.nuget.org/packages/Cuemon.Extensions.Runtime.Caching/) 📦
* [Cuemon.Extensions.Swashbuckle.AspNetCore](https://www.nuget.org/packages/Cuemon.Extensions.Swashbuckle.AspNetCore/) 📦
* [Cuemon.Extensions.Text](https://www.nuget.org/packages/Cuemon.Extensions.Text/) 📦
* [Cuemon.Extensions.Text.Json](https://www.nuget.org/packages/Cuemon.Extensions.Text.Json/) 📦
* [Cuemon.Extensions.Threading](https://www.nuget.org/packages/Cuemon.Extensions.Threading/) 📦
* [Cuemon.Extensions.Xml](https://www.nuget.org/packages/Cuemon.Extensions.Xml/) 📦
* [Cuemon.Extensions.Xunit](https://www.nuget.org/packages/Cuemon.Extensions.Xunit/) 📦
* [Cuemon.Extensions.Xunit.App](https://www.nuget.org/packages/Cuemon.Extensions.Xunit.App/) 🏭
* [Cuemon.Extensions.Xunit.Hosting](https://www.nuget.org/packages/Cuemon.Extensions.Xunit.Hosting/) 📦
* [Cuemon.Extensions.Xunit.Hosting.AspNetCore](https://www.nuget.org/packages/Cuemon.Extensions.Xunit.Hosting.AspNetCore/) 📦
* [Cuemon.Extensions.Xunit.Hosting.AspNetCore.Mvc](https://www.nuget.org/packages/Cuemon.Extensions.Xunit.Hosting.AspNetCore.Mvc/) 📦
* [Cuemon.IO](https://www.nuget.org/packages/Cuemon.IO/) 📦
* [Cuemon.Net](https://www.nuget.org/packages/Cuemon.Net/) 📦
* [Cuemon.Resilience](https://www.nuget.org/packages/Cuemon.Resilience/) 📦
* [Cuemon.Runtime.Caching](https://www.nuget.org/packages/Cuemon.Runtime.Caching/) 📦
* [Cuemon.Security.Cryptography](https://www.nuget.org/packages/Cuemon.Security.Cryptography/) 📦
* [Cuemon.Threading](https://www.nuget.org/packages/Cuemon.Threading/) 📦
* [Cuemon.Xml](https://www.nuget.org/packages/Cuemon.Xml/) 📦


text:
{{ album.title }}

{{ album.description }}

 0">
			<audio-sample ng-repeat="sample in album.samples | orderBy: recordingsOrderPredicate" src="sample.src" song-title="sample.title">{{ sample.title }}</audio-sample>

 0">BUY NOW!

			{{ store.storeName }}


text:
package es.mresti.xemio.app.contract;

import com.firebase.client.Firebase;

/**
 * This specifies the contract between the view and the presenter.
 */
public interface HistoricalDetailContract {

  interface View extends BaseContract.BaseView {

  }

  interface UserActionsListener {
    Firebase getHistoricalRef(String key);
  }
}


text:
//
//  WCSession.h
//  WatchConnectivity
//
//  Copyright (c) 2015 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@class WCSessionFile, WCSessionFileTransfer, WCSessionUserInfoTransfer;
@protocol WCSessionDelegate;

typedef NS_ENUM(NSInteger, WCSessionActivationState) {
	WCSessionActivationStateNotActivated  = 0,
	WCSessionActivationStateInactive      = 1,
	WCSessionActivationStateActivated     = 2,
} __IOS_AVAILABLE(9.3) __WATCHOS_AVAILABLE(2.2);

/** -------------------------------- WCSession ----------------------------------
 *  The default session is used to communicate between two counterpart apps
 *  (i.e. iOS app and its native WatchKit extension). The session provides
 *  methods for sending, receiving, and tracking state.
 *
 *  On start up an app should set a delegate on the default session and call
 *  activate. This will allow the system to populate the state properties and
 *  deliver any outstanding background transfers.
 */
NS_CLASS_AVAILABLE_IOS(9.0)
@interface WCSession : NSObject

/** Check if session is supported on this iOS device. Session is always available on WatchOS */
+ (BOOL)isSupported;

/** Use the default session for all transferring of content and state monitoring. */
+ (WCSession *)defaultSession;

/** Use the default session instead. */
- (instancetype)init NS_UNAVAILABLE;

/** A delegate must exist before the session will allow sends. */
@property (nonatomic, weak, nullable) id <WCSessionDelegate> delegate;

/** The default session must be activated on startup before the session's properties contain correct values and will begin receiving delegate callbacks. Calling activate without a delegate set is undefined. If the WCSessionDelegate session:activationDidCompleteWithState:error: is implemented this method becomes an asynchronous call. */
- (void)activateSession;

/** The state of the current session */
@property (nonatomic, readonly) WCSessionActivationState activationState __IOS_AVAILABLE(9.3) __WATCHOS_AVAILABLE(2.2);

/** ------------------------- iOS App State For Watch ---------------------------
 *  State information that applies to Watch and is only available to the iOS app.
 *  This information includes device state, counterpart app state, and iOS app
 *  information specific to Watch.
 */

/** Check if iOS device is paired to a watch */
@property (nonatomic, readonly, getter=isPaired) BOOL paired __WATCHOS_UNAVAILABLE;

/** Check if the user has the Watch app installed */
@property (nonatomic, readonly, getter=isWatchAppInstalled) BOOL watchAppInstalled __WATCHOS_UNAVAILABLE;

/** Check if the user has the Watch app's complication enabled */
@property (nonatomic, readonly, getter=isComplicationEnabled) BOOL complicationEnabled __WATCHOS_UNAVAILABLE;

/** Use this directory to persist any data specific to the selected Watch. The location of the URL will change when the selected Watch changes. This directory will be deleted upon next launch if the watch app is uninstalled for the selected Watch, or that Watch is unpaired. If the watch app is not installed for the selected Watch the value will be nil. */
@property (nonatomic, readonly, nullable) NSURL *watchDirectoryURL __WATCHOS_UNAVAILABLE;

/** -------------------------- Interactive Messaging ---------------------------
 *  Interactive messages can only be sent between two actively running apps.
 *  They require the counterpart app to be reachable.
 */

/** The counterpart app must be reachable for a send message to succeed. */
@property (nonatomic, readonly, getter=isReachable) BOOL reachable;

/** Reachability in the Watch app requires the paired iOS device to have been unlocked at least once after reboot. This property can be used to determine if the iOS device needs to be unlocked. If the reachable property is set to NO it may be because the iOS device has rebooted and needs to be unlocked. If this is the case, the Watch can show a prompt to the user suggesting they unlock their paired iOS device. */
@property (nonatomic, readonly) BOOL iOSDeviceNeedsUnlockAfterRebootForReachability __IOS_UNAVAILABLE __WATCHOS_AVAILABLE(2.0);

/** Clients can use this method to send messages to the counterpart app. Clients wishing to receive a reply to a particular message should pass in a replyHandler block. If the message cannot be sent or if the reply could not be received, the errorHandler block will be invoked with an error. If both a replyHandler and an errorHandler are specified, then exactly one of them will be invoked. Messages can only be sent while the sending app is running. If the sending app exits before the message is dispatched the send will fail. If the counterpart app is not running the counterpart app will be launched upon receiving the message (iOS counterpart app only). The message dictionary can only accept the property list types. */
- (void)sendMessage:(NSDictionary<NSString *, id> *)message replyHandler:(nullable void (^)(NSDictionary<NSString *, id> *replyMessage))replyHandler errorHandler:(nullable void (^)(NSError *error))errorHandler;

/** Clients can use this method to send message data. All the policies of send message apply to send message data. Send message data is meant for clients that have an existing transfer format and do not need the convenience of the send message dictionary. */
- (void)sendMessageData:(NSData *)data replyHandler:(nullable void (^)(NSData *replyMessageData))replyHandler errorHandler:(nullable void (^)(NSError *error))errorHandler;

/** --------------------------- Background Transfers ---------------------------
 *  Background transfers continue transferring when the sending app exits. The
 *  counterpart app (other side) is not required to be running for background
 *  transfers to continue. The system will transfer content at opportune times.
 */

/** Setting the applicationContext is a way to transfer the latest state of an app. After updating the applicationContext, the system initiates the data transfer at an appropriate time, which can occur after the app exits. The counterpart app will receive a delegate callback on next launch if the applicationContext has successfully arrived. If there is no app context, it should be updated with an empty dictionary. The applicationContext dictionary can only accept the property list types. */
@property (nonatomic, readonly, copy) NSDictionary<NSString *, id> *applicationContext;
- (BOOL)updateApplicationContext:(NSDictionary<NSString *, id> *)applicationContext error:(NSError **)error;

/** Stores the most recently received applicationContext from the counterpart app. */
@property (nonatomic, readonly, copy) NSDictionary<NSString *, id> *receivedApplicationContext;

/** The system will enqueue the user info dictionary and transfer it to the counterpart app at an opportune time. The transfer of user info will continue after the sending app has exited. The counterpart app will receive a delegate callback on next launch if the file has successfully arrived. The userInfo dictionary can only accept the property list types.
 */
- (WCSessionUserInfoTransfer *)transferUserInfo:(NSDictionary<NSString *, id> *)userInfo;

/** Enqueues a user info dictionary containing the most current information for an enabled complication. If the app's complication is enabled the system will try to transfer this user info immediately. Once a current complication user info is received the system will launch the Watch App Extension in the background and allow it to update the complication content. If the current user info cannot be transferred (i.e. devices disconnected, out of background launch budget, etc.) it will wait in the outstandingUserInfoTransfers queue until next opportune time. There can only be one current complication user info in the outstandingUserInfoTransfers queue. If a current complication user info is outstanding (waiting to transfer) and -transferCurrentComplicationUserInfo: is called again with new user info, the new user info will be tagged as current and the previously current user info will be untagged. The previous user info will however stay in the queue of outstanding transfers. */
- (WCSessionUserInfoTransfer *)transferCurrentComplicationUserInfo:(NSDictionary<NSString *, id> *)userInfo __WATCHOS_UNAVAILABLE;

/** Returns an array of user info transfers that are still transferring (i.e. have not been cancelled, failed, or been received by the counterpart app).*/
@property (nonatomic, readonly, copy) NSArray<WCSessionUserInfoTransfer *> *outstandingUserInfoTransfers;

/** The system will enqueue the file and transfer it to the counterpart app at an opportune time. The transfer of a file will continue after the sending app has exited. The counterpart app will receive a delegate callback on next launch if the file has successfully arrived. The metadata dictionary can only accept the property list types. */
- (WCSessionFileTransfer *)transferFile:(NSURL *)file metadata:(nullable NSDictionary<NSString *, id> *)metadata;

/** Returns an array of file transfers that are still transferring (i.e. have not been cancelled, failed, or been received by the counterpart app). */
@property (nonatomic, readonly, copy) NSArray<WCSessionFileTransfer *> *outstandingFileTransfers;

@end

/** ----------------------------- WCSessionDelegate -----------------------------
 *  The session calls the delegate methods when content is received and session
 *  state changes. All delegate methods will be called on the same queue. The
 *  delegate queue is a non-main serial queue. It is the client's responsibility
 *  to dispatch to another queue if neccessary.
 */
@protocol WCSessionDelegate <NSObject>

@optional

/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error __IOS_AVAILABLE(9.3) __WATCHOS_AVAILABLE(2.2);

/** ------------------------- iOS App State For Watch ------------------------ */

/** Called when the session can no longer be used to modify or add any new transfers and, all interactive messages will be cancelled, but delegate callbacks for background transfers can still occur. This will happen when the selected watch is being changed. */
- (void)sessionDidBecomeInactive:(WCSession *)session __IOS_AVAILABLE(9.3) __WATCHOS_UNAVAILABLE;

/** Called when all delegate callbacks for the previously selected watch has occurred. The session can be re-activated for the now selected watch using activateSession. */
- (void)sessionDidDeactivate:(WCSession *)session __IOS_AVAILABLE(9.3) __WATCHOS_UNAVAILABLE;

/** Called when any of the Watch state properties change. */
- (void)sessionWatchStateDidChange:(WCSession *)session __WATCHOS_UNAVAILABLE;

/** ------------------------- Interactive Messaging ------------------------- */

/** Called when the reachable state of the counterpart app changes. The receiver should check the reachable property on receiving this delegate callback. */
- (void)sessionReachabilityDidChange:(WCSession *)session;

/** Called on the delegate of the receiver. Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message;

/** Called on the delegate of the receiver when the sender sends a message that expects a reply. Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler;

/** Called on the delegate of the receiver. Will be called on startup if the incoming message data caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessageData:(NSData *)messageData;

/** Called on the delegate of the receiver when the sender sends message data that expects a reply. Will be called on startup if the incoming message data caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessageData:(NSData *)messageData replyHandler:(void(^)(NSData *replyMessageData))replyHandler;

/** -------------------------- Background Transfers ------------------------- */

/** Called on the delegate of the receiver. Will be called on startup if an applicationContext is available. */
- (void)session:(WCSession *)session didReceiveApplicationContext:(NSDictionary<NSString *, id> *)applicationContext;

/** Called on the sending side after the user info transfer has successfully completed or failed with an error. Will be called on next launch if the sender was not running when the user info finished. */
- (void)session:(WCSession * __nonnull)session didFinishUserInfoTransfer:(WCSessionUserInfoTransfer *)userInfoTransfer error:(nullable NSError *)error;

/** Called on the delegate of the receiver. Will be called on startup if the user info finished transferring when the receiver was not running. */
- (void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *, id> *)userInfo;

/** Called on the sending side after the file transfer has successfully completed or failed with an error. Will be called on next launch if the sender was not running when the transfer finished. */
- (void)session:(WCSession *)session didFinishFileTransfer:(WCSessionFileTransfer *)fileTransfer error:(nullable NSError *)error;

/** Called on the delegate of the receiver. Will be called on startup if the file finished transferring when the receiver was not running. The incoming file will be located in the Documents/Inbox/ folder when being delivered. The receiver must take ownership of the file by moving it to another location. The system will remove any content that has not been moved when this delegate method returns. */
- (void)session:(WCSession *)session didReceiveFile:(WCSessionFile *)file;

@end

NS_ASSUME_NONNULL_END


text:
namespace Microsoft.Zelig.Runtime.TypeSystem
{
    using System;
    using System.Collections.Generic;

    public sealed class AssemblyRepresentation
    {
        public struct VersionData
        {
            //
            // This is just a copy of Microsoft.Zelig.MetaData.AssemblyFlags, needed to break the dependency of TypeSystem from MetaData.
            //
            public enum AssemblyFlags
            {
                PublicKey                  = 0x0001, // The assembly ref holds the full (unhashed) public key.
                CompatibilityMask          = 0x0070,
                SideBySideCompatible       = 0x0000, // The assembly is side by side compatible.
                NonSideBySideAppDomain     = 0x0010, // The assembly cannot execute with other versions if they are executing in the same application domain.
                NonSideBySideProcess       = 0x0020, // The assembly cannot execute with other versions if they are executing in the same process.
                NonSideBySideMachine       = 0x0030, // The assembly cannot execute with other versions if they are executing on the same machine.
                EnableJITcompileTracking   = 0x8000, // From "DebuggableAttribute".
                DisableJITcompileOptimizer = 0x4000  // From "DebuggableAttribute".
            }

            //
            // State
            //

            public short         MajorVersion;
            public short         MinorVersion;
            public short         BuildNumber;
            public short         RevisionNumber;
            public AssemblyFlags Flags;
            public byte[]        PublicKey;

            //
            // Helper Methods
            //

            public bool IsCompatible( ref VersionData ver   ,
                                          bool        exact )
            {
                // BUGBUG: This ignores the strong name of an assembly.

                if(this.MajorVersion   < ver.MajorVersion            ) return false;
                if(this.MajorVersion   > ver.MajorVersion   && !exact) return true;

                if(this.MinorVersion   < ver.MinorVersion            ) return false;
                if(this.MinorVersion   > ver.MinorVersion   && !exact) return true;

                if(this.BuildNumber    < ver.BuildNumber             ) return false;
                if(this.BuildNumber    > ver.BuildNumber    && !exact) return true;

                if(this.RevisionNumber < ver.RevisionNumber          ) return false;
                if(this.RevisionNumber > ver.RevisionNumber && !exact) return true;

                return true;
            }

            public void ApplyTransformation( TransformationContext context )
            {
                context.Transform( ref this.MajorVersion   );
                context.Transform( ref this.MinorVersion   );
                context.Transform( ref this.BuildNumber    );
                context.Transform( ref this.RevisionNumber );
                context.Transform( ref this.Flags          );
                context.Transform( ref this.PublicKey      );
            }

            //
            // Access Methods
            //

            //
            // Debug Methods
            //

            public override String ToString()
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataVersion(" );

                sb.Append( MajorVersion                              );
                sb.Append( ","                                       );
                sb.Append( MinorVersion                              );
                sb.Append( ","                                       );
                sb.Append( BuildNumber                               );
                sb.Append( ","                                       );
                sb.Append( RevisionNumber                            );
                sb.Append( ","                                       );
                sb.Append( Flags                                     );
                sb.Append( ",["                                      );
                // BUGBUG: ArrayReader.AppendAsString( sb, PublicKey );
                sb.Append( "])" );

                return sb.ToString();
            }
        }

        //
        // State
        //

        private string      m_name;
        private VersionData m_version;

        //
        // Constructor Methods
        //

        public AssemblyRepresentation(     string      name    ,
                                       ref VersionData version )
        {
            CHECKS.ASSERT( name != null, "Cannot create an AssemblyRepresentation without a name" );

            m_name    = name;
            m_version = version;
        }

        //
        // MetaDataEquality Methods
        //

        public override bool Equals( object obj )
        {
            if(obj is AssemblyRepresentation)
            {
                AssemblyRepresentation other = (AssemblyRepresentation)obj;

                if(m_name == other.m_name)
                {
                    if(m_version.IsCompatible( ref other.m_version, true ))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public override int GetHashCode()
        {
            return      m_name.GetHashCode()     ^
                   (int)m_version.MajorVersion   ^
                   (int)m_version.MinorVersion   ^
                   (int)m_version.BuildNumber    ^
                   (int)m_version.RevisionNumber;
        }

        //--//

        //
        // Helper Methods
        //

        public void ApplyTransformation( TransformationContext context )
        {
            context.Push( this );

            context.Transform( ref m_name    );
            context.Transform( ref m_version );

            context.Pop();
        }

        //--//

        //
        // Access Methods
        //

        public VersionData Version
        {
            get
            {
                return m_version;
            }
        }

        public String Name
        {
            get
            {
                return m_name;
            }
        }
    }
}


text:
function [latentMean,LatentDataHandler] = meanLatentsDB(indices,LatentDataHandler)
%functions to keep a matrix of all the latent variables sampled for the ramping model without taking too much RAM
%Information about what is stored/loaded is all in LatentDataHandler! Keep this object around.
%
% takes the mean of all latents

%checks data setup
if(LatentDataHandler.DataBlockNumber <= 0)
    error('Invalid data block');
end
if(LatentDataHandler.DataRowLength <= 0)
    error('Data storage not initialized.');
end

% get block number for each index
blockIdx = floor((indices-1)/LatentDataHandler.DataRowsPerBlock) + 1;

% save each block, starting with any rows in current block
blockIdxs = unique(blockIdx);

latentBlock = zeros(LatentDataHandler.DataRowLength,length(blockIdxs));
Ns = zeros(length(blockIdxs),1);

blockOrderToRun = [blockIdxs(blockIdxs == LatentDataHandler.DataBlockNumber) blockIdxs(blockIdxs ~= LatentDataHandler.DataBlockNumber)];
for ii = blockOrderToRun

    LatentDataHandler = loadLatentFileDB(ii,LatentDataHandler);

    indicesInBlock = find(blockIdx == ii);
    offset = (ii-1)*LatentDataHandler.DataRowsPerBlock;

    if(max(indices(indicesInBlock)-offset) > size(LatentDataHandler.DataBlock,2))
        error('Accessing data outside pre-initialized block');
    else
        latentBlock(:,blockIdxs == ii) = mean(LatentDataHandler.DataBlock(:,indices(indicesInBlock)-offset),2);
        Ns(blockIdxs == ii) = length(indicesInBlock);

        if(sum(LatentDataHandler.DataValidRows(indices(indicesInBlock)-offset) < 1) > 0)
            warning('Loading data from unitialized array index');
        end
    end
end

latentMean = latentBlock * (Ns./sum(Ns));


text:
import { drawChoropleth, getThresholds, findValue } from './utils'
import base from './conf'

export default class ChoroplethLayer {
  constructor (conf) {
    this.conf = Object.assign({}, base, conf)
    this.thresholds = getThresholds(this.conf.data, this.conf.level)
    this.drawChoropleth = drawChoropleth.bind(this)
  }
  onAreaEnter (map, areaProps) {
    let value = findValue(areaProps.name, this.conf.data)
    this.conf.onAreaEnter({
      name: areaProps.name,
      cp: areaProps.cp,
      value: value
    })
  }
  onAreaLeave (map, areaProps) {
    let value = findValue(areaProps.name, this.conf.data)
    this.conf.onAreaLeave({
      name: areaProps.name,
      cp: areaProps.cp,
      value: value
    })
  }
  // hover 时叠加浅色遮罩
  onAreaHover (map, points, areaProps) {
    map.ctx.fillStyle = 'rgba(255, 255, 255, 0.4)'
    map.utils.drawPath(map.ctx, points)
  }
  afterAreaDraw (map, points, areaProps) {
    this.drawChoropleth(map, points, areaProps)
  }
}

if (typeof module !== 'undefined') module.exports = ChoroplethLayer