text:
using System;
using QuantConnect.Algorithm;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

package com.quantconnect.lean
{
    /**
     * QuantConnect University: Indicator Suite Example.
    */
    public class IndicatorSuiteAlgorithm : QCAlgorithm
    {
        String _symbol = "SPY";
        String _customSymbol = "BTC";

        Indicators _indicators;
        Indicators _selectorIndicators;
        IndicatorBase<IndicatorDataPoint> _ratio;

            //RSI Custom Data:
        RelativeStrengthIndex _rsiCustom;
        Minimum _minCustom;
        Maximum _maxCustom;

        BigDecimal _price;

        /**
         * Initialize the data and resolution you require for your strategy
        */
        public @Override void Initialize() {
            //Initialize
            SetStartDate(2013, 1, 1);
            SetEndDate(2014, 12, 31);
            SetCash(25000);

            //Add as many securities as you like. All the data will be passed into the event handler:
            AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute);

            //Add the Custom Data:
            AddData<Bitcoin>( "BTC");

            //Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
            _indicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily),
                EMA = EMA(_symbol, 14, Resolution.Daily),
                SMA = SMA(_symbol, 14, Resolution.Daily),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily),
                AROON = AROON(_symbol, 20, Resolution.Daily),
                MOM = MOM(_symbol, 20, Resolution.Daily),
                MOMP = MOMP(_symbol, 20, Resolution.Daily),
                STD = STD(_symbol, 20, Resolution.Daily),
                MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property
                MAX = MAX(_symbol, 14, Resolution.Daily)  // by default if the symbol is a tradebar type then it will be the max of the high property
            };

            // Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
            //  These functions have a signature like the following: BigDecimal Selector(BaseData baseData), and can be defined like: baseData -> baseData.Value
            //  We'll define these 'selector' functions to select the Low value
            //
            //  For more information on 'anonymous functions' see: http://en.wikipedia.org/wiki/Anonymous_function
            //                                                     https://msdn.microsoft.com/en-us/library/bb397687.aspx
            //
            _selectorIndicators = new Indicators
            {
                BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                EMA = EMA(_symbol, 14, Resolution.Daily, Field.Low),
                SMA = SMA(_symbol, 14, Resolution.Daily, Field.Low),
                MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Daily, Field.Low),
                MOM = MOM(_symbol, 20, Resolution.Daily, Field.Low),
                MOMP = MOMP(_symbol, 20, Resolution.Daily, Field.Low),
                STD = STD(_symbol, 20, Resolution.Daily, Field.Low),
                MIN = MIN(_symbol, 14, Resolution.Daily, Field.High), // this will find the 14 day min of the high property
                MAX = MAX(_symbol, 14, Resolution.Daily, Field.Low),  // this will find the 14 day max of the low property

                // ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
                // before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
                ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily, SelectorDoubleTradeBar),
                AROON = AROON(_symbol, 20, Resolution.Daily, SelectorDoubleTradeBar)
            };

            //Custom Data Indicator:
            _rsiCustom = RSI(_customSymbol, 14, MovingAverageType.Simple, Resolution.Daily);
            _minCustom = MIN(_customSymbol, 14, Resolution.Daily);
            _maxCustom = MAX(_customSymbol, 14, Resolution.Daily);

            // in addition to defining indicators on a single security, you can all define 'composite' indicators.
            // these are indicators that require multiple inputs. the most common of which is a ratio.
            // suppose we seek the ratio of BTC to SPY, we could write the following:
            spyClose = Identity(_symbol);
            btcClose = Identity(_customSymbol);
            // this will create a new indicator whose value is BTC/SPY
            _ratio = btcClose.Over(spyClose);
            // we can also easily plot our indicators each time they update using th PlotIndicator function
            PlotIndicator( "Ratio", _ratio);
        }

        /**
         * Custom data event handler:
        */
         * @param data Bitcoin - dictionary of TradeBarlike Bars of Bitcoin Data
        public void OnData(Bitcoin data) {
        }

        /**
         * OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        */
         * @param data TradeBars IDictionary object with your stock data
        public void OnData(TradeBars data) {
            if( !_indicators.BB.IsReady || !_indicators.RSI.IsReady) return;

            _price = data["SPY"].Close;

            if( !Portfolio.HoldStock) {
                int quantity = (int)Math.Floor(Portfolio.Cash / data[_symbol].Close);

                //Order function places trades: enter the String symbol and the quantity you want:
                Order(_symbol, quantity);

                //Debug sends messages to the user console: "Time" is the algorithm time keeper object
                Debug( "Purchased SPY on " + Time.ToShortDateString());
            }
        }

        /**
         * Fire plotting events once per day.
        */
        public @Override void OnEndOfDay() {
            if( !_indicators.BB.IsReady) return;

            Plot( "BB", "Price", _price);
            Plot( "BB", _indicators.BB.UpperBand, _indicators.BB.MiddleBand, _indicators.BB.LowerBand);

            Plot( "RSI", _indicators.RSI);

            //Custom data indicator
            Plot( "RSI-BTC", _rsiCustom);

            Plot( "ATR", _indicators.ATR);

            Plot( "STD", _indicators.STD);

            Plot( "AROON", _indicators.AROON.AroonUp, _indicators.AROON.AroonDown);

            Plot( "MOM", _indicators.MOM);
            Plot( "MOMP", _indicators.MOMP);

            Plot( "MACD", "Price", _price);
            Plot( "MACD", _indicators.MACD.Fast, _indicators.MACD.Slow, _indicators.MACD.Signal);

            Plot( "Averages", _indicators.EMA, _indicators.SMA);
        }

        /**
         * Class to hold a bunch of different indicators for this example
        */
        class Indicators
        {
            public BollingerBands BB;
            public SimpleMovingAverage SMA;
            public ExponentialMovingAverage EMA;
            public RelativeStrengthIndex RSI;
            public AverageTrueRange ATR;
            public StandardDeviation STD;
            public AroonOscillator AROON;
            public Momentum MOM;
            public MomentumPercent MOMP;
            public MovingAverageConvergenceDivergence MACD;
            public Minimum MIN;
            public Maximum MAX;
        }

        /**
         * Function used to select a trade bar that has double the values of the input trade bar
        */
        private static TradeBar SelectorDoubleTradeBar(BaseData baseData) {
            bar = (TradeBar)baseData;
            return new TradeBar
            {
                Close = 2 * bar.Close,
                DataType = bar.DataType,
                High = 2 * bar.High,
                Low = 2 * bar.Low,
                Open = 2 * bar.Open,
                Symbol = bar.Symbol,
                Time = bar.Time,
                Value = 2 * bar.Value,
                Volume = 2 * bar.Volume,
                Period = bar.Period
            };
        }
    }
}


text:
package com.salesforce.dva.argus.util;

import com.salesforce.dva.argus.service.metric.MetricReader;

public class TransformUtil {

	public static long getWindowInSeconds(String window) {
		MetricReader.TimeUnit timeunit = null;

		try {
			timeunit = MetricReader.TimeUnit.fromString(window.substring(window.length() - 1));
			long timeDigits = Long.parseLong(window.substring(0, window.length() - 1));
			return timeDigits * timeunit.getValue() / 1000;
		} catch (Exception t) {
			throw new IllegalArgumentException("Fail to parse window size!");
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

$languages = array(
    "register_page" => "Регистрация",
    "uagree_page" => "Пользовательское соглашение",
    "register_disabled" => "Извините, но регистрация отключена администратором!",
    "register_only_invite" => "<b>Внимание:</b> регистрация доступна только при наличии пригласительного кода!",
    "register_invalid_invite_code" => "Неправильный пригласительный код",
    "register_step_by_step" => "Регистрация шаг-за-шагом",
    "register_user_agree" => "Пользовательское соглашение",
    "register_next" => "Далее",
    "register_back" => "Назад",
    "register_end" => "Регистрация",
    'register_user_exists' => "Данное имя пользователя уже существует",
    'register_email_exists' => "Данный E-mail уже существует",
    'register_len_login' => "Длина логина должна быть от 2 до 25 символов. Логин должен содержать символы a-z, а-я, 0-9, -, _",
    'register_len_pass' => "Длина пароля должна быть от 6 до 15 символов",
    'register_false_passagain' => "Повтор пароля не совпадает с самим паролем",
    'register_false_email' => "E-mail не похож на настоящий",
    'register_not_valid_website' => "Введённый Вами адрес сайта не является правильным",
    "register_all_areas_must_be" => "Все поля, отмеченные звёздочкой, должны быть заполнены!",
    'register_area_username' => "Имя пользователя*:",
    'register_area_password' => "Пароль*:",
    'register_area_passagain' => "Потвор пароля*:",
    'register_area_email' => "E-mail*:",
    'register_area_birthday' => "Дата рождения*:",
    'register_area_country' => "Страна:",
    'register_area_town' => "Город:",
    'register_area_timezone' => "Часовой пояс:",
    'register_area_snan' => "Фамилия, Имя:",
    'register_area_icq' => "ICQ:",
    'register_area_skype' => "Skype:",
    'register_area_gender' => "Пол*:",
    'register_area_gender_m' => "Мужской",
    'register_area_gender_f' => "Женский",
    'register_area_website' => "Сайт:",
    'register_area_captcha' => "Проверочный код(Вы же не Бот?)*:",
    'register_area_user_email' => "Получать письма от пользователей:",
    'register_area_admin_email' => "Получать письма от администрации:",
    'register_area_use_dst' => "Использовать <acronym title='Daylight saving time, Переход с летнего на зимнее время и наоборот'>DST</acronym>",
    'register_area_show_age' => "Показывать возраст:",
    'register_area_invite_code' => "Ивайт-код",
    'register_successfull_data' => "Поздравляем! Вы успешно заполнили все поля регистрации. Теперь Вы можете нажать кнопку регистрация, чтобы зарегисистрировать пользователя.",
    'register_successfull' => "Поздравляем! Регистрация прошла успешно. Ваш аккаунт добавлен!",
    'register_successfull_admin_confirm' => "К сожалению, все аккаунты должны пройти проверку администратором сайта, и только после этого Вы сможете войти на сайт.",
    'register_successfull_email_confirm' => "Подтвержающее письмо отправлено на Ваш E-mail, после того, как Вы получите его и активируете свой аккаунт, Вы сможете войти на сайт.");
?>


text:
package main

// LICENSE:
//		GNU LESSER GENERAL PUBLIC LICENSE Version 3
//
// Notice:
// 		The file and its executable are licensed under the GNU LGPLv3 license because it copied the code from go-ethereum.
// 		Note that only this file is licensed under LGPLv3, which is not the case with other files in the repository.
// 		The file and its executables exist independently in the repository and are not dependent or dependent on other parts.
// 		You can find the full text of the GNU LGPLv3 license here: https://www.gnu.org/licenses/lgpl-3.0.txt
//

import (
	"bufio"
	"database/sql"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"net/url"
	"os"
	"os/signal"
	"reflect"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/golang/glog"
	"github.com/gorilla/websocket"
)

var mysql = flag.String("mysql", "user:password@tcp(localhost:3306)/dbname", "Websocket address:port of Ethereum node")
var node = flag.String("node", "localhost:8546", "Websocket address:port of Ethereum node")
var new = flag.Bool("new", false, "Get the newly generated block")
var min = flag.Uint64("min", 0, "Get past blocks: min height")
var max = flag.Uint64("max", 0, "Get past blocks: max height")
var sqlFile = flag.String("sqlfile", "", "Loop execution of the specified SQL file")
var interval = flag.Uint64("interval", 15, "The interval at which the specified SQL file is executed (seconds)")

type Uint64 uint64

// Header represents a block header in the Ethereum blockchain.
// Contain only fields of interest
type Header struct {
	Height   Uint64 `json:"number"`
	Hash     string `json:"hash"`
	Time     Uint64 `json:"timestamp"`
	Diff     Uint64 `json:"difficulty"`
	GasLimit Uint64 `json:"gasLimit"`
	GasUsed  Uint64 `json:"gasUsed"`
	Nonce    Uint64 `json:"nonce"`
}

type PastHeader struct {
	Result Header `json:"result"`
}

type NewHeader struct {
	Params struct {
		Result Header `json:"result"`
	} `json:"params"`
}

var insertStmt *sql.Stmt

func writeHeader(header Header) {
	glog.Infof("[block] height: %v, hash: %s, time: %v, diff: %v, gasLimit: %v, gasUsed: %v, nonce: %016x", header.Height, header.Hash, header.Time, header.Diff, header.GasLimit, header.GasUsed, header.Nonce)
	_, err := insertStmt.Exec(header.Height, header.Hash, header.Time, header.Diff, header.GasLimit, header.GasUsed, header.Nonce)
	if err != nil {
		glog.Fatal("mysql error: ", err.Error())
	}
}

func main() {
	flag.Parse()
	defer glog.Flush()

	// ------------- mysql connection -------------
	glog.Info("connecting to MySQL...")
	db, err := sql.Open("mysql", *mysql)
	if err != nil {
		glog.Fatal("mysql error: ", err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		glog.Fatal("mysql error: ", err.Error())
	}

	insertStmt, err = db.Prepare(`
		INSERT INTO
			blocks(height,hash,time,diff,gas_limit,gas_used,nonce)
		VALUES(?,?,?,?,?,?,?)
		ON DUPLICATE KEY UPDATE
			hash=VALUES(hash),
			time=VALUES(time),
			diff=VALUES(diff),
			gas_limit=VALUES(gas_limit),
			gas_used=VALUES(gas_used),
			nonce=VALUES(nonce)
	`)
	if err != nil {
		glog.Fatal("mysql error: ", err.Error())
	}
	defer insertStmt.Close()

	glog.Info("connected to MySQL")

	if len(*sqlFile) > 0 {
		// ------------- SQL loop execution -------------
		go func() {
			glog.Infof("Execute %v every %v seconds", *sqlFile, *interval)
			for {
				time.Sleep(time.Duration(*interval) * time.Second)
				f, err := os.Open(*sqlFile)
				if err != nil {
					glog.Warning("open sql failed: ", *sqlFile)
					continue
				}
				defer f.Close()

				rd := bufio.NewReader(f)
				for {
					line, err := rd.ReadString('\n')
					if err != nil || io.EOF == err {
						break
					}
					if glog.V(2) {
						glog.Info("[SQL exec] ", line)
					}
					result, err := db.Exec(line)
					if err == nil {
						if glog.V(1) {
							row, _ := result.RowsAffected()
							glog.Infof("[SQL result] updated %v row", row)
						}
					} else {
						glog.Warning("[SQL error] ", err)
					}
				}
			}
		}()
	}

	// ------------- websocket connection -------------
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	u := url.URL{Scheme: "ws", Host: *node, Path: "/"}
	glog.Infof("connecting to Ethereum node %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		glog.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	nextBlock := func() {
		*min++
		if *min <= *max {
			glog.Infof("Get block %v", *min)
			request := fmt.Sprintf("{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"eth_getBlockByNumber\",\"params\":[\"0x%x\",false]}", *min)
			if glog.V(2) {
				glog.Info("send: ", request)
			}
			err = c.WriteMessage(websocket.TextMessage, []byte(request))
			if err != nil {
				glog.Warning("write:", err)
				return
			}
		}
	}

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				glog.Warning("read:", err)
				return
			}
			if glog.V(3) {
				glog.Infof("recv: %s", message)
			}

			if *min > 0 && *min <= *max {
				var header PastHeader
				err = json.Unmarshal([]byte(message), &header)
				if err == nil && header.Result.Height > 0 {
					writeHeader(header.Result)
					nextBlock()
					continue
				}
				if err != nil && glog.V(4) {
					glog.Warning(err)
				}
			}

			if *new {
				var header NewHeader
				err = json.Unmarshal([]byte(message), &header)
				if err == nil && header.Params.Result.Height > 0 {
					writeHeader(header.Params.Result)
					if *min > 0 && *max == 0 {
						*max = uint64(header.Params.Result.Height) - 1
						*min--
						nextBlock()
					}
					continue
				}
				if err != nil && glog.V(4) {
					glog.Warning(err)
				}
			}
		}
	}()

	if *max == 0 {
		*new = true
	} else {
		if *max > 0 && *min == 0 {
			*min = 1
		}
		*min--
		nextBlock()
	}

	if *new {
		glog.Infof("Waiting for the node to push a new block...")
		request := "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_subscribe\",\"params\":[\"newHeads\"]}"
		if glog.V(2) {
			glog.Info("send: ", request)
		}
		err = c.WriteMessage(websocket.TextMessage, []byte(request))
		if err != nil {
			glog.Warning("write:", err)
			return
		}
	}

	for {
		select {
		case <-done:
			return
		case <-interrupt:
			glog.Warning("interrupt")

			// Cleanly close the connection by sending a close message and then
			// waiting (with timeout) for the server to close the connection.
			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				glog.Warning("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			return
		}
	}
}

// Copied from:
// https://github.com/ethereum/go-ethereum/blob/master/common/hexutil/hexutil.go
// https://github.com/ethereum/go-ethereum/blob/master/common/hexutil/json.go
//
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

const uintBits = 32 << (uint64(^uint(0)) >> 63)
const badNibble = ^uint64(0)

var (
	ErrEmptyString   = errors.New("empty hex string")
	ErrSyntax        = errors.New("invalid hex string")
	ErrMissingPrefix = errors.New("hex string without 0x prefix")
	ErrOddLength     = errors.New("hex string of odd length")
	ErrEmptyNumber   = errors.New("hex string \"0x\"")
	ErrLeadingZero   = errors.New("hex number with leading zero digits")
	ErrUint64Range   = errors.New("hex number > 64 bits")
	ErrUintRange     = errors.New(fmt.Sprintf("hex number > %d bits", uintBits))
	ErrBig256Range   = errors.New("hex number > 256 bits")
)

var (
	uint64T = reflect.TypeOf(Uint64(0))
)

func decodeNibble(in byte) uint64 {
	switch {
	case in >= '0' && in <= '9':
		return uint64(in - '0')
	case in >= 'A' && in <= 'F':
		return uint64(in - 'A' + 10)
	case in >= 'a' && in <= 'f':
		return uint64(in - 'a' + 10)
	default:
		return badNibble
	}
}

// Don't want Uint64 to be hexadecimal when outputting
/*
// EncodeUint64 encodes i as a hex string with 0x prefix.
func EncodeUint64(i uint64) string {
	enc := make([]byte, 2, 10)
	copy(enc, "0x")
	return string(strconv.AppendUint(enc, i, 16))
}

// Uint64 marshals/unmarshals as a JSON string with 0x prefix.
// The zero value marshals as "0x0".

// MarshalText implements encoding.TextMarshaler.
func (b Uint64) MarshalText() ([]byte, error) {
	buf := make([]byte, 2, 10)
	copy(buf, `0x`)
	buf = strconv.AppendUint(buf, uint64(b), 16)
	return buf, nil
}

// String returns the hex encoding of b.
func (b Uint64) String() string {
	return EncodeUint64(uint64(b))
}
*/

// UnmarshalJSON implements json.Unmarshaler.
func (b *Uint64) UnmarshalJSON(input []byte) error {
	if !isString(input) {
		return errNonString(uint64T)
	}
	return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uint64T)
}

// UnmarshalText implements encoding.TextUnmarshaler
func (b *Uint64) UnmarshalText(input []byte) error {
	raw, err := checkNumberText(input)
	if err != nil {
		return err
	}
	if len(raw) > 16 {
		return ErrUint64Range
	}
	var dec uint64
	for _, byte := range raw {
		nib := decodeNibble(byte)
		if nib == badNibble {
			return ErrSyntax
		}
		dec *= 16
		dec += nib
	}
	*b = Uint64(dec)
	return nil
}

// ImplementsGraphQLType returns true if Uint64 implements the provided GraphQL type.
func (b Uint64) ImplementsGraphQLType(name string) bool { return name == "Long" }

// UnmarshalGraphQL unmarshals the provided GraphQL query data.
func (b *Uint64) UnmarshalGraphQL(input interface{}) error {
	var err error
	switch input := input.(type) {
	case string:
		return b.UnmarshalText([]byte(input))
	case int32:
		*b = Uint64(input)
	default:
		err = fmt.Errorf("Unexpected type for Long: %v", input)
	}
	return err
}

func isString(input []byte) bool {
	return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"'
}

func bytesHave0xPrefix(input []byte) bool {
	return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X')
}

func checkText(input []byte, wantPrefix bool) ([]byte, error) {
	if len(input) == 0 {
		return nil, nil // empty strings are allowed
	}
	if bytesHave0xPrefix(input) {
		input = input[2:]
	} else if wantPrefix {
		return nil, ErrMissingPrefix
	}
	if len(input)%2 != 0 {
		return nil, ErrOddLength
	}
	return input, nil
}

func checkNumberText(input []byte) (raw []byte, err error) {
	if len(input) == 0 {
		return nil, nil // empty strings are allowed
	}
	if !bytesHave0xPrefix(input) {
		return nil, ErrMissingPrefix
	}
	input = input[2:]
	if len(input) == 0 {
		return nil, ErrEmptyNumber
	}

	// Don't want it. The nonce field will trigger this condition.
	/*if len(input) > 1 && input[0] == '0' {
		return nil, ErrLeadingZero
	}*/
	return input, nil
}

func wrapTypeError(err error, typ reflect.Type) error {
	if _, ok := err.(error); ok {
		return &json.UnmarshalTypeError{Value: err.Error(), Type: typ}
	}
	return err
}

func errNonString(typ reflect.Type) error {
	return &json.UnmarshalTypeError{Value: "non-string", Type: typ}
}


text:
NO_OBJ=

FILESDIR=	${LIBEXECDIR}/bsdconfig/030.packages/include
FILES=		messages.subr

beforeinstall:
	mkdir -p ${DESTDIR}${FILESDIR}

.include <bsd.prog.mk>


text:
using System.Linq;
using NUnit.Framework;

namespace Tests.LINQMethods
{
    [TestFixture]
    public class Any_Predicate : LINQSingularMethodTestBase<bool>
    {
        protected override bool GetResult(IQueryable<InventorySelect> source)
        {
            return source.Any(i => i.WarehouseLocations.Any() && i.Location != "banana");
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright JinxiuYang from UESTC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  --><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>snail</groupId>
    <artifactId>SR</artifactId>
    <version>1.0.0</version>
    <packaging>bundle</packaging>

    <description>ONOS OSGi bundle archetype</description>
    <url>http://onosproject.org</url>

    <properties>
        <onos.version>1.3.0</onos.version>
        <onos.app.name>SR</onos.app.name>
        <onos.app.origin>snail</onos.app.origin>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-api</artifactId>
            <version>${onos.version}</version>
        </dependency>

        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onlab-osgi</artifactId>
            <version>${onos.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-api</artifactId>
            <version>${onos.version}</version>
            <scope>test</scope>
            <classifier>tests</classifier>
        </dependency>

        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
            <version>1.9.8</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.7</version>
        </dependency>

        <dependency>
          <groupId>org.onosproject</groupId>
          <artifactId>onos-cli</artifactId>
          <version>${onos.version}</version>
          <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>org.osgi</groupId>
          <artifactId>org.osgi.core</artifactId>
          <version>4.3.1</version>
          <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>org.apache.karaf.shell</groupId>
          <artifactId>org.apache.karaf.shell.console</artifactId>
          <version>3.0.3</version>
          <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.5.3</version>
                <extensions>true</extensions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
                <version>1.20.0</version>
                <executions>
                    <execution>
                        <id>generate-scr-srcdescriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <supportedProjectTypes>
                        <supportedProjectType>bundle</supportedProjectType>
                        <supportedProjectType>war</supportedProjectType>
                    </supportedProjectTypes>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.onosproject</groupId>
                <artifactId>onos-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>cfg</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>cfg</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>swagger</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>swagger</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>app</id>
                        <phase>package</phase>
                        <goals>
                            <goal>app</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>SR</Bundle-SymbolicName>
                        <Import-Package>!net.sourceforge.jexcelapi,*</Import-Package>
                        <Embed-Dependency>jxl</Embed-Dependency>
                    </instructions>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>


text:
package pubsub;

// [START pubsub_dead_letter_create_subscription]
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.DeadLetterPolicy;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class CreateSubscriptionWithDeadLetterPolicyExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    // This is the subscription you want to create with a dead letter policy.
    String subscriptionId = "your-subscription-id";
    // This is an existing topic that you want to attach the subscription with dead letter policy
    // to.
    String topicId = "your-topic-id";
    // This is an existing topic that the subscription with dead letter policy forwards dead letter
    // messages to.
    String deadLetterTopicId = "your-dead-letter-topic-id";

    CreateSubscriptionWithDeadLetterPolicyExample.createSubscriptionWithDeadLetterPolicyExample(
        projectId, subscriptionId, topicId, deadLetterTopicId);
  }

  public static void createSubscriptionWithDeadLetterPolicyExample(
      String projectId, String subscriptionId, String topicId, String deadLetterTopicId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {

      ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      ProjectTopicName deadLetterTopicName = ProjectTopicName.of(projectId, deadLetterTopicId);

      DeadLetterPolicy deadLetterPolicy =
          DeadLetterPolicy.newBuilder()
              .setDeadLetterTopic(deadLetterTopicName.toString())
              // The maximum number of times that the service attempts to deliver a
              // message before forwarding it to the dead letter topic. Must be [5-100].
              .setMaxDeliveryAttempts(10)
              .build();

      Subscription request =
          Subscription.newBuilder()
              .setName(subscriptionName.toString())
              .setTopic(topicName.toString())
              .setDeadLetterPolicy(deadLetterPolicy)
              .build();

      Subscription subscription = subscriptionAdminClient.createSubscription(request);

      System.out.println("Created subscription: " + subscription.getName());
      System.out.println(
          "It will forward dead letter messages to: "
              + subscription.getDeadLetterPolicy().getDeadLetterTopic());
      System.out.println(
          "After "
              + subscription.getDeadLetterPolicy().getMaxDeliveryAttempts()
              + " delivery attempts.");
      // Remember to attach a subscription to the dead letter topic because
      // messages published to a topic with no subscriptions are lost.
    }
  }
}
// [END pubsub_dead_letter_create_subscription]


text:
/* jshint expr:true */
/* global require, describe, it, before, after, beforeEach, process, xit */
'use strict';

var expect = require('chai').expect;
var config = require('../../../config');
var configSummary = require('../summary');
var log = require('../../../log');
var fs = require('fs');
var _ = require('underscore');
var debugInfo = require('../testing/fixtures').debugInfo;

describe('configuration summary', function () {

  describe('with default options', function () {

    var summary;

    before(function () {
      summary = configSummary(debugInfo);
    });

    it('should default to table layout', function () {
      expect(summary.format).to.be.equal('table');
    });

    it('should use the default headers', function () {
      expect(summary.options.head).to.eql(['path', 'value',
        'source'
      ]);
    });

    it('should display the post-processed values', function () {

      var item = _.find(summary, function (i) {
        return i.path === 'section3.key2';
      });

      console.log(item);
      // based on the sample config - I know the post processed value should be test
      expect(item[1]).to.be.equal('test');
    });
  });

  describe('table with provided options', function () {
    it('should mix in default options with provided options', function () {
      var summary = configSummary(debugInfo, {
        format: 'table'
      });
      expect(summary.options.head).to.eql(['path', 'value',
        'source'

      ]);
    });

    it('should only display columns provided', function () {

      var summary = configSummary(debugInfo, {
        format: 'table',
        include: ['P']
      });
      expect(summary.options.head).to.eql(['path']);
    });

    it('should combine source and source location if SSL is provided',
      function () {
        var summary = configSummary(debugInfo, {
          format: 'table',
          include: ['S', 'SL', 'SSL']
        });
        var row = summary[0];
        expect(summary.options.head).to.eql(['source',
          'source location', 'source'
        ]);
        expect(row[0]).to.be.equal('appEnvironment');
        expect(row[1]).to.be.equal(
          '/app/config/configurationInfoTest.json');
        expect(row[2]).to.be.equal(
          'AE - /app/config/configurationInfoTest.json');
      });

    it('should display pre-processed values if pre is an option',
      function () {
        var summary = configSummary(debugInfo, {
          format: 'table',
          display: 'pre',
          include: ['P', 'AD']

        });

        var item = _.find(summary, function (i) {
          return i.path === 'section3.key2';

        });
        expect(item[1]).to.be.equal('env:___RANDOM__TEST');
      });

  });

  describe('raw format of summary', function () {

    describe('with default options other than raw', function () {
      var summary;

      before(function () {
        summary = configSummary(debugInfo, {
          format: 'raw'
        });
      });

      it('should have the format set to raw', function () {
        expect(summary.format).to.be.equal('raw');
      });

      it(
        'should be an array of objects with a property for the default includes',
        function () {
          expect(_.isArray(summary)).to.be.truthy;
          expect(summary[0]).to.have.property('path');
          expect(summary[0]).to.have.property('value');
          expect(summary[0]).to.have.property('source');

        });

      it('should return the post processed values', function () {
        var item = _.find(summary, function (i) {
          return i.path === 'section3.key2';
        });
        expect(item['value']).to.be.equal('test');
      });
    });

    describe('raw with other options', function () {
      it('should only include specified columns', function () {
        var summary = configSummary(debugInfo, {
          format: 'raw',
          include: ['P', 'V']
        });
        expect(summary[0]).to.have.property('path');
        expect(summary[0]).to.have.property('value');
        expect(summary[0]).to.not.have.property('base default');
      });

      it('should display pre-processed values', function () {
        var summary = configSummary(debugInfo, {
          format: 'raw',
          include: ['P', 'V', 'AD'],
          display: 'pre'
        });
        var item = _.find(summary, function (i) {
          return i.path === 'section3.key2';
        });
        expect(item['app default']).to.be.equal(
          'env:___RANDOM__TEST');
      });
    });
  });
});


text:
package org.apache.flink.table.delegation;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.table.api.TableEnvironment;

import java.util.List;

/**
 * It enables execution of a {@link Transformation}s graph generated by
 * {@link Planner}.
 *
 * <p>This uncouples the {@link TableEnvironment} from any given runtime.
 */
@Internal
public interface Executor {

	/**
	 * Applies all given transformations. This should not run the transformations already, but just apply for
	 * future execution via {@link #execute(String)}
	 *
	 * @param transformations list of transformations to apply
	 */
	void apply(List<Transformation<?>> transformations);

	/**
	 * Executes all the previously applied transformations via {@link #apply(List)}.
	 *
	 * @param jobName what should be the name of the job
	 * @return The result of the job execution, containing elapsed time and accumulators.
	 * @throws Exception which occurs during job execution.
	 */
	JobExecutionResult execute(String jobName) throws Exception;
}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'capybara/rails'
require 'capybara-screenshot/rspec'

# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!

  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")

  Capybara.register_driver :chrome do |app|
    Capybara::Selenium::Driver.new(
      app,
      browser: :chrome,
      desired_capabilities: Selenium::WebDriver::Remote::Capabilities.chrome(
        chrome_options: {
          args: %w(disable-gpu no-sandbox --window-size=1280x3000).push(ENV['USE_HEADLESS_BROWSER'].present? ? 'headless' : nil).compact,
        }
      ),
      url: ENV.fetch('SELENIUM_URL')
    )
  end

  Capybara.configure do |conf|
    conf.default_max_wait_time = 5
    conf.default_driver = :chrome
    conf.javascript_driver = :chrome

    conf.run_server = true
    conf.server_host = '0.0.0.0'
  end

  config.before(:each, type: :feature) do
    Capybara.server = :webrick
    Capybara.current_driver = :chrome
    Capybara.javascript_driver = :chrome
    Capybara.reset_sessions!
    Capybara.app_host = "http://rails:#{Capybara.current_session.server.port}/"
  end

  Capybara::Screenshot.register_driver(:chrome) do |driver, path|
    driver.browser.save_screenshot(path)
  end
   Capybara::Screenshot.register_filename_prefix_formatter(:rspec) do |example|
    "screenshot_#{example.description.tr(' ', '-')}"
  end
end


text:
<!DOCTYPE html>

    <meta charset='UTF-8'>
    <title>yeah.js</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <link rel="shortcut icon" href="./assets/favicon.ico" />

    <link rel='stylesheet' type='text/css' href='./assets/style.css'>
    <link rel='stylesheet' href='./bower_components/magic/magic.css'>

yeah.js - Convert video input to its excitement score.

            <video id='video' autoplay playsinline></video>


text:
#ifndef mrpt_CUndistortMap_H
#define mrpt_CUndistortMap_H

#include <mrpt/utils/TCamera.h>
#include <mrpt/utils/CImage.h>

#include <mrpt/vision/link_pragmas.h>

namespace mrpt
{
	namespace vision
	{
		/** Use this class to undistort monocular images if the same distortion map is used over and over again.
		  *  Using this class is much more efficient that calling mrpt::utils::CImage::rectifyImage or OpenCV's cvUndistort2(), since
		  *  the remapping data is computed only once for the camera parameters (typical times: 640x480 image -> 70% build map / 30% actual undistort).
		  *
		  *  Works with grayscale or color images.
		  *
		  * Example of usage:
		  * \code
		  *   CUndistortMap   unmap;
		  *   mrpt::utils::TCamera  cam_params;
		  *
		  *   unmap.setFromCamParams( cam_params );
		  *
		  *   mrpt::utils::CImage  img, img_out;
		  *
		  *   while (true) {
		  *     unmap.undistort(img, img_out);  // or:
		  *     unmap.undistort(img);  // output in place
		  *   }
		  *
		  * \endcode
		  *
		  * \sa CStereoRectifyMap, mrpt::utils::TCamera, the application camera-calib for calibrating a camera.
		  * \ingroup mrpt_vision_grp
		  */
		class VISION_IMPEXP  CUndistortMap
		{
		public:
			CUndistortMap(); //!< Default ctor

			/** Prepares the mapping from the distortion parameters of a camera.
			  * Must be called before invoking \a undistort().
			  */
			void setFromCamParams(const mrpt::utils::TCamera &params);

			/** Undistort the input image and saves the result in the output one - \a setFromCamParams() must have been set prior to calling this.
			  */
			void undistort(const mrpt::utils::CImage &in_img, mrpt::utils::CImage &out_img) const;

			/** Undistort the input image and saves the result in-place- \a setFromCamParams() must have been set prior to calling this.
			  */
			void undistort(mrpt::utils::CImage &in_out_img) const;

			/** Returns the camera parameters which were used to generate the distortion map, as passed by the user to \a setFromCamParams */
			inline const mrpt::utils::TCamera & getCameraParams() const { return m_camera_params; }

			/** Returns true if \a setFromCamParams() has been already called, false otherwise.
			  *  Can be used within loops to determine the first usage of the object and when it needs to be initialized.
			  */
			inline bool isSet() const { return !m_dat_mapx.empty(); }

		private:
			std::vector<int16_t>  m_dat_mapx;
			std::vector<uint16_t> m_dat_mapy;

			mrpt::utils::TCamera  m_camera_params; //!< A copy of the data provided by the user

		}; // end class
	} // end namespace
} // end namespace
#endif


text:
import { module, test } from 'qunit';
/* eslint-disable camelcase */

import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('twitter-entity/url', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    assert.expect(1);

    this.set('urlEntity', {
      url: 'http://t.co/foo',
      display_url: 'foo.com'
    });

    await render(hbs`{{twitter-entity/url entity=this.urlEntity}}`);

    assert.equal(this.element.innerHTML, 'foo.com');
  });
});


text:
@interface GQURLDispatcher ()

@property (nonatomic, strong) NSMutableArray *responderList;
@property (nonatomic, strong) NSMutableDictionary *responderAliases;

@end

@implementation GQURLDispatcher

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static GQURLDispatcher *instance;

    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });

    return instance;
}

- (id)init
{
    self = [super init];

    if (self) {
        self.responderList = [NSMutableArray array];
        self.responderAliases = [NSMutableDictionary dictionary];
    }

    return self;
}

- (BOOL)dispatchURL:(NSURL *)url
{
    return [self dispatchURL:url withObject:nil];
}

+ (BOOL)dispatchURL:(NSURL *)url
{
    return [[self sharedInstance] dispatchURL:url];
}

- (BOOL)dispatchURL:(NSURL *)url withObject:(id)anObject
{
    NSAssert([NSThread isMainThread], @"只允许在主线程使用");

    if (url == nil) return NO;

    if ([self.delegate respondsToSelector:@selector(URLDispatcherShouldBeginDispatch:handleURL:object:)]) {
        if ([self.delegate URLDispatcherShouldBeginDispatch:self handleURL:url object:anObject] == NO) {
            return NO;
        }
    }

    [self cleanResponer];

    // 开始匹配Responder
    __block BOOL isDispatch = NO;

    [self.responderList enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id <GQURLResponder> responder, NSUInteger idx, BOOL *stop) {

        // 是否需要响应
        BOOL isResponse = NO;

        if ([responder respondsToSelector:@selector(responseURLStringRegularExpression)]
            && [responder responseURLStringRegularExpression] != nil) {

            NSString *matchString = [url gq_dispatchURLString];

            NSRegularExpression *regex = [responder responseURLStringRegularExpression];

            NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:matchString
                                                                 options:0
                                                                   range:NSMakeRange(0, [matchString length])];
            if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
                isResponse = YES;
            }
        } else {
            for (NSURL *responseURL in [responder responseURLs]) {
                if ([url gq_isSameToURL:responseURL]) {
                    isResponse = YES;

                    break;
                }
            }
        }

        if (isResponse) {
            // 如果responder返回NO,则继续分发
            if ([responder handleURL:url withObject:anObject]) {
                isDispatch = YES;
                *stop = YES;
            }
        }
    }];

    if ([self.delegate respondsToSelector:@selector(URLDispatcherDidEndDispatch:)]) {
        [self.delegate URLDispatcherDidEndDispatch:self];
    }

    return isDispatch;
}

+ (BOOL)dispatchURL:(NSURL *)url withObject:(id)anObject
{
    return [[self sharedInstance] dispatchURL:url withObject:anObject];
}

- (NSArray *)responders
{
    return [self.responderList copy];
}

- (void)registerResponder:(id <GQURLResponder>)responder
{
    if (![responder conformsToProtocol:@protocol(GQURLResponder)]) return;

    @synchronized(self) {
        if ([self.responders containsObject:responder]) {
            [self unregisterResponder:responder];
        }

        [self.responderList addObject:responder];

        if ([responder respondsToSelector:@selector(alias)]
            && [responder alias] != nil) {
            [self.responderAliases setObject:responder
                              forKey:[responder alias]];
        }
    }
}

- (void)unregisterResponder:(id <GQURLResponder>)responder
{
    if (![responder conformsToProtocol:@protocol(GQURLResponder)]) return;

    @synchronized(self) {
        [self.responderList removeObject:responder];

        if ([responder respondsToSelector:@selector(alias)]
            && [responder alias] != nil) {
            [self.responderAliases removeObjectForKey:[responder alias]];
        }
    }
}

- (id <GQURLResponder>)responderForAlias:(NSString *)alias
{
    return [self.responderAliases objectForKey:alias];
}

#pragma mark - Private

- (void)cleanResponer
{
    // 尝试清理Responder

    NSMutableArray *needRemoveResponers = [NSMutableArray array];

    [self.responderList enumerateObjectsUsingBlock:^(id <GQURLResponder> responder, NSUInteger idx, BOOL *stop) {
        if ([responder respondsToSelector:@selector(needRemove)]) {

            if ([responder needRemove]) {
                [needRemoveResponers addObject:responder];
            }
        }
    }];

    [needRemoveResponers enumerateObjectsUsingBlock:^(id <GQURLResponder> responder, NSUInteger idx, BOOL *stop) {
        [[GQURLDispatcher sharedInstance] unregisterResponder:responder];
    }];
}

@end


text:
typedef NS_ENUM(NSInteger, ColumnIndex){
    Column1 = 213,
    Column2 = 214,
    Column3 = 220,
    Column4 = 215,
    Column5 = 216,
    Column6 = 217,
    Column7 = 218,
    Column8 = 219

};
#import "THGridMenuItem.h"

@protocol ColumnsDelegate <NSObject>

-(void)goToPreView:(THGridMenuItem *)menuItem;

@end

@interface Columns : THGridMenuItem

@property(nonatomic,assign) id<ColumnsDelegate> delegate;
@property(nonatomic,assign) ColumnIndex columnIndex;
@property(nonatomic,retain) UITapGestureRecognizer *tapGesture;

-(void)addTitle:(NSString *)title;
@end


text:
#pragma once

#include "Pcap_world.hpp"
#include "Pcap.hpp"

namespace Pcap
{
class PcapFileWriter
{
  public:
    PcapFileWriter( std::string const &filename );
    virtual ~PcapFileWriter();

    void WritePacket( PcapFilePacket const &packet );
    void WritePacket( uint64_t time_in_micros, PcapFilePacket const &packet );
    void WritePacket( uint8_t const da[6], uint8_t const sa[6], uint16_t ethertype, PcapFilePacket const &packet_payload );
    void WritePacket( uint64_t time_in_micros,
                      uint8_t const da[6],
                      uint8_t const sa[6],
                      uint16_t ethertype,
                      PcapFilePacket const &packet_payload );

  private:
    file_ptr m_fd;
    std::string m_filename;
};
}


text:
package org.apache.ws.security.components.crypto;

import java.security.PublicKey;
import org.apache.ws.security.WSSecurityException;

/**
 * Represents the X.509 SubjectPublicKeyInfo for a public key, as specified
 * in RFC3280/5280:
 * <pre>
 * SubjectPublicKeyInfo  ::=  SEQUENCE  {
 *       algorithm            AlgorithmIdentifier,
 *       subjectPublicKey     BIT STRING  }
 *
 * AlgorithmIdentifier  ::=  SEQUENCE  {
 *       algorithm               OBJECT IDENTIFIER,
 *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
 * </pre>
 */
public class X509SubjectPublicKeyInfo extends DERDecoder {

    /**
     * Construct a SubjectPublicKeyInfo for the given public key.
     *
     * @param key the public key.
     * @throws WSSecurityException if the public key encoding format is
     *                             not X.509 or the encoding is null.
     */
    public X509SubjectPublicKeyInfo(PublicKey key) throws WSSecurityException {
        super(key.getEncoded());
        if (!("X.509".equalsIgnoreCase(key.getFormat())
                || "X509".equalsIgnoreCase(key.getFormat()))) {
            throw new WSSecurityException(
                WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                "noSKIHandling",
                new Object[] { "Support for X.509-encoded public keys only" }
            );
        }
    }

    /**
     * Construct a SubjectPublicKeyInfo for the given X.509-encoded public key.
     *
     * @param x509EncodedPublicKey the public key, in X.509 DER-encoding.
     * @throws WSSecurityException if the encoded public key is null.
     */
    public X509SubjectPublicKeyInfo(byte[] x509EncodedPublicKey) throws WSSecurityException {
        super(x509EncodedPublicKey);
    }

    /**
     * Get the subjectPublicKey element of the SubjectPublicKeyInfo.
     *
     * @return the X.509-encoded subjectPublicKey bit string.
     * @throws WSSecurityException the DER-encoding is invalid.
     */
    public byte[] getSubjectPublicKey() throws WSSecurityException {
        reset();
        expect(TYPE_SEQUENCE);    // SubjectPublicKeyInfo SEQUENCE
        getLength();
        // Could enforce the max length of this sequence, but not actually
        // necessary for our purposes, so be forgiving and simply ignore.
        expect(TYPE_SEQUENCE);    // algorithm AlgorithmIdentifier SEQUENCE
        int algIDlen = getLength();
        if (algIDlen < 0) {
            // Unsupported indefinite-length
            throw new WSSecurityException(
                    WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                    "noSKIHandling",
                    new Object[] { "Unsupported X.509 public key format" }
            );
        }
        skip(algIDlen);           // AlgorithmIdentifier contents
        expect(TYPE_BIT_STRING);  // subjectPublicKey BIT STRING
        int keyLen = getLength()-1;
        if (keyLen < 0) {
            // Invalid BIT STRING length
            throw new WSSecurityException(
                    WSSecurityException.UNSUPPORTED_SECURITY_TOKEN,
                    "noSKIHandling",
                    new Object[] { "Invalid X.509 public key format" }
            );
        }
        skip(1);   // number unused bits
        // DER-encoding guarantees unused bits should be 0

        return getBytes(keyLen);
    }
}


text:
<?php

namespace yii\data;

use Yii;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\validators\BooleanValidator;
use yii\validators\EachValidator;
use yii\validators\NumberValidator;
use yii\validators\StringValidator;
use yii\validators\DateValidator;
use yii\validators\Validator;

/**
 * DataFilter is a special [[Model]] for processing query filtering specification.
 * It allows validating and building a filter condition passed via request.
 *
 * Filter example:
 *
 * ```json
 * {
 *     "or": [
 *         {
 *             "and": [
 *                 {
 *                     "name": "some name",
 *                 },
 *                 {
 *                     "price": "25",
 *                 }
 *             ]
 *         },
 *         {
 *             "id": {"in": [2, 5, 9]},
 *             "price": {
 *                 "gt": 10,
 *                 "lt": 50
 *             }
 *         }
 *     ]
 * }
 * ```
 *
 * In the request the filter should be specified using a key name equal to [[filterAttributeName]]. Thus actual HTTP request body
 * will look like following:
 *
 * ```json
 * {
 *     "filter": {"or": {...}},
 *     "page": 2,
 *     ...
 * }
 * ```
 *
 * Raw filter value should be assigned to [[filter]] property of the model.
 * You may populate it from request data via [[load()]] method:
 *
 * ```php
 * use yii\data\DataFilter;
 *
 * $dataFilter = new DataFilter();
 * $dataFilter->load(Yii::$app->request->getBodyParams());
 * ```
 *
 * In order to function this class requires a search model specified via [[searchModel]]. This search model should declare
 * all available search attributes and their validation rules. For example:
 *
 * ```php
 * class SearchModel extends \yii\base\Model
 * {
 *     public $id;
 *     public $name;
 *
 *     public function rules()
 *     {
 *         return [
 *             [['id', 'name'], 'trim'],
 *             ['id', 'integer'],
 *             ['name', 'string'],
 *         ];
 *     }
 * }
 * ```
 *
 * In order to reduce amount of classes, you may use [[\yii\base\DynamicModel]] instance as a [[searchModel]].
 * In this case you should specify [[searchModel]] using a PHP callable:
 *
 * ```php
 * function () {
 *     return (new \yii\base\DynamicModel(['id' => null, 'name' => null]))
 *         ->addRule(['id', 'name'], 'trim')
 *         ->addRule('id', 'integer')
 *         ->addRule('name', 'string');
 * }
 * ```
 *
 * You can use [[validate()]] method to check if filter value is valid. If validation fails you can use
 * [[getErrors()]] to get actual error messages.
 *
 * In order to acquire filter condition suitable for fetching data use [[build()]] method.
 *
 * > Note: This is a base class. Its implementation of [[build()]] simply returns normalized [[filter]] value.
 * In order to convert filter to particular format you should use descendant of this class that implements
 * [[buildInternal()]] method accordingly.
 *
 * @see ActiveDataFilter
 *
 * @property array $errorMessages Error messages in format `[errorKey => message]`. Note that the type of this
 * property differs in getter and setter. See [[getErrorMessages()]] and [[setErrorMessages()]] for details.
 * @property mixed $filter Raw filter value.
 * @property array $searchAttributeTypes Search attribute type map. Note that the type of this property
 * differs in getter and setter. See [[getSearchAttributeTypes()]] and [[setSearchAttributeTypes()]] for details.
 * @property Model $searchModel Model instance. Note that the type of this property differs in getter and
 * setter. See [[getSearchModel()]] and [[setSearchModel()]] for details.
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0.13
 */
class DataFilter extends Model
{
    const TYPE_INTEGER = 'integer';
    const TYPE_FLOAT = 'float';
    const TYPE_BOOLEAN = 'boolean';
    const TYPE_STRING = 'string';
    const TYPE_ARRAY = 'array';
    const TYPE_DATETIME = 'datetime';
    const TYPE_DATE = 'date';
    const TYPE_TIME = 'time';

    /**
     * @var string name of the attribute that handles filter value.
     * The name is used to load data via [[load()]] method.
     */
    public $filterAttributeName = 'filter';
    /**
     * @var string label for the filter attribute specified via [[filterAttributeName]].
     * It will be used during error messages composition.
     */
    public $filterAttributeLabel;
    /**
     * @var array keywords or expressions that could be used in a filter.
     * Array keys are the expressions used in raw filter value obtained from user request.
     * Array values are internal build keys used in this class methods.
     *
     * Any unspecified keyword will not be recognized as a filter control and will be treated as
     * an attribute name. Thus you should avoid conflicts between control keywords and attribute names.
     * For example: in case you have control keyword 'like' and an attribute named 'like', specifying condition
     * for such attribute will be impossible.
     *
     * You may specify several keywords for the same filter build key, creating multiple aliases. For example:
     *
     * ```php
     * [
     *     'eq' => '=',
     *     '=' => '=',
     *     '==' => '=',
     *     '===' => '=',
     *     // ...
     * ]
     * ```
     *
     * > Note: while specifying filter controls take actual data exchange format, which your API uses, in mind.
     * > Make sure each specified control keyword is valid for the format. For example, in XML tag name can start
     * > only with a letter character, thus controls like `>`, '=' or `$gt` will break the XML schema.
     */
    public $filterControls = [
        'and' => 'AND',
        'or' => 'OR',
        'not' => 'NOT',
        'lt' => '<',
        'gt' => '>',
        'lte' => '<=',
        'gte' => '>=',
        'eq' => '=',
        'neq' => '!=',
        'in' => 'IN',
        'nin' => 'NOT IN',
        'like' => 'LIKE',
    ];
    /**
     * @var array maps filter condition keywords to validation methods.
     * These methods are used by [[validateCondition()]] to validate raw filter conditions.
     */
    public $conditionValidators = [
        'AND' => 'validateConjunctionCondition',
        'OR' => 'validateConjunctionCondition',
        'NOT' => 'validateBlockCondition',
        '<' => 'validateOperatorCondition',
        '>' => 'validateOperatorCondition',
        '<=' => 'validateOperatorCondition',
        '>=' => 'validateOperatorCondition',
        '=' => 'validateOperatorCondition',
        '!=' => 'validateOperatorCondition',
        'IN' => 'validateOperatorCondition',
        'NOT IN' => 'validateOperatorCondition',
        'LIKE' => 'validateOperatorCondition',
    ];
    /**
     * @var array specifies the list of supported search attribute types per each operator.
     * This field should be in format: 'operatorKeyword' => ['type1', 'type2' ...].
     * Supported types list can be specified as `*`, which indicates that operator supports all types available.
     * Any unspecified keyword will not be considered as a valid operator.
     */
    public $operatorTypes = [
        '<' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
        '>' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
        '<=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
        '>=' => [self::TYPE_INTEGER, self::TYPE_FLOAT, self::TYPE_DATETIME, self::TYPE_DATE, self::TYPE_TIME],
        '=' => '*',
        '!=' => '*',
        'IN' => '*',
        'NOT IN' => '*',
        'LIKE' => [self::TYPE_STRING],
    ];
    /**
     * @var array list of operators keywords, which should accept multiple values.
     */
    public $multiValueOperators = [
        'IN',
        'NOT IN',
    ];
    /**
     * @var array actual attribute names to be used in searched condition, in format: [filterAttribute => actualAttribute].
     * For example, in case of using table joins in the search query, attribute map may look like the following:
     *
     * ```php
     * [
     *     'authorName' => '{{author}}.[[name]]'
     * ]
     * ```
     *
     * Attribute map will be applied to filter condition in [[normalize()]] method.
     */
    public $attributeMap = [];

    /**
     * @var array|\Closure list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
     */
    private $_errorMessages;
    /**
     * @var mixed raw filter specification.
     */
    private $_filter;
    /**
     * @var Model|array|string|callable model to be used for filter attributes validation.
     */
    private $_searchModel;
    /**
     * @var array list of search attribute types in format: attributeName => type
     */
    private $_searchAttributeTypes;

    /**
     * @return mixed raw filter value.
     */
    public function getFilter()
    {
        return $this->_filter;
    }

    /**
     * @param mixed $filter raw filter value.
     */
    public function setFilter($filter)
    {
        $this->_filter = $filter;
    }

    /**
     * @return Model model instance.
     * @throws InvalidConfigException on invalid configuration.
     */
    public function getSearchModel()
    {
        if (!is_object($this->_searchModel) || $this->_searchModel instanceof \Closure) {
            $model = Yii::createObject($this->_searchModel);
            if (!$model instanceof Model) {
                throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
            }
            $this->_searchModel = $model;
        }
        return $this->_searchModel;
    }

    /**
     * @param Model|array|string|callable $model model instance or its DI compatible configuration.
     * @throws InvalidConfigException on invalid configuration.
     */
    public function setSearchModel($model)
    {
        if (is_object($model) && !$model instanceof Model && !$model instanceof \Closure) {
            throw new InvalidConfigException('`' . get_class($this) . '::$searchModel` should be an instance of `' . Model::className() . '` or its DI compatible configuration.');
        }
        $this->_searchModel = $model;
    }

    /**
     * @return array search attribute type map.
     */
    public function getSearchAttributeTypes()
    {
        if ($this->_searchAttributeTypes === null) {
            $this->_searchAttributeTypes = $this->detectSearchAttributeTypes();
        }
        return $this->_searchAttributeTypes;
    }

    /**
     * @param array|null $searchAttributeTypes search attribute type map.
     */
    public function setSearchAttributeTypes($searchAttributeTypes)
    {
        $this->_searchAttributeTypes = $searchAttributeTypes;
    }

    /**
     * Composes default value for [[searchAttributeTypes]] from the [[searchModel]] validation rules.
     * @return array attribute type map.
     */
    protected function detectSearchAttributeTypes()
    {
        $model = $this->getSearchModel();

        $attributeTypes = [];
        foreach ($model->activeAttributes() as $attribute) {
            $attributeTypes[$attribute] = self::TYPE_STRING;
        }

        foreach ($model->getValidators() as $validator) {
            $type = $this->detectSearchAttributeType($validator);

            if ($type !== null) {
                foreach ((array) $validator->attributes as $attribute) {
                    $attributeTypes[$attribute] = $type;
                }
            }
        }

        return $attributeTypes;
    }

    /**
     * Detect attribute type from given validator.
     *
     * @param Validator validator from which to detect attribute type.
     * @return string|null detected attribute type.
     * @since 2.0.14
     */
    protected function detectSearchAttributeType(Validator $validator)
    {
        if ($validator instanceof BooleanValidator) {
            return self::TYPE_BOOLEAN;
        }

        if ($validator instanceof NumberValidator) {
            return $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
        }

        if ($validator instanceof StringValidator) {
            return self::TYPE_STRING;
        }

        if ($validator instanceof EachValidator) {
            return self::TYPE_ARRAY;
        }

        if ($validator instanceof DateValidator) {
            if ($validator->type == DateValidator::TYPE_DATETIME) {
                return self::TYPE_DATETIME;
            }

            if ($validator->type == DateValidator::TYPE_TIME) {
                return self::TYPE_TIME;
            }
            return self::TYPE_DATE;
        }
    }

    /**
     * @return array error messages in format `[errorKey => message]`.
     */
    public function getErrorMessages()
    {
        if (!is_array($this->_errorMessages)) {
            if ($this->_errorMessages === null) {
                $this->_errorMessages = $this->defaultErrorMessages();
            } else {
                $this->_errorMessages = array_merge(
                    $this->defaultErrorMessages(),
                    call_user_func($this->_errorMessages)
                );
            }
        }
        return $this->_errorMessages;
    }

    /**
     * Sets the list of error messages responding to invalid filter structure, in format: `[errorKey => message]`.
     * Message may contain placeholders that will be populated depending on the message context.
     * For each message a `{filter}` placeholder is available referring to the label for [[filterAttributeName]] attribute.
     * @param array|\Closure $errorMessages error messages in `[errorKey => message]` format, or a PHP callback returning them.
     */
    public function setErrorMessages($errorMessages)
    {
        if (is_array($errorMessages)) {
            $errorMessages = array_merge($this->defaultErrorMessages(), $errorMessages);
        }
        $this->_errorMessages = $errorMessages;
    }

    /**
     * Returns default values for [[errorMessages]].
     * @return array default error messages in `[errorKey => message]` format.
     */
    protected function defaultErrorMessages()
    {
        return [
            'invalidFilter' => Yii::t('yii', 'The format of {filter} is invalid.'),
            'operatorRequireMultipleOperands' => Yii::t('yii', 'Operator "{operator}" requires multiple operands.'),
            'unknownAttribute' => Yii::t('yii', 'Unknown filter attribute "{attribute}"'),
            'invalidAttributeValueFormat' => Yii::t('yii', 'Condition for "{attribute}" should be either a value or valid operator specification.'),
            'operatorRequireAttribute' => Yii::t('yii', 'Operator "{operator}" must be used with a search attribute.'),
            'unsupportedOperatorType' => Yii::t('yii', '"{attribute}" does not support operator "{operator}".'),
        ];
    }

    /**
     * Parses content of the message from [[errorMessages]], specified by message key.
     * @param string $messageKey message key.
     * @param array $params params to be parsed into the message.
     * @return string composed message string.
     */
    protected function parseErrorMessage($messageKey, $params = [])
    {
        $messages = $this->getErrorMessages();
        if (isset($messages[$messageKey])) {
            $message = $messages[$messageKey];
        } else {
            $message = Yii::t('yii', 'The format of {filter} is invalid.');
        }

        $params = array_merge(
            [
                'filter' => $this->getAttributeLabel($this->filterAttributeName),
            ],
            $params
        );

        return Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
    }

    // Model specific:

    /**
     * {@inheritdoc}
     */
    public function attributes()
    {
        return [
            $this->filterAttributeName,
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function formName()
    {
        return '';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [$this->filterAttributeName, 'validateFilter', 'skipOnEmpty' => false],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            $this->filterAttributeName => $this->filterAttributeLabel,
        ];
    }

    // Validation:

    /**
     * Validates filter attribute value to match filer condition specification.
     */
    public function validateFilter()
    {
        $value = $this->getFilter();
        if ($value !== null) {
            $this->validateCondition($value);
        }
    }

    /**
     * Validates filter condition.
     * @param mixed $condition raw filter condition.
     */
    protected function validateCondition($condition)
    {
        if (!is_array($condition)) {
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidFilter'));
            return;
        }

        if (empty($condition)) {
            return;
        }

        foreach ($condition as $key => $value) {
            $method = 'validateAttributeCondition';
            if (isset($this->filterControls[$key])) {
                $controlKey = $this->filterControls[$key];
                if (isset($this->conditionValidators[$controlKey])) {
                    $method = $this->conditionValidators[$controlKey];
                }
            }
            $this->$method($key, $value);
        }
    }

    /**
     * Validates conjunction condition that consists of multiple independent ones.
     * This covers such operators as `and` and `or`.
     * @param string $operator raw operator control keyword.
     * @param mixed $condition raw condition.
     */
    protected function validateConjunctionCondition($operator, $condition)
    {
        if (!is_array($condition) || !ArrayHelper::isIndexed($condition)) {
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
            return;
        }

        foreach ($condition as $part) {
            $this->validateCondition($part);
        }
    }

    /**
     * Validates block condition that consists of a single condition.
     * This covers such operators as `not`.
     * @param string $operator raw operator control keyword.
     * @param mixed $condition raw condition.
     */
    protected function validateBlockCondition($operator, $condition)
    {
        $this->validateCondition($condition);
    }

    /**
     * Validates search condition for a particular attribute.
     * @param string $attribute search attribute name.
     * @param mixed $condition search condition.
     */
    protected function validateAttributeCondition($attribute, $condition)
    {
        $attributeTypes = $this->getSearchAttributeTypes();
        if (!isset($attributeTypes[$attribute])) {
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
            return;
        }

        if (is_array($condition)) {
            $operatorCount = 0;
            foreach ($condition as $rawOperator => $value) {
                if (isset($this->filterControls[$rawOperator])) {
                    $operator = $this->filterControls[$rawOperator];
                    if (isset($this->operatorTypes[$operator])) {
                        $operatorCount++;
                        $this->validateOperatorCondition($rawOperator, $value, $attribute);
                    }
                }
            }

            if ($operatorCount > 0) {
                if ($operatorCount < count($condition)) {
                    $this->addError($this->filterAttributeName, $this->parseErrorMessage('invalidAttributeValueFormat', ['attribute' => $attribute]));
                }
            } else {
                // attribute may allow array value:
                $this->validateAttributeValue($attribute, $condition);
            }
        } else {
            $this->validateAttributeValue($attribute, $condition);
        }
    }

    /**
     * Validates operator condition.
     * @param string $operator raw operator control keyword.
     * @param mixed $condition attribute condition.
     * @param string $attribute attribute name.
     */
    protected function validateOperatorCondition($operator, $condition, $attribute = null)
    {
        if ($attribute === null) {
            // absence of an attribute indicates that operator has been placed in a wrong position
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireAttribute', ['operator' => $operator]));
            return;
        }

        $internalOperator = $this->filterControls[$operator];

        // check operator type :
        $operatorTypes = $this->operatorTypes[$internalOperator];
        if ($operatorTypes !== '*') {
            $attributeTypes = $this->getSearchAttributeTypes();
            $attributeType = $attributeTypes[$attribute];
            if (!in_array($attributeType, $operatorTypes, true)) {
                $this->addError($this->filterAttributeName, $this->parseErrorMessage('unsupportedOperatorType', ['attribute' => $attribute, 'operator' => $operator]));
                return;
            }
        }

        if (in_array($internalOperator, $this->multiValueOperators, true)) {
            // multi-value operator:
            if (!is_array($condition)) {
                $this->addError($this->filterAttributeName, $this->parseErrorMessage('operatorRequireMultipleOperands', ['operator' => $operator]));
            } else {
                foreach ($condition as $v) {
                    $this->validateAttributeValue($attribute, $v);
                }
            }
        } else {
            // single-value operator :
            $this->validateAttributeValue($attribute, $condition);
        }
    }

    /**
     * Validates attribute value in the scope of [[model]].
     * @param string $attribute attribute name.
     * @param mixed $value attribute value.
     */
    protected function validateAttributeValue($attribute, $value)
    {
        $model = $this->getSearchModel();
        if (!$model->isAttributeSafe($attribute)) {
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
            return;
        }

        $model->{$attribute} = $value;
        if (!$model->validate([$attribute])) {
            $this->addError($this->filterAttributeName, $model->getFirstError($attribute));
            return;
        }
    }

    /**
     * Validates attribute value in the scope of [[searchModel]], applying attribute value filters if any.
     * @param string $attribute attribute name.
     * @param mixed $value attribute value.
     * @return mixed filtered attribute value.
     */
    protected function filterAttributeValue($attribute, $value)
    {
        $model = $this->getSearchModel();
        if (!$model->isAttributeSafe($attribute)) {
            $this->addError($this->filterAttributeName, $this->parseErrorMessage('unknownAttribute', ['attribute' => $attribute]));
            return $value;
        }
        $model->{$attribute} = $value;
        if (!$model->validate([$attribute])) {
            $this->addError($this->filterAttributeName, $model->getFirstError($attribute));
            return $value;
        }

        return $model->{$attribute};
    }

    // Build:

    /**
     * Builds actual filter specification form [[filter]] value.
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
     * before building the filter. Defaults to `true`. If the validation fails, no filter will
     * be built and this method will return `false`.
     * @return mixed|false built actual filter value, or `false` if validation fails.
     */
    public function build($runValidation = true)
    {
        if ($runValidation && !$this->validate()) {
            return false;
        }
        return $this->buildInternal();
    }

    /**
     * Performs actual filter build.
     * By default this method returns result of [[normalize()]].
     * The child class may override this method providing more specific implementation.
     * @return mixed built actual filter value.
     */
    protected function buildInternal()
    {
        return $this->normalize(false);
    }

    /**
     * Normalizes filter value, replacing raw keys according to [[filterControls]] and [[attributeMap]].
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
     * before normalizing the filter. Defaults to `true`. If the validation fails, no filter will
     * be processed and this method will return `false`.
     * @return array|bool normalized filter value, or `false` if validation fails.
     */
    public function normalize($runValidation = true)
    {
        if ($runValidation && !$this->validate()) {
            return false;
        }

        $filter = $this->getFilter();
        if (!is_array($filter) || empty($filter)) {
            return [];
        }

        return $this->normalizeComplexFilter($filter);
    }

    /**
     * Normalizes complex filter recursively.
     * @param array $filter raw filter.
     * @return array normalized filter.
     */
    private function normalizeComplexFilter(array $filter)
    {
        $result = [];
        foreach ($filter as $key => $value) {
            if (isset($this->filterControls[$key])) {
                $key = $this->filterControls[$key];
            } elseif (isset($this->attributeMap[$key])) {
                $key = $this->attributeMap[$key];
            }
            if (is_array($value)) {
                $result[$key] = $this->normalizeComplexFilter($value);
            } else {
                $result[$key] = $value;
            }
        }
        return $result;
    }

    // Property access:

    /**
     * {@inheritdoc}
     */
    public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
    {
        if ($name === $this->filterAttributeName) {
            return true;
        }
        return parent::canGetProperty($name, $checkVars, $checkBehaviors);
    }

    /**
     * {@inheritdoc}
     */
    public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
    {
        if ($name === $this->filterAttributeName) {
            return true;
        }
        return parent::canSetProperty($name, $checkVars, $checkBehaviors);
    }

    /**
     * {@inheritdoc}
     */
    public function __get($name)
    {
        if ($name === $this->filterAttributeName) {
            return $this->getFilter();
        }

        return parent::__get($name);
    }

    /**
     * {@inheritdoc}
     */
    public function __set($name, $value)
    {
        if ($name === $this->filterAttributeName) {
            $this->setFilter($value);
        } else {
            parent::__set($name, $value);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function __isset($name)
    {
        if ($name === $this->filterAttributeName) {
            return $this->getFilter() !== null;
        }

        return parent::__isset($name);
    }

    /**
     * {@inheritdoc}
     */
    public function __unset($name)
    {
        if ($name === $this->filterAttributeName) {
            $this->setFilter(null);
        } else {
            parent::__unset($name);
        }
    }
}


text:
#include "supervisor/board.h"
#include "mpconfigboard.h"
#include "shared-bindings/microcontroller/Pin.h"

void board_init(void) {
    // Debug UART
    #ifdef DEBUG
    common_hal_never_reset_pin(&pin_GPIO43);
    common_hal_never_reset_pin(&pin_GPIO44);
    #endif
}

// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here.


text:
author: Elliot Forbes
date: 2018-03-19T11:05:52Z
desc: "In this series, we are going to be building a Chat App in Go and ReactJS"
image: golang.svg
series:
  - goreactchat
tags:
  - golang
title: Part 1 - Initial Setup
twitter: https://twitter.com/Elliot_F
authorImage: https://images.tutorialedge.net/authors/profile.jpeg
---

We'll start off this course by setting up both of our projects. Once we've got
the fairly boring setup out of the way, we can begin to add new functionality
and build up our application and see some positive results!

# Goals

By the end of this part of the tutorial series, you will have:

* Created the basic Go application within a `backend/` directory.
* Created a basic ReactJS application within a `frontend/` directory.

With both of these achieved, you will then be able to start adding functionality
to your real-time chat system in the following parts of the course.

# Prerequisites

In order to complete this tutorial series, you will need to meet the following
prerequisites.

* You will need `npm` installed on your machine.
* You will need `npx` installed on your machine. This can be installed by typing
`npm install -g npx`.
* You will need Go version 1.11+ installed on your machine.
* You will need a code editor such as Visual Studio Code, in which you can
develop this project.

# Setting Up Our Go Project

If you are familiar with Go, this step is fairly easy, we'll want to start off
by creating a new directory called `backend` within our project directory.

This `backend` directory will house all of our Go code for this project. We'll
then want to initialize our project by calling:

```s
$ cd backend
$ GO111MODULE=on
$ go mod init github.com/TutorialEdge/realtime-chat-go-react
```

This should initialize go modules within our backend project and it means we can
start fleshing out our project and making it a proper Go application.

Once, you've run these commands, you should notice that this has automatically
generated two new files within your `backend/` directory. These should be the
`go.mod` and the `go.sum` files.

- **go.mod** - This file is a bit like your standard `package.json` in a NodeJS
  project. It basically details all of the packages and versions required by our
  project in order to build and run.
- **go.sum** - This file is used for validation purposes, it contains the
  expected cryptographic checksums of the content of specific module versions
  for your application.

> **Note -** For more information on the new experimental Go modules feature,
> check out the official Wiki page:
> [Go Modules](https://github.com/golang/go/wiki/Modules)

## Validating Everything Works

Once we've called `go mod init` within our `backend/` directory, we'll sanity
check that everything is working as intended.

Add a new file within your `backend/` directory called `main.go` and add the
following Go code:

```go
package main

import "fmt"

func main() {
  fmt.Println("Chat App v0.01")
}
```

Once you have done this and saved your new file, try running it:

```s
$ go run main.go
Chat App v0.01
```

Awesome, if that worked successfully, we can then move on to setting up our
Frontend application.

# Setting Up Our React Frontend

Setting up our frontend is slightly more complex, we'll first start by creating
another directory within the root of our project that we'll call `frontend`
which will house all of our ReactJS code.

> **Note -** We'll be using
> [facebook/create-react-app](https://github.com/facebook/create-react-app) in
> order to generate our React frontend.

```s
$ cd frontend
```

You will then need to create a new ReactJS application using the `create-react-app`
package. This can be installed with `npm`:

```s
$ npm install -g create-react-app
```

Once this is installed, you should then be able to create your new ReactJS application
with the following command:

```s
$ npx create-react-app .
```

Upon running these commands, you should see that it populates our `frontend/`
directory with a basic ReactJS application that we can use as our starting point
for our application.

Our directory structure should look something like this:

```s
node_modules/
public/
src/
.gitignore
package.json
README.md
yarn.lock
```

## Running Your ReactJS App Locally

Now that you have successfully created your basic ReactJS application, it is time
to test that everything is working as expected. Try running your application by
typing the following:

```s
$ npm start
```

If everything went to plan, you will see that your new ReactJS application compiles
and is served on a local development server running on `http://localhost:3000`:

```output
Compiled successfully!

You can now view frontend in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.1.234:3000/

Note that the development build is not optimized.
To create a production build, use yarn build.
```

Perfect, you now have a basic ReactJS which can be extended in the next parts of this
tutorial series.

# Conclusion

Awesome, you have now successfully setup both your frontend and your backend pieces of
our project and we can get cracking on adding cool new functionality.

> **Check out the next part of this series here:
[Part 2 - Simple Communication](/projects/chat-system-in-go-and-react/part-2-simple-communication/)**


text:
namespace electron {

namespace {

const char kIpcKey[] = "ipcNative";

// Gets the private object under kIpcKey
v8::Local<v8::Object> GetIpcObject(v8::Local<v8::Context> context) {
  auto* isolate = context->GetIsolate();
  auto binding_key = gin::StringToV8(isolate, kIpcKey);
  auto private_binding_key = v8::Private::ForApi(isolate, binding_key);
  auto global_object = context->Global();
  auto value =
      global_object->GetPrivate(context, private_binding_key).ToLocalChecked();
  if (value.IsEmpty() || !value->IsObject()) {
    LOG(ERROR) << "Attempted to get the 'ipcNative' object but it was missing";
    return v8::Local<v8::Object>();
  }
  return value->ToObject(context).ToLocalChecked();
}

void InvokeIpcCallback(v8::Local<v8::Context> context,
                       const std::string& callback_name,
                       std::vector<v8::Local<v8::Value>> args) {
  TRACE_EVENT0("devtools.timeline", "FunctionCall");
  auto* isolate = context->GetIsolate();

  auto ipcNative = GetIpcObject(context);
  if (ipcNative.IsEmpty())
    return;

  // Only set up the node::CallbackScope if there's a node environment.
  // Sandboxed renderers don't have a node environment.
  node::Environment* env = node::Environment::GetCurrent(context);
  std::unique_ptr<node::CallbackScope> callback_scope;
  if (env) {
    callback_scope.reset(new node::CallbackScope(isolate, ipcNative, {0, 0}));
  }

  auto callback_key = gin::ConvertToV8(isolate, callback_name)
                          ->ToString(context)
                          .ToLocalChecked();
  auto callback_value = ipcNative->Get(context, callback_key).ToLocalChecked();
  DCHECK(callback_value->IsFunction());  // set by init.ts
  auto callback = callback_value.As<v8::Function>();
  ignore_result(callback->Call(context, ipcNative, args.size(), args.data()));
}

void EmitIPCEvent(v8::Local<v8::Context> context,
                  bool internal,
                  const std::string& channel,
                  std::vector<v8::Local<v8::Value>> ports,
                  v8::Local<v8::Value> args,
                  int32_t sender_id) {
  auto* isolate = context->GetIsolate();

  v8::HandleScope handle_scope(isolate);
  v8::Context::Scope context_scope(context);
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);

  std::vector<v8::Local<v8::Value>> argv = {
      gin::ConvertToV8(isolate, internal), gin::ConvertToV8(isolate, channel),
      gin::ConvertToV8(isolate, ports), args,
      gin::ConvertToV8(isolate, sender_id)};

  InvokeIpcCallback(context, "onMessage", argv);
}

}  // namespace

ElectronApiServiceImpl::~ElectronApiServiceImpl() = default;

ElectronApiServiceImpl::ElectronApiServiceImpl(
    content::RenderFrame* render_frame,
    RendererClientBase* renderer_client)
    : content::RenderFrameObserver(render_frame),
      renderer_client_(renderer_client),
      weak_factory_(this) {}

void ElectronApiServiceImpl::BindTo(
    mojo::PendingAssociatedReceiver<mojom::ElectronRenderer> receiver) {
  // Note: BindTo might be called for multiple times.
  if (receiver_.is_bound())
    receiver_.reset();

  receiver_.Bind(std::move(receiver));
  receiver_.set_disconnect_handler(
      base::BindOnce(&ElectronApiServiceImpl::OnConnectionError, GetWeakPtr()));
}

void ElectronApiServiceImpl::DidCreateDocumentElement() {
  document_created_ = true;
}

void ElectronApiServiceImpl::OnDestruct() {
  delete this;
}

void ElectronApiServiceImpl::OnConnectionError() {
  if (receiver_.is_bound())
    receiver_.reset();
}

void ElectronApiServiceImpl::Message(bool internal,
                                     const std::string& channel,
                                     blink::CloneableMessage arguments,
                                     int32_t sender_id) {
  // Don't handle browser messages before document element is created.
  //
  // Note: It is probably better to save the message and then replay it after
  // document is ready, but current behavior has been there since the first
  // day of Electron, and no one has complained so far.
  //
  // Reason 1:
  // When we receive a message from the browser, we try to transfer it
  // to a web page, and when we do that Blink creates an empty
  // document element if it hasn't been created yet, and it makes our init
  // script to run while `window.location` is still "about:blank".
  // (See https://github.com/electron/electron/pull/1044.)
  //
  // Reason 2:
  // The libuv message loop integration would be broken for unkown reasons.
  // (See https://github.com/electron/electron/issues/19368.)
  if (!document_created_)
    return;

  blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
  if (!frame)
    return;

  v8::Isolate* isolate = blink::MainThreadIsolate();
  v8::HandleScope handle_scope(isolate);

  v8::Local<v8::Context> context = renderer_client_->GetContext(frame, isolate);
  v8::Context::Scope context_scope(context);

  v8::Local<v8::Value> args = gin::ConvertToV8(isolate, arguments);

  EmitIPCEvent(context, internal, channel, {}, args, sender_id);
}

void ElectronApiServiceImpl::ReceivePostMessage(
    const std::string& channel,
    blink::TransferableMessage message) {
  blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
  if (!frame)
    return;

  v8::Isolate* isolate = blink::MainThreadIsolate();
  v8::HandleScope handle_scope(isolate);

  v8::Local<v8::Context> context = renderer_client_->GetContext(frame, isolate);
  v8::Context::Scope context_scope(context);

  v8::Local<v8::Value> message_value = DeserializeV8Value(isolate, message);

  std::vector<v8::Local<v8::Value>> ports;
  for (auto& port : message.ports) {
    ports.emplace_back(
        blink::WebMessagePortConverter::EntangleAndInjectMessagePortChannel(
            context, std::move(port)));
  }

  std::vector<v8::Local<v8::Value>> args = {message_value};

  EmitIPCEvent(context, false, channel, ports, gin::ConvertToV8(isolate, args),
               0);
}

void ElectronApiServiceImpl::NotifyUserActivation() {
  blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
  if (frame)
    frame->NotifyUserActivation(
        blink::mojom::UserActivationNotificationType::kInteraction);
}

void ElectronApiServiceImpl::TakeHeapSnapshot(
    mojo::ScopedHandle file,
    TakeHeapSnapshotCallback callback) {
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  base::ScopedPlatformFile platform_file;
  if (mojo::UnwrapPlatformFile(std::move(file), &platform_file) !=
      MOJO_RESULT_OK) {
    LOG(ERROR) << "Unable to get the file handle from mojo.";
    std::move(callback).Run(false);
    return;
  }
  base::File base_file(std::move(platform_file));

  bool success =
      electron::TakeHeapSnapshot(blink::MainThreadIsolate(), &base_file);

  std::move(callback).Run(success);
}

}  // namespace electron


text:
define(['jquery', 'underscore', 'backbone', 'module'], function($, _, Backbone, module) {'use strict';

	var AppRouter, initialize;

	AppRouter = Backbone.Marionette.AppRouter.extend({

		appRoutes : {
			'welcome' : 'welcome',
		},

		routes : {
			// Define some URL routes
			// Default
			'*actions' : 'defaultAction'
		},

		initialize : function(options) {
			console.log('init index router');
		},

		defaultAction : function(actions) {
			console.log('route default');
			Backbone.history.navigate('welcome', {
				trigger : true,
				replace : true
			});
		}
	});

	initialize = function(ctl) {

		new AppRouter({ controller: ctl });

		var pushState = false, pathParts = window.location.pathname.split('/');
		pathParts = pathParts.slice(0, pathParts.length - 1);

		if ('true' === module.config().pushState) {
			pushState = true;
		}

		Backbone.history.start({
			root : pathParts.join('/'),
			pushState : pushState
		});

		// All navigation that is relative should be passed through the navigate
		// method, to be processed by the router. If the link has a `data-bypass`
		// attribute, bypass the delegation completely.
		$(document).on('click', 'a[href]:not([data-bypass])', function(event) {
			// Get the absolute anchor href.
			// Get the anchor href and protcol
			var href = $(this).attr('href'), protocol = this.protocol + '//';

			// Ensure the protocol is not part of URL, meaning its relative.
			// Stop the event bubbling to ensure the link will not cause a page refresh.
			if (href.slice(protocol.length) !== protocol) {
				// Stop the default event to ensure the link will not cause a page
				// refresh.
				event.preventDefault();

				// `Backbone.history.navigate` is sufficient for all Routers and will
				// trigger the correct events. The Router's internal `navigate` method
				// calls this anyways.  The fragment is sliced from the root.
				Backbone.history.navigate(href.attr, true);
			}
		});
		// you can switch current panel of router by navigate function.
		// router.navigate("advanced", true);
	};
	return {
		initialize : initialize
	};
});