text:
module Brcobranca
  module Retorno
    module Cnab400
      # Formato de Retorno CNAB 400
      # Baseado em: http://www.bradesco.com.br/portal/PDF/pessoajuridica/solucoes-integradas/outros/layout-de-arquivo/cobranca/4008-524-0121-08-layout-cobranca-versao-portugues.pdf
      class Bradesco < Brcobranca::Retorno::Cnab400::Base
        extend ParseLine::FixedWidth # Extendendo parseline

        # Load lines
        def self.load_lines(file, options = {})
          default_options = { except: [1] } # por padrao ignora a primeira linha que é header
          options = default_options.merge!(options)
          super file, options
        end

        # Fixed width layout for Bradesco
        fixed_width_layout do |parse|
          # Todos os campos descritos no documento em ordem
          # :tipo_de_registro, 0..0 # identificacao do registro transacao
          # :codigo_de_inscricao, 1..2 # identificacao do tipo de inscricao/empresa
          # :numero_de_inscricao, 3..16 # numero de inscricao da empresa (cpf/cnpj)
          # :zeros, 17..19

          # Identificacao da empresa no banco
          # :zeros, 20..20
          # :carteira, 21..23
          # :agencia_sem_dv, 24..28
          # :cedente_com_dv 29..36
          parse.field :carteira, 21..23
          parse.field :agencia_sem_dv, 24..28
          parse.field :cedente_com_dv, 29..36

          # :numero_controle_empresa, 37..61, # numero de controle da empresa
          # :zeros, 62..69

          # :nosso_numero, 70..81 # identificacao do titulo no banco
          parse.field :nosso_numero, 70..81

          # :zeros, 82..91 # uso do banco
          # :zeros, 92..103 # uso do banco
          # :indicador_de_rateio, 104..104 # indicador de rateio de credito
          # :zeros, 105..106
          # :carteira, 107..107 # de novo?
          parse.field :cod_de_ocorrencia, 108..109
          # :data_de_ocorrencia, 110..115 # data de ocorrencia no banco (ddmmaa)
          # :n_do_documento, 116..125 # n umero do documento de cobranca (dupl, np etc)
          # :nosso_numero, 126..133 # confirmacao do numero do titulo no banco
          # :brancos, 134..145 # complemento de registro

          # :vencimento, 146..151 # data de vencimento do titulo (ddmmaa)
          parse.field :data_vencimento, 146..151

          # :valor_do_titulo, 152..164 # valor nominal do titulo (ultimos 2 digitos, virgula decimal assumida)
          parse.field :valor_titulo, 152..164

          # :codigo_do_banco, 165..167 # numero do banco na camara de compensacao
          parse.field :banco_recebedor, 165..167

          # :agencia_cobradora, 168..171 # agencia cobradora, ag de liquidacao ou baixa
          # :dac_ag_cobradora, 172..172 # dac da agencia cobradora
          parse.field :agencia_recebedora_com_dv, 168..172

          # :especie, 173..174 # especie do titulo
          parse.field :especie_documento, 173..174

          # :tarifa_de_cobranca, 175..187 # valor da despesa de cobranca (ultimos 2 digitos, virgula decimal assumida)
          parse.field :valor_tarifa, 175..187

          # :outras_despesas 188..200, # valor de outras despesas ou custos do protesto
          # :juros_operacao_em_atraso, 201..213 # zeros?

          # :valor_do_iof, 214..226 # valor do iof a ser recolhido (ultimos 2 digitos, virgula decimal assumida)
          parse.field :iof, 214..226

          # :valor_abatimento, 227..239 # valor do abatimento concedido (ultimos 2 digitos, virgula decimal assumida)
          parse.field :valor_abatimento, 227..239

          # :descontos, 240..252 # valor do desconto concedido (ultimos 2 digitos, virgula decimal assumida)
          parse.field :desconto, 240..252

          # :valor_recebido, 253..265 # valor lancado em conta corrente (ultimos 2 digitos, virgula decimal assumida)
          parse.field :valor_recebido, 253..265

          # :juros_mora, 266..278 # valor de mora e multa pagos pelo sacado (ultimos 2 digitos, virgula decimal assumida)
          parse.field :juros_mora, 266..278

          # :outros_creditos, 279..291 # valor de outros creditos (ultimos 2 digitos, virgula decimal assumida)
          parse.field :outros_recebimento, 279..291

          # :brancos, 292..293
          # :motivo_do_codigo_de_ocorrencia, 294..294

          # :data_credito, 295..300 # data de credito desta liquidacao
          parse.field :data_credito, 295..300

          # :origem_pagamento, 301..303
          # :brancos, 304..313
          # :cheque_bradesco, 314..317
          # :motivo_rejeicao, 318..327
          # :brancos, 328..367
          # :numero_do_cartorio, 368..369
          # :numero_do_protocolo, 370..379
          # :brancos, 380..393

          # :numero_sequencial, 394..399 # numero sequencial no arquivo
          parse.field :sequencial, 394..399
        end

        def agencia_com_dv
          "#{agencia_sem_dv}-#{agencia_sem_dv.modulo11}"
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
injected_dir=$1
source /usr/local/s2i/install-common.sh

S2I_CLI_SCRIPT="${injected_dir}/configuration.cli"

run_cli_script "${S2I_CLI_SCRIPT}"


text:
/*global require */

"use strict";

var path = require("path"),
    // This conditional require is to run the electron version of edge.js
    // when this code runs on electron (gpii-app).
    edge = process.versions.electron ? require("electron-edge-js") : require("edge-js"),
    stringArgv = require("string-argv"),
    fluid = require("gpii-universal");

var gpii = fluid.registerNamespace("gpii");

var dotNetProcesses = edge.func({
    source: path.join(__dirname, "dotNetProcesses.csx"),
    references: ["System.Management.dll"]
});

fluid.defaults("gpii.processes.windows", {
    gradeNames: ["gpii.processes"],
    invokers: {
        getProcessList: {
            funcName: "gpii.processes.windows.getProcessList",
            args: ["{arguments}.0"] // process name or id, optional.
        },
        getProcessPath: {
            funcName: "gpii.processes.windows.getProcessPath",
            args: ["{arguments}.0"] // command name (string)
        }
    },
    ignoreCase: true
});

/**
 * Return the path of a running process.
 *
 * If the full path is not known (the process is running as another user), only the command is returned.
 *
 * @param {Component} that - an instance of a processes component.
 * @param {Number} pid - the process id of the process.
 * @return {String} - The full path of the process, or null if there's no matching process.
 */
gpii.processes.windows.getProcessPath = function (that, pid) {
    return gpii.windows.getProcessPath(pid);
};

/**
 * Return a list of processes -- a snapshot of the current processes.  If the
 * process name or process id is passed, then the return value will be limited
 * to only processes with that name or the process with that pid.
 *
 * @param {String|Number} processIdentifier [optional] Specify a process to find via a name, or a process id.
 * @return {Array<Object>} Array of processes.
 */
gpii.processes.windows.getProcessList = function (processIdentifier) {
    var procInfos = dotNetProcesses(processIdentifier, true);

    // Loop to convert the command line to an argv[].
    fluid.each(procInfos, function (aProcInfo) {
        aProcInfo.argv = stringArgv(aProcInfo.commandLine);
        delete aProcInfo.commandLine;

        // In some cases the first argument is just the command, e.g., "Notepad".
        // In others, it is the full path and may include the ".exe"
        // extension.  Normalize it to always be the full path.
        aProcInfo.argv[0] = aProcInfo.fullPath;
    });
    return procInfos;
};


text:
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Permissions;

namespace CupCake.DefaultCommands.Commands.Owner
{
    public sealed class LoadlevelCommand : OwnerCommandBase
    {
        [MinGroup(Group.Moderator)]
        [Command("loadlevel")]
        [CorrectUsage("")]
        private void Run(IInvokeSource source, ParsedCommand message)
        {
            this.RequireOwner();
            this.Chatter.LoadLevel();
            source.Reply("Loaded level.");
        }
    }
}


text:
;

/*** DEPENDS (including cascading dependencies, listed in cascading dependency order):
  core.static.js (optional)
  core.util.error.js (required)
  core.init.array.js (required)
  jquery.js (required)
***/

var _= _ || {};
_.CORE= _.CORE || {};
_.CORE.INIT= _.CORE.INIT || {};

_.STATIC= _.STATIC || {};
_.DOM= _.DOM || {};

_.STATIC.TAGS= ['A','AREA','BUTTON','CENTER','DIV','FIELDSET','FORM','H1','H2','H3','H4','H5','H6','IFRAME','IMG','INPUT','LI','LINK','OBJECT','OL','OPTION','P','PRE','SECTION','SELECT','SPAN','TABLE','TBODY','TD','TEXTAREA','TH','THEAD','TR','UL'];
_.STATIC.ATTRIBUTES= ['ID', 'NAME', 'HREF', 'CLASS', 'REL'];
_.STATIC.INPUTLIST= ['BUTTON', 'CHECKBOX', 'FILE', 'HIDDEN', 'IMAGE', 'PASSWORD', 'RADIO', 'RESET', 'TEXT', 'EMAIL', 'SUBMIT'];

_.CORE.INIT.DOM= function(){
    _.DOM.WINDOW= $(window);
    _.DOM.HTML= $('html');
    _.DOM.BODY= $('body');

    var register= function(item, i){
      var ref= item.replace(/\-/g, '_').replace('#', '_').replace('.', '__').replace(/\[(.*)=\"(.*)\"\]/, "_$1_$2").toUpperCase().replace('_NAME_', '___').replace('_ID_', '_');
      var tag= ref.split('_')[0];

      var isInput= (_.STATIC.INPUTLIST.indexOf(tag)!== -1);
      var isTag= (ref.indexOf('_')=== -1);

      if(isInput){item= item.replace(tag, 'input');}
      if(isInput && isTag){item= item+ '[type="'+ tag+ '"]';}

      try{var o= $(item);}
      catch(e){return false;}

      _.DOM[ref]= o;

      return o;
    };

    var tagName= function(item){
      var tag= item.tagName.toUpperCase();
      if(tag!== 'INPUT'){return tag;}
      if(!item.hasAttribute('type')){return tag;}

      tag= item.type.toUpperCase();
      return tag;
    };

    var bootstrap= function(elements, filter, map){
      return elements.filter(filter).map(map).flat().set().map(register).filter(function(el){return el!= false;});
    };

    var bootstrapTags= function(elements){
      var filter= function(item, i){return item;};
      var map= function(item, i){return tagName(item);};
      return bootstrap(elements, filter, map);
    };

    var bootstrapClasses= function(elements){
      var filter= function(item, i){return item.hasAttribute('class');};
      var map= function(item, i){return item.className.split(/\s+/).map(function(cls, k){return tagName(item)+ '.'+ cls;});};
      return bootstrap(elements, filter, map);
    };

    var bootstrapAttribute= function(elements, attr){
      if(_.STATIC.ATTRIBUTES.indexOf(attr.toUpperCase())=== -1){
        throw new _.E.ArgumentValueError(attr.toUpperCase()+ " is not a valid argument for bootstrapping.");
      }
      var filter= function(item, i){return item.hasAttribute(attr);};
      var map= function(item, i){return tagName(item)+ '['+ attr+ '="'+ item.getAttribute(attr)+ '"]';};
      return bootstrap(elements, filter, map);
    };

    var elements= _.DOM.BODY.find('*').toArray().filter(function(item, i){
      return _.STATIC.TAGS.indexOf(item.tagName.toUpperCase())!== -1;
    });

    var tags= bootstrapTags(elements);
    var classes= bootstrapClasses(elements);
    var ids= bootstrapAttribute(elements, 'id');
    var names= bootstrapAttribute(elements, 'name');
    var rels= bootstrapAttribute(elements, 'rel');

    return true;
};

//$(function(){_.CORE.INIT.DOM();});


text:
//  SDLBeltStatus.h
//

#import "SDLRPCMessage.h"

#import "SDLVehicleDataEventStatus.h"

NS_ASSUME_NONNULL_BEGIN

/**
 Vehicle data struct for the seat belt status
 */
@interface SDLBeltStatus : SDLRPCStruct

/**
 References signal "VedsDrvBelt_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus driverBeltDeployed;

/**
 References signal "VedsPasBelt_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus passengerBeltDeployed;

/**
 References signal "VedsRw1PasBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus passengerBuckleBelted;

/**
 References signal "VedsRw1DrvBckl_D_Ltchd". See VehicleDataEventStatus

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus driverBuckleBelted;

/**
 References signal "VedsRw2lBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus leftRow2BuckleBelted;

/**
 References signal "VedsRw1PasChld_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus passengerChildDetected;

/**
 References signal "VedsRw2rBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus rightRow2BuckleBelted;

/**
 References signal "VedsRw2mBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus middleRow2BuckleBelted;

/**
 References signal "VedsRw3mBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus middleRow3BuckleBelted;

/**
 References signal "VedsRw3lBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus leftRow3BuckleBelted;

/**
 References signal "VedsRw3rBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus rightRow3BuckleBelted;

/**
 References signal "VedsRw2lRib_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus leftRearInflatableBelted;

/**
 References signal "VedsRw2rRib_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus rightRearInflatableBelted;

/**
 References signal "VedsRw1mBelt_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus middleRow1BeltDeployed;

/**
 References signal "VedsRw1mBckl_D_Ltchd". See VehicleDataEventStatus.

 Required
 */
@property (strong, nonatomic) SDLVehicleDataEventStatus middleRow1BuckleBelted;

@end

NS_ASSUME_NONNULL_END


text:
package db

import (
	"fmt"
	"strconv"
	"time"

	jsoniter "github.com/json-iterator/go"
	"github.com/pkg/errors"
	"gorm.io/gorm"

	"gogs.io/gogs/internal/auth"
	"gogs.io/gogs/internal/auth/github"
	"gogs.io/gogs/internal/auth/ldap"
	"gogs.io/gogs/internal/auth/pam"
	"gogs.io/gogs/internal/auth/smtp"
	"gogs.io/gogs/internal/errutil"
)

// LoginSourcesStore is the persistent interface for login sources.
//
// NOTE: All methods are sorted in alphabetical order.
type LoginSourcesStore interface {
	// Create creates a new login source and persist to database.
	// It returns ErrLoginSourceAlreadyExist when a login source with same name already exists.
	Create(opts CreateLoginSourceOpts) (*LoginSource, error)
	// Count returns the total number of login sources.
	Count() int64
	// DeleteByID deletes a login source by given ID.
	// It returns ErrLoginSourceInUse if at least one user is associated with the login source.
	DeleteByID(id int64) error
	// GetByID returns the login source with given ID.
	// It returns ErrLoginSourceNotExist when not found.
	GetByID(id int64) (*LoginSource, error)
	// List returns a list of login sources filtered by options.
	List(opts ListLoginSourceOpts) ([]*LoginSource, error)
	// ResetNonDefault clears default flag for all the other login sources.
	ResetNonDefault(source *LoginSource) error
	// Save persists all values of given login source to database or local file.
	// The Updated field is set to current time automatically.
	Save(t *LoginSource) error
}

var LoginSources LoginSourcesStore

// LoginSource represents an external way for authorizing users.
type LoginSource struct {
	ID        int64
	Type      auth.Type
	Name      string        `xorm:"UNIQUE" gorm:"UNIQUE"`
	IsActived bool          `xorm:"NOT NULL DEFAULT false" gorm:"NOT NULL"`
	IsDefault bool          `xorm:"DEFAULT false"`
	Provider  auth.Provider `xorm:"-" gorm:"-"`
	Config    string        `xorm:"TEXT cfg" gorm:"COLUMN:cfg;TYPE:TEXT" json:"RawConfig"`

	Created     time.Time `xorm:"-" gorm:"-" json:"-"`
	CreatedUnix int64
	Updated     time.Time `xorm:"-" gorm:"-" json:"-"`
	UpdatedUnix int64

	File loginSourceFileStore `xorm:"-" gorm:"-" json:"-"`
}

// NOTE: This is a GORM save hook.
func (s *LoginSource) BeforeSave(_ *gorm.DB) (err error) {
	if s.Provider == nil {
		return nil
	}
	s.Config, err = jsoniter.MarshalToString(s.Provider.Config())
	return err
}

// NOTE: This is a GORM create hook.
func (s *LoginSource) BeforeCreate(tx *gorm.DB) error {
	if s.CreatedUnix == 0 {
		s.CreatedUnix = tx.NowFunc().Unix()
		s.UpdatedUnix = s.CreatedUnix
	}
	return nil
}

// NOTE: This is a GORM update hook.
func (s *LoginSource) BeforeUpdate(tx *gorm.DB) error {
	s.UpdatedUnix = tx.NowFunc().Unix()
	return nil
}

// NOTE: This is a GORM query hook.
func (s *LoginSource) AfterFind(_ *gorm.DB) error {
	s.Created = time.Unix(s.CreatedUnix, 0).Local()
	s.Updated = time.Unix(s.UpdatedUnix, 0).Local()

	switch s.Type {
	case auth.LDAP:
		var cfg ldap.Config
		err := jsoniter.UnmarshalFromString(s.Config, &cfg)
		if err != nil {
			return err
		}
		s.Provider = ldap.NewProvider(false, &cfg)

	case auth.DLDAP:
		var cfg ldap.Config
		err := jsoniter.UnmarshalFromString(s.Config, &cfg)
		if err != nil {
			return err
		}
		s.Provider = ldap.NewProvider(true, &cfg)

	case auth.SMTP:
		var cfg smtp.Config
		err := jsoniter.UnmarshalFromString(s.Config, &cfg)
		if err != nil {
			return err
		}
		s.Provider = smtp.NewProvider(&cfg)

	case auth.PAM:
		var cfg pam.Config
		err := jsoniter.UnmarshalFromString(s.Config, &cfg)
		if err != nil {
			return err
		}
		s.Provider = pam.NewProvider(&cfg)

	case auth.GitHub:
		var cfg github.Config
		err := jsoniter.UnmarshalFromString(s.Config, &cfg)
		if err != nil {
			return err
		}
		s.Provider = github.NewProvider(&cfg)

	default:
		return fmt.Errorf("unrecognized login source type: %v", s.Type)
	}
	return nil
}

func (s *LoginSource) TypeName() string {
	return auth.Name(s.Type)
}

func (s *LoginSource) IsLDAP() bool {
	return s.Type == auth.LDAP
}

func (s *LoginSource) IsDLDAP() bool {
	return s.Type == auth.DLDAP
}

func (s *LoginSource) IsSMTP() bool {
	return s.Type == auth.SMTP
}

func (s *LoginSource) IsPAM() bool {
	return s.Type == auth.PAM
}

func (s *LoginSource) IsGitHub() bool {
	return s.Type == auth.GitHub
}

func (s *LoginSource) LDAP() *ldap.Config {
	return s.Provider.Config().(*ldap.Config)
}

func (s *LoginSource) SMTP() *smtp.Config {
	return s.Provider.Config().(*smtp.Config)
}

func (s *LoginSource) PAM() *pam.Config {
	return s.Provider.Config().(*pam.Config)
}

func (s *LoginSource) GitHub() *github.Config {
	return s.Provider.Config().(*github.Config)
}

var _ LoginSourcesStore = (*loginSources)(nil)

type loginSources struct {
	*gorm.DB
	files loginSourceFilesStore
}

type CreateLoginSourceOpts struct {
	Type      auth.Type
	Name      string
	Activated bool
	Default   bool
	Config    interface{}
}

type ErrLoginSourceAlreadyExist struct {
	args errutil.Args
}

func IsErrLoginSourceAlreadyExist(err error) bool {
	_, ok := err.(ErrLoginSourceAlreadyExist)
	return ok
}

func (err ErrLoginSourceAlreadyExist) Error() string {
	return fmt.Sprintf("login source already exists: %v", err.args)
}

func (db *loginSources) Create(opts CreateLoginSourceOpts) (*LoginSource, error) {
	err := db.Where("name = ?", opts.Name).First(new(LoginSource)).Error
	if err == nil {
		return nil, ErrLoginSourceAlreadyExist{args: errutil.Args{"name": opts.Name}}
	} else if err != gorm.ErrRecordNotFound {
		return nil, err
	}

	source := &LoginSource{
		Type:      opts.Type,
		Name:      opts.Name,
		IsActived: opts.Activated,
		IsDefault: opts.Default,
	}
	source.Config, err = jsoniter.MarshalToString(opts.Config)
	if err != nil {
		return nil, err
	}
	return source, db.DB.Create(source).Error
}

func (db *loginSources) Count() int64 {
	var count int64
	db.Model(new(LoginSource)).Count(&count)
	return count + int64(db.files.Len())
}

type ErrLoginSourceInUse struct {
	args errutil.Args
}

func IsErrLoginSourceInUse(err error) bool {
	_, ok := err.(ErrLoginSourceInUse)
	return ok
}

func (err ErrLoginSourceInUse) Error() string {
	return fmt.Sprintf("login source is still used by some users: %v", err.args)
}

func (db *loginSources) DeleteByID(id int64) error {
	var count int64
	err := db.Model(new(User)).Where("login_source = ?", id).Count(&count).Error
	if err != nil {
		return err
	} else if count > 0 {
		return ErrLoginSourceInUse{args: errutil.Args{"id": id}}
	}

	return db.Where("id = ?", id).Delete(new(LoginSource)).Error
}

func (db *loginSources) GetByID(id int64) (*LoginSource, error) {
	source := new(LoginSource)
	err := db.Where("id = ?", id).First(source).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return db.files.GetByID(id)
		}
		return nil, err
	}
	return source, nil
}

type ListLoginSourceOpts struct {
	// Whether to only include activated login sources.
	OnlyActivated bool
}

func (db *loginSources) List(opts ListLoginSourceOpts) ([]*LoginSource, error) {
	var sources []*LoginSource
	query := db.Order("id ASC")
	if opts.OnlyActivated {
		query = query.Where("is_actived = ?", true)
	}
	err := query.Find(&sources).Error
	if err != nil {
		return nil, err
	}

	return append(sources, db.files.List(opts)...), nil
}

func (db *loginSources) ResetNonDefault(dflt *LoginSource) error {
	err := db.Model(new(LoginSource)).Where("id != ?", dflt.ID).Updates(map[string]interface{}{"is_default": false}).Error
	if err != nil {
		return err
	}

	for _, source := range db.files.List(ListLoginSourceOpts{}) {
		if source.File != nil && source.ID != dflt.ID {
			source.File.SetGeneral("is_default", "false")
			if err = source.File.Save(); err != nil {
				return errors.Wrap(err, "save file")
			}
		}
	}

	db.files.Update(dflt)
	return nil
}

func (db *loginSources) Save(source *LoginSource) error {
	if source.File == nil {
		return db.DB.Save(source).Error
	}

	source.File.SetGeneral("name", source.Name)
	source.File.SetGeneral("is_activated", strconv.FormatBool(source.IsActived))
	source.File.SetGeneral("is_default", strconv.FormatBool(source.IsDefault))
	if err := source.File.SetConfig(source.Provider.Config()); err != nil {
		return errors.Wrap(err, "set config")
	} else if err = source.File.Save(); err != nil {
		return errors.Wrap(err, "save file")
	}
	return nil
}


text:
package bunker

import (
	"github.com/mailgun/lemma/secret"
	"github.com/mailgun/sandra"
	. "gopkg.in/check.v1"
)

var testCassandraConf = sandra.CassandraConfig{
	Nodes:            []string{"192.168.19.2:9042"},
	Keyspace:         "bunker_test",
	ReadConsistency:  "one",
	WriteConsistency: "one",
	TestMode:         true,
}

var testConf = []ClusterConfig{
	ClusterConfig{
		Name: "cluster-1", Weight: 1, Cassandra: testCassandraConf,
	},
	ClusterConfig{
		Name: "cluster-2", Weight: 1, Cassandra: testCassandraConf,
	},
}

var testHMACKey = []byte("s3cr3t")

type BunkerSuite struct {
	b *bunker
}

var _ = Suite(&BunkerSuite{})

func (s *BunkerSuite) SetUpSuite(c *C) {
	b, err := NewBunker(testConf, testHMACKey)
	if err != nil {
		c.Fatal(err)
	}
	s.b = b.(*bunker)
}

func (s *BunkerSuite) TestPackUnpackKeys(c *C) {
	cluster := s.b.clusters["cluster-1"]
	keys := []string{"key-1", "key-2", "key-3"}

	packedKeys, err := packKeys(cluster, keys, 0)
	c.Assert(err, IsNil)

	// unpack the keys and verify they are the same
	unpackedKeys, err := unpackKeys(cluster, packedKeys)
	c.Assert(err, IsNil)
	c.Assert(unpackedKeys, DeepEquals, keys)
}

func (s *BunkerSuite) TestBasicCRUD(c *C) {
	key, err := s.b.Put("hello, world")
	c.Assert(err, IsNil)

	message, err := s.b.Get(key)
	c.Assert(err, IsNil)
	c.Assert(message, Equals, "hello, world")

	err = s.b.Delete(key)
	c.Assert(err, IsNil)

	message, err = s.b.Get(key)
	c.Assert(err, NotNil)
}

func (s *BunkerSuite) TestMessageChunking(c *C) {
	// mock max chunk size so we can test chunking
	save := getChunkSizeBytes
	defer func() { getChunkSizeBytes = save }()
	getChunkSizeBytes = func() int { return 1 }

	// this message has 3 chars so it'll be chunked into 3 pieces
	message := "hey"

	encKey, err := s.b.Put(message)
	c.Assert(err, IsNil)

	// decode the key and verify it is packed
	key, err := decodeKey(encKey, testHMACKey)
	c.Assert(err, IsNil)
	c.Assert(key.Packed, Equals, true)
}

func (s *BunkerSuite) TestGetAndDeleteChunkedMessage(c *C) {
	// set chunk size to 1 byte...
	save := getChunkSizeBytes
	defer func() { getChunkSizeBytes = save }()
	getChunkSizeBytes = func() int { return 1 }

	// ...and re-run the BasicCRUD test
	s.TestBasicCRUD(c)
}

func (s *BunkerSuite) TestClustersFailover(c *C) {
	// replace clusters iterator with a fake one to make sure cluster-1 is always returned first
	savedIterator := s.b.clustersIterator
	s.b.clustersIterator = &fakeIterator{[]string{"cluster-1", "cluster-2"}}
	defer func() { s.b.clustersIterator = savedIterator }() // restore

	// replace the backend for cluster-1 with a fake one to make sure it always errors
	savedCluster := s.b.clusters["cluster-1"]
	s.b.clusters["cluster-1"] = &fakeCluster{}
	defer func() { s.b.clusters["cluster-1"] = savedCluster }() // restore

	// now verify a message can still be saved successfully
	_, err := s.b.Put("hello")
	c.Assert(err, IsNil)
}

func (s *BunkerSuite) TestAllClustersFailed(c *C) {
	// replace both backends with fake ones to make sure they always error
	savedClusters := s.b.clusters
	s.b.clusters = map[string]backend{"cluster-1": &fakeCluster{}, "cluster-2": &fakeCluster{}}
	defer func() { s.b.clusters = savedClusters }() // restore

	// verify an error is returned
	_, err := s.b.Put("hello")
	c.Assert(err, NotNil)
}

func (s *BunkerSuite) TestCompressDecompress(c *C) {
	compressed, err := compress("hello, world")
	c.Assert(err, IsNil)

	decompressed, err := decompress(compressed)
	c.Assert(err, IsNil)
	c.Assert(decompressed, Equals, "hello, world")
}

func (s *BunkerSuite) TestEncryptDecrypt(c *C) {
	key, err := secret.NewKey()
	c.Assert(err, IsNil)

	secretService, err := secret.New(&secret.Config{KeyBytes: key})
	c.Assert(err, IsNil)

	encrypted, err := encrypt("hello, world", secretService)
	c.Assert(err, IsNil)

	decrypted, err := decrypt(encrypted, secretService)
	c.Assert(err, IsNil)
	c.Assert(decrypted, Equals, "hello, world")
}


text:
/* --------------------------------------

Below are several examples of hooking
up a Falcor model and getting data from
it to be displayed on the screen.

Step 1: A local model cache is setup
with some data. Data is requested with
various get requests to the model.

Step 2: We change the model over to a
JSON Graph with references so that data
isn't duplicated.

Step 3: We move the data over to the
server to be served from a Falcor Router.
This step is currently setup to run but
you can comment it out and start from
Step 1 by uncommenting the appropriate
pieces.

----------------------------------------*/

/* === Step 1 === */

// We can prime the model cache with a new falcor.Model
// var model = new falcor.Model({
//   cache: {
//     events: [
//       {
//         name: "ng-conf",
//         description: "The world's best Angular Conference",
//         stuff: "oh hey stuff",
//         location: { city: "Salt Lake City", state: "Utah" }
//       },
//       {
//         name: "React Rally",
//         description: "Conference focusing on Facebook's React",
//         location: { city: "Salt Lake City", state: "Utah" }
//       },
//       {
//         name: "ng-Vegas",
//         description: "Two days jam-packed with Angular goodness with a focus on Angular 2",
//         location: { city: "Las Vegas", state: "Nevada" }
//       },
//       {
//         name: "Midwest JS",
//         description: "Midwest JS is a premier technology conference focused on the JavaScript ecosystem.",
//         location: { city: "Minneapolis", state: "Minnesota" }
//       },
//       {
//         name: "NodeConf",
//         description: "NodeConf is the longest running community driven conference for the Node community.",
//         location: { city: "Walker Creek Ranch", state: "California" }
//       }
//     ]
//   }
// });

// model
//   We want the name and description values for the first three items
//   from the data model
// .get(["events", {from: 0, to: 2}, ["name", "description"]])
//   To get the values on the "location" object, we need to pass the paths for the
//   keys on that object
  // .get(["events", {from: 0, to: 2}, ["name", "description", "location"],["city", "state"]])
  // .then(function(response) {
  //   document.getElementById("event-data").innerHTML = JSON.stringify(response, null, 2);
  // });

// model
//       // We set the value of the first occurrence of Utah to UT
//   .set(falcor.pathValue(["events", 0, "location", "state"], 'UT'))
//   .then(function(response) {
//     model
//     // What we find afterwards is that the value gets changed in one location, but not both.
//       .get(["events", {from: 0, to: 2}, ["name", "description", "location"],["city", "state"]])
//       .then(function(response) {
//         document.getElementById('event-data').innerHTML = JSON.stringify(response, null, 2);
//       });
//   });

/* === Step 2 === */

// We can use the shorthand for references with a variable
// var $ref = falcor.Model.ref;
//
// var model = new falcor.Model({
//   cache: {
//     locationsById: {
//       1: {
//         city: "Salt Lake City",
//         state: "Utah"
//       },
//       2: {
//         city: "Las Vegas",
//         state: "Nevada"
//       },
//       3: {
//         city: "Minneapolis",
//         state: "Minnesota"
//       },
//       4: {
//         city: "Walker Creek Ranch",
//         state: "California"
//       }
//     },
//     events: [
//       {
//         name: "ng-conf",
//         description: "The world's best Angular Conference",
//         location: $ref('locationsById[1]')
//       },
//       {
//         name: "React Rally",
//         description: "Conference focusing on Facebook's React",
//         location: $ref('locationsById[1]')
//       },
//       {
//         name: "ng-Vegas",
//         description: "Two days jam-packed with Angular goodness with a focus on Angular 2",
//         location: $ref('locationsById[2]')
//       },
//       {
//         name: "Midwest JS",
//         description: "Midwest JS is a premier technology conference focused on the JavaScript ecosystem.",
//         location: $ref('locationsById[3]')
//       },
//       {
//         name: "NodeConf",
//         description: "NodeConf is the longest running community driven conference for the Node community.",
//         location: $ref('locationsById[4]')
//       }
//     ]
//   }
// });
//

// model
//   // Now when we set Utah to UT for the first occurrence, it is changed everywhere else
//   .set(falcor.pathValue(["events", 0, "location", "state"], 'UT'))
//   .then(function(response) {
//     model
//       .get(["events", {from: 0, to: 2}, ["name", "description", "location"],["city", "state"]])
//       .then(function(response) {
//         document.getElementById('event-data').innerHTML = JSON.stringify(response, null, 2);
//       });
//   });

/* === Step 3 === */

// We can set the model to have a data source that is retrieved from the backend
// over HTTP by setting the soure to be a falcor.HttpDataSource.
var model = new falcor.Model({source: new falcor.HttpDataSource('/model.json')});
  // .get(["events", {from: 0, to: 2}, ["name", "description"]])
  // .get([
  //   "events", {from: 0, to: 2}, ["name", "description"]
  // ],
  // [
  //   'events', {from: 0, to: 2}, 'location', ['city', 'state']
  // ])
// model
//   .get(["events", {from: 0, to: 2}, ["name", "description", "location"],["city", "state"]])
//
//   .then(function(response) {
//     document.getElementById('event-data').innerHTML = JSON.stringify(response, null, 2);
//   });

// Search example - we pass "Midwest JS" which will be looked up
// in the events data on the server and sent back if it exists
model
  .get(["events", "byName", ["Midwest JS"], ['description']])
  .then(function(response) {
    document.getElementById('event-data').innerHTML = JSON.stringify(response, null, 2);
  }, function(err) {
    console.log(err);
    // console.log(err['0'].value.message);
  });


text:
package devmenu.com.swmansion.gesturehandler;

import android.view.MotionEvent;

public interface OnTouchEventListener<T extends GestureHandler> {
  void onTouchEvent(T handler, MotionEvent event);
  void onStateChange(T handler, int newState, int oldState);
}


text:
List Files From Set
===================

A concrete5.7 block package to list files from a File Set

A 5.6 compatible version of the block is available in the '5.6 version' branch.


text:
package org.elasticsearch.index.mapper;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.query.QueryShardContext;
import org.mockito.Mockito;

import java.io.IOException;
import java.util.Collections;
import java.util.Set;

public class TypeFieldTypeTests extends FieldTypeTestCase {
    @Override
    protected MappedFieldType createDefaultFieldType() {
        return new TypeFieldMapper.TypeFieldType();
    }

    public void testTermsQueryWhenTypesAreDisabled() throws Exception {
        QueryShardContext context = Mockito.mock(QueryShardContext.class);
        Settings indexSettings = Settings.builder()
                .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
                .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
                .put("index.mapping.single_type", true).build();
        IndexMetaData indexMetaData = IndexMetaData.builder(IndexMetaData.INDEX_UUID_NA_VALUE).settings(indexSettings).build();
        IndexSettings mockSettings = new IndexSettings(indexMetaData, Settings.EMPTY);
        Mockito.when(context.getIndexSettings()).thenReturn(mockSettings);

        MapperService mapperService = Mockito.mock(MapperService.class);
        Set<String> types = Collections.emptySet();
        Mockito.when(mapperService.types()).thenReturn(types);
        Mockito.when(context.getMapperService()).thenReturn(mapperService);

        TypeFieldMapper.TypeFieldType ft = new TypeFieldMapper.TypeFieldType();
        ft.setName(TypeFieldMapper.NAME);
        Query query = ft.termQuery("my_type", context);
        assertEquals(new MatchNoDocsQuery(), query);

        types = Collections.singleton("my_type");
        Mockito.when(mapperService.types()).thenReturn(types);
        query = ft.termQuery("my_type", context);
        assertEquals(new MatchAllDocsQuery(), query);

        Mockito.when(mapperService.hasNested()).thenReturn(true);
        query = ft.termQuery("my_type", context);
        assertEquals(Queries.newNonNestedFilter(), query);

        types = Collections.singleton("other_type");
        Mockito.when(mapperService.types()).thenReturn(types);
        query = ft.termQuery("my_type", context);
        assertEquals(new MatchNoDocsQuery(), query);
    }

    public void testTermsQueryWhenTypesAreEnabled() throws Exception {
        Directory dir = newDirectory();
        IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
        IndexReader reader = openReaderWithNewType("my_type", w);

        QueryShardContext context = Mockito.mock(QueryShardContext.class);
        Settings indexSettings = Settings.builder()
                .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
                .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
                .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
                .put("index.mapping.single_type", false).build();
        IndexMetaData indexMetaData = IndexMetaData.builder(IndexMetaData.INDEX_UUID_NA_VALUE).settings(indexSettings).build();
        IndexSettings mockSettings = new IndexSettings(indexMetaData, Settings.EMPTY);
        Mockito.when(context.getIndexSettings()).thenReturn(mockSettings);

        TypeFieldMapper.TypeFieldType ft = new TypeFieldMapper.TypeFieldType();
        ft.setName(TypeFieldMapper.NAME);
        Query query = ft.termQuery("my_type", context);
        assertEquals(new MatchAllDocsQuery(), query.rewrite(reader));

        // Make sure that Lucene actually simplifies the query when there is a single type
        Query userQuery = new PhraseQuery("body", "quick", "fox");
        Query filteredQuery = new BooleanQuery.Builder().add(userQuery, Occur.MUST).add(query, Occur.FILTER).build();
        Query rewritten = new IndexSearcher(reader).rewrite(filteredQuery);
        assertEquals(userQuery, rewritten);

        // ... and does not rewrite it if there is more than one type
        reader.close();
        reader = openReaderWithNewType("my_type2", w);
        Query expected = new ConstantScoreQuery(
            new BooleanQuery.Builder()
                .add(new TermQuery(new Term(TypeFieldMapper.NAME, "my_type")), Occur.SHOULD)
            .build()
        );
        assertEquals(expected, query.rewrite(reader));

        BytesRef[] types =
            new BytesRef[] {new BytesRef("my_type"), new BytesRef("my_type2"), new BytesRef("my_type3")};
        // the query should match all documents
        query = new TypeFieldMapper.TypesQuery(types);
        assertEquals(new MatchAllDocsQuery(), query.rewrite(reader));

        reader.close();
        reader = openReaderWithNewType("unknown_type", w);
        // the query cannot rewrite to a match all docs sinc unknown_type is not queried.
        query = new TypeFieldMapper.TypesQuery(types);
        expected =
            new ConstantScoreQuery(
                new BooleanQuery.Builder()
                    .add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, types[0])), Occur.SHOULD)
                    .add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, types[1])), Occur.SHOULD)
                .build()
            );
        rewritten = query.rewrite(reader);
        assertEquals(expected, rewritten);

        // make sure that redundant types does not rewrite to MatchAllDocsQuery
        query = new TypeFieldMapper.TypesQuery(new BytesRef("my_type"), new BytesRef("my_type"), new BytesRef("my_type"));
        expected =
            new ConstantScoreQuery(
                new BooleanQuery.Builder()
                    .add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, "my_type")), Occur.SHOULD)
                    .build()
            );
        rewritten = query.rewrite(reader);
        assertEquals(expected, rewritten);

        IOUtils.close(reader, w, dir);
    }

    static DirectoryReader openReaderWithNewType(String type, IndexWriter writer) throws IOException {
        Document doc = new Document();
        StringField typeField = new StringField(TypeFieldMapper.NAME, type, Store.NO);
        doc.add(typeField);
        writer.addDocument(doc);
        return DirectoryReader.open(writer);
    }
}


text:
title: Styles
meaning: Tricking or deceiving someone
usage: Man was running styles on me
---


text:
package internalversion

import (
	network "github.com/openshift/origin/pkg/network/apis/network"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
)

// ClusterNetworkLister helps list ClusterNetworks.
type ClusterNetworkLister interface {
	// List lists all ClusterNetworks in the indexer.
	List(selector labels.Selector) (ret []*network.ClusterNetwork, err error)
	// Get retrieves the ClusterNetwork from the index for a given name.
	Get(name string) (*network.ClusterNetwork, error)
	ClusterNetworkListerExpansion
}

// clusterNetworkLister implements the ClusterNetworkLister interface.
type clusterNetworkLister struct {
	indexer cache.Indexer
}

// NewClusterNetworkLister returns a new ClusterNetworkLister.
func NewClusterNetworkLister(indexer cache.Indexer) ClusterNetworkLister {
	return &clusterNetworkLister{indexer: indexer}
}

// List lists all ClusterNetworks in the indexer.
func (s *clusterNetworkLister) List(selector labels.Selector) (ret []*network.ClusterNetwork, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*network.ClusterNetwork))
	})
	return ret, err
}

// Get retrieves the ClusterNetwork from the index for a given name.
func (s *clusterNetworkLister) Get(name string) (*network.ClusterNetwork, error) {
	obj, exists, err := s.indexer.GetByKey(name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(network.Resource("clusternetwork"), name)
	}
	return obj.(*network.ClusterNetwork), nil
}


text:
module Integral
  # Allow list items to be renderered through a partial
  class PartialListItemRenderer < Integral::ListItemRenderer
    def initialize(list_item, opts = {})
      super

      raise_if_partial_path_missing
    end

    # Override Integral::ListItemRenderer#render_item
    def render_item
      partial_opts = {
        title: title,
        subtitle: subtitle,
        description: description,
        url: url,
        image: image(@opts[:image_version]),
        type: list_item.type,
        object: object_available? ? list_item.object.decorate : nil
      }

      controller.render partial: @opts[:partial_path], locals: partial_opts, layout: false
    end

    private

    def raise_if_partial_path_missing
      return if @opts[:partial_path].present?

      error_msg = 'PartialListItemRenderer requires the partial_path (pass this in via opts hash)'
      raise ArgumentError, error_msg
    end

    def controller
      return @opts[:controller] if @opts[:controller].present?

      ApplicationController
    end
  end
end


text:
import os
from datetime import datetime
_BASE_PATH = os.path.abspath(os.path.dirname(__file__))
VERSION_FILE = os.path.abspath(os.path.join(_BASE_PATH, '../VERSION'))

def next_version(version_file):
    now = datetime.now()
    this_month = datetime(now.year, now.month, 1)
    with open(version_file, 'r') as f:
        version = f.read().strip().split('.')
        release_month = datetime.strptime('.'.join(version[:-1]), '%y.%m')
        release_number = int(version[-1]) + 1
        if this_month != release_month:
            release_number = 1
        release_number =  max(1, release_number)
        return '{:%y.%m}.{}'.format(this_month, release_number).decode('utf-8')

def bump_version_file(filename=None):
    if filename is None:
        filename = VERSION_FILE
    next_version_string = next_version(filename)
    with open(filename, 'w') as f:
        f.write(next_version_string)

if __name__ == '__main__':
    bump_version_file()


text:
VERSION=`grep 'version' package.json | cut -d '"' -f 4`

package:
	npm test
	mkdir -p build
	cp README.md build/README.md
	cp src/retina.less build/retina.less
	echo "// retina.js, a high-resolution image swapper (http://retinajs.com), v$(VERSION)\n" > build/retina.js
	uglifyjs src/retina.js >> build/retina.js
	cat build/retina.js


text:
import string

def ceaser(plaintext, shift, mode='encode'):
    '''
    Ceaser cipher encoder and decoder.
    :param plaintext: bytes
    :param shift: int, Number of characters to shift by.
    :param mode: 'encode' from plain to cipher, 'decode' from cipher to plain.
    :return: bytes
    '''
    if type(plaintext) is not bytes:
        raise TypeError('plaintext must be bytes.')
    alphabet = string.ascii_lowercase.encode()
    if mode == 'encode':
        shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    elif mode == 'decode':
        shift *= -1
        shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = bytes.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)

def groups(seq, length):
    '''
    :param seq: A slicable object like string or list.
    :param length: The length of the groups
    :return:
    '''
    for i in range(0, len(seq), length):
        # print(i)
        yield seq[i:i + length]

def hexbytes_to_bytestr(bytes_data):
    l = list(map(lambda x: chr(int(x, 16)).encode(), groups(bytes_data, 2)))
    s = b''.join(l)
    return s


text:
from datetime import datetime
import json

class JSONEncoder(json.JSONEncoder):
    """ This encoder will serialize all entities that have a to_dict
    method by calling that method and serializing the result. """

    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        if hasattr(obj, 'to_dict'):
            return obj.to_dict()
        raise TypeError("%r is not JSON serializable" % obj)


text:
local SERVICE     = require "LuaService"
local config      = require "spylog.config"
config.LOG.prefix = "[jail] "
-------------------------------------------------

local log           = require "spylog.log"
local version       = require "spylog.version"
local uv            = require "lluv"
uv.poll_zmq         = require "lluv.poll_zmq"
local zthreads      = require "lzmq.threads"
local ztimer        = require "lzmq.timer"
local cjson         = require "cjson.safe"
local Counter       = require "spylog.TimeCounters"
local date          = require "date"
local stp           = require "StackTracePlus"
local exit          = require "spylog.exit"
local var           = require "spylog.var"
local path          = require "path"
local CaptureFilter = require "spylog.cfilter"

local function rndint(v)
  return math.random(0, v)
end

log.info('Starting %s version %s. %s', version._NAME, version._VERSION, version._COPYRIGHT)

local DEFAULT = config.JAIL and config.JAIL.default or {}

local sub, err = zthreads.context():socket("SUB",{
  [config.CONNECTIONS.JAIL.FILTER.type] = config.CONNECTIONS.JAIL.FILTER.address;
  subscribe = "";
})

if not sub then
  log.fatal("Can not start filter interface: %s", tostring(err))
  ztimer.sleep(500)
  return SERVICE.exit()
end

local pub, err = zthreads.context():socket("PUB",{
  [config.CONNECTIONS.JAIL.ACTION.type] = config.CONNECTIONS.JAIL.ACTION.address;
})

if not pub then
  log.fatal("Can not start action interface: %s", tostring(err))
  ztimer.sleep(500)
  return SERVICE.exit()
end

local function apply_vars(jail, dst, src, context)
  for i, v in pairs(src) do
    if type(v) == 'table' then
      dst[i] = apply_vars(jail, {}, v, context)
    elseif type(v) == 'string' then
      local unknown
      dst[i], unknown = var.format(v, context)
      if unknown then
        return log.alert("[%s] unknown parameter: %s", jail.name, next(unknown))
      end
    else dst[i] = v end
  end
  return dst
end

local function build_action(jail, action, context)
  if type(action) == 'string' then
    local unknown
    action, unknown = var.format(action, context)
    if unknown then
      return log.alert("[%s] unknown parameter: %s", jail.name, next(unknown))
    end
    return {action}
  end

  local name, unknown, parameters = var.format(action[1], context)
  if unknown then
    return log.alert("[%s] unknown parameter: %s", jail.name, next(unknown))
  end

  if action[2] then
    context.action = name
    parameters = apply_vars(jail, {}, action[2], context)
  end

  return {name, parameters}
end

local function action(jail, filter, value)
  -- extend filter capture
  filter.jail    = jail.name
  filter.bantime = jail.bantime
  filter.counter = value
  if jail.rndtime then
    filter.bantime = filter.bantime + rndint(jail.rndtime)
  end

  -- build jail parameters
  local parameters
  if jail.parameters then
    local context = DEFAULT.parameters and var.combine{filter, DEFAULT.parameters} or filter
    parameters = apply_vars(jail, {}, jail.parameters, context)
  end

  local context
  if parameters then
    context = var.combine{filter, parameters, DEFAULT.parameters}
  elseif DEFAULT.parameters then
    context = var.combine{filter, DEFAULT.parameters}
  else
    context = filter
  end

  local actions = {}
  if type(jail.action) == 'string' then
    local action = build_action(jail, jail.action, context)
    if not action then return end
    actions[1] = action
  else
    for _, action in ipairs(jail.action) do
      action = build_action(jail, action, context)
      if not action then return end
      actions[#actions + 1] = action
    end
  end

  local msg = cjson.encode{
    filter     = filter.filter;
    jail       = filter.jail;
    bantime    = filter.bantime;
    host       = filter.host;
    date       = filter.date;
    action     = actions;
  }

  log.trace("action %s", msg)

  pub:send(msg)
end

log.debug("config.LOG.multithread: %s", tostring(config.LOG.multithread))

log.notice("Connected to filters")

local JAIL do

local function append_jail(jails, filter_name, jail)
  local t = jails[filter_name]

  if not t then
    t = {}
    jails[filter_name] = t
  end
  t[#t + 1] = jail

  return jails
end

local function j(t)
  local jails = {}
  for i = 1, #t do if t[i].enabled or (t[i].enabled == nil) then
    local jail = t[i]
    jails[#jails + 1] = jail

    jail.name = jail.name or jail[1]
    if type(jail.filter) == 'table' then
      for j = 1, #jail.filter do
        append_jail(jails, jail.filter[j], jail)
      end
    else
      append_jail(jails, jail.filter, jail)
    end

    -- apply default values
    for name, value in pairs(DEFAULT) do
      if name ~= 'parameters' and jail[name] == nil then
        jail[name] = value
      end
    end

    if jail.cfilter then
      local ok, cfilter= pcall(CaptureFilter.new, jail.cfilter)
      if not ok then
        local err = string.format('can not build capture filter `%s`: %s', jail.name, cfilter)
        return nil, err
      end

      local names = cfilter:filter_names()
      if #names == 0 then jail.cfilter = nil else
        jail.cfilter = cfilter
        for i = 1, #names do
          log.info('[%s] add capture filter `%s`', jail.name, names[i])
        end
      end
    end
  end end

  return jails
end

JAIL, err = j(config.JAILS)

if not JAIL then
  log.fatal("Can not load jails: %s", tostring(err))
  ztimer.sleep(500)
  return SERVICE.exit()
end

if not next(JAIL) then
  log.warning('there no any active jails')
end

end

local jail_counters = {}

local function create_counter(jail)
  local counter

  counter = Counter.jail:new( jail )
  return counter
end

local function check_jail(jail, capture)
  local banwhat = jail.counter and jail.counter.capture or 'host'
  if not capture[banwhat] then
    log.error('filter `%s` does not provide `%s` capture', capture.filter, banwhat)
    return
  end

  if jail.cfilter then
    local ok, cfilter_name = jail.cfilter:apply(capture)
    if not ok then
      log.debug("[%s] message from %s excluded by capture filter %s", jail.name, capture.filter, cfilter_name)
      return
    end
  end

  local counter = jail_counters[jail.name]
  if not counter then
    counter = create_counter(jail)
    jail_counters[jail.name] = counter
  end

  local value = counter:inc(capture)

  if value then
    if value >= jail.maxretry then
      counter:reset(capture)
      log.warning("[%s] %s - %d", jail.name, capture[banwhat], value)
      action(jail, capture, value) --! @note `action` may add some fields to `capture`
    else
      log.trace("[%s] %s - %d", jail.name, capture[banwhat], value)
    end
  end
end

uv.poll_zmq(sub):start(function(handle, err, pipe)
  if err then
    log.fatal("poll: ", err)
    return uv.stop()
  end

  local msg, err = sub:recvx()
  if not msg then
    if err:name() ~= 'EAGAIN' then
      log.fatal("recv msg: ", err)
      uv.stop()
    end
    return
  end

  log.trace("%s", msg)

  local capture = cjson.decode(msg)
  if not (capture and capture.filter and capture.date) then
    log.error("invalid msg: ", msg:sub(128))
    return
  end

  local jails = JAIL[capture.filter]
  if not jails then
    log.warning("unknown jail for filter `%s`", capture.filter)
  else for i = 1, #jails do
    check_jail(jails[i], capture)
  end end
end)

if config.JAIL and config.JAIL.purge_interval then
  local LVL_TRACE = require "log".LVL.TRACE
  local purge_counter  = 0
  local purge_interval = config.JAIL.purge_interval
  log.info("Start purge timer %d [min]", purge_interval)
  uv.timer():start(60000, 60000, function()
    purge_counter = purge_counter + 1
    if purge_counter >= purge_interval then
      purge_counter = 0
      local now = date()
      for name, jail_counter in pairs(jail_counters) do
        local c
        if log.lvl() >= LVL_TRACE then
          c = jail_counter:count()
        end
        jail_counter:purge(now)
        if c then
          log.trace("Purge jail %s %d => %d", name, c, jail_counter:count())
        end
      end
    end
  end)
end

exit.start_monitor(...)

for filter, jails in pairs(JAIL) do
  if type(filter) ~= 'number' then
    for i = 1, #jails do
      log.info("Attach filter `%s` to jail `%s`", filter, jails[i].name)
    end
  end
end

local ok, err = pcall(uv.run, stp.stacktrace)

if not ok then
  log.alert(err)
end

log.info("Service stopped")

ztimer.sleep(500)

SERVICE.exit()


text:
'use strict';

module.exports = function(grunt) {
	var path = require('path');
	var fs = require('fs');
	var yaml = require('js-yaml');
	var resolve = require('json-refs').resolveRefs;

	var SwaggerResolver = require('../swagger-resolver');

	// Filter out non-relative paths, and any schema $refs
	function refFilter(ref, path) {
		if( ref.type !== 'relative' ) {
			return false;
		}
		if( path && path.length > 0 && path[path.length-1] === 'schema' ) {
			return false;
		}
		return true;
	}

	/**
	 * This task flattens the nested swagger yaml into a single flat file.
	 * It does not resolve the JSON schema links.
	 * @param {object} options
	 * @param {string} options.format The output format, either 'yaml' or 'json' (default)
	 * @param {object} data Task data
	 * @param {string} data.src The input file (root level swagger file)
	 * @param {string} data.dest The destination file (the flattened output file)
	 */
	grunt.registerMultiTask('flattenSwagger', 'Resolve references in swagger YAML files', function() {
		var srcFile = this.data.src||'swagger.yml';
		var destFile = this.data.dest||'swagger.json';
		var version = this.data.version || '';

		var resolver = new SwaggerResolver({
			log: function() {
				grunt.log.writeln.apply(grunt.log, arguments);
			}
		});

		function resolveContent(res, callback) {
			callback(undefined, resolver.resolveContent(res));
		}

		// See: http://azimi.me/2015/07/16/split-swagger-into-smaller-files.html
		// and the corresponding repo: https://github.com/mohsen1/multi-file-swagger-example
		if(!fs.existsSync(srcFile)) {
			grunt.log.writeln('Could not find:', srcFile);
			return false;
		}

		var options = this.options({
			format: 'json'
		});

		var root = yaml.safeLoad(fs.readFileSync(srcFile).toString());

		// Set version
		if( version && root.info ) {
			root.info.version = version;
		}

		// Resolve any top-level includes or templates
		try {
			root = resolver.resolveObject(root);
		} catch (e) {
			grunt.log.writeln("Could not resolve root:", e);
			return false;
		}

		var resolveOpts = {
			filter: refFilter,
			loaderOptions: {
				processContent: resolveContent
			}
		};

		var done = this.async();
		resolve(root, resolveOpts).then(function(results) {
			var data;
			if( options.format === 'yaml' ) {
				data = yaml.safeDump(results.resolved);
			} else if( options.format === 'json' ) {
				data = JSON.stringify(results.resolved, null, 2);
			}

			fs.writeFileSync(destFile, data);
			done();
		});
	});
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.uclab.mm.sl.uiux.analytics.TrackMe</title>
<meta name="date" content="2016-12-23">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.uclab.mm.sl.uiux.analytics.TrackMe

Packages that use TrackMe

Package
Description

org.uclab.mm.sl.uiux.analytics

org.uclab.mm.sl.uiux.analytics.plugins

Uses of TrackMe in org.uclab.mm.sl.uiux.analytics

Methods in org.uclab.mm.sl.uiux.analytics that return TrackMe

Modifier and Type
Method and Description

TrackMe
TrackHelper.Screen.build()

TrackMe
TrackHelper.EventBuilder.build()

TrackMe
TrackHelper.Exception.build()

TrackMe
Tracker.getDefaultTrackMe()

UIUXAnalytics will use the content of this object to fill in missing values before any transmission.

TrackMe
TrackMe.set(QueryParams key,
   float value)

Set track me.

TrackMe
TrackMe.set(QueryParams key,
   int value)

Set track me.

TrackMe
TrackMe.set(QueryParams key,
   long value)

Set track me.

TrackMe
TrackMe.set(QueryParams key,
   java.lang.String value)

You can set any additional Tracking API Parameters within the SDK.

TrackMe
TrackMe.trySet(QueryParams key,
      float value)

Only sets the value if it doesn't exist.

TrackMe
TrackMe.trySet(QueryParams key,
      int value)

Only sets the value if it doesn't exist.

TrackMe
TrackMe.trySet(QueryParams key,
      long value)

Try set track me.

TrackMe
TrackMe.trySet(QueryParams key,
      java.lang.String value)

Only sets the value if it doesn't exist.

Methods in org.uclab.mm.sl.uiux.analytics with parameters of type TrackMe

Modifier and Type
Method and Description

static TrackHelper
TrackHelper.track(TrackMe base)

Track track helper.

Tracker
Tracker.track(TrackMe trackMe)

Track tracker.

Constructors in org.uclab.mm.sl.uiux.analytics with parameters of type TrackMe

Constructor and Description

TrackMe(TrackMe trackMe)

Instantiates a new Track me.

UIUXExceptionHandler(Tracker tracker,
                    TrackMe trackMe)

Instantiates a new Uiux exception handler.

Uses of TrackMe in org.uclab.mm.sl.uiux.analytics.plugins

Subclasses of TrackMe in org.uclab.mm.sl.uiux.analytics.plugins

Modifier and Type
Class and Description

class
CustomDimensions

This plugins allows you to track any Custom Dimensions.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
CREATE TABLE `httpRequestError` (
  `httpRequestId` binary(16) NOT NULL,
  `httpRequestErrorId` binary(16) DEFAULT NULL,
  `httpRequestErrorCreateTime` datetime(6) NOT NULL,
  PRIMARY KEY (`httpRequestId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


text:
'use strict';

var React = require('react');

module.exports = React.createClass({
    displayName: 'ViewSource',

    propTypes: {
        onFinished: React.PropTypes.func.isRequired
    },

    componentDidMount: function() {
        document.addEventListener("keydown", this.onKeyDown);
    },

    componentWillUnmount: function() {
        document.removeEventListener("keydown", this.onKeyDown);
    },

    onKeyDown: function(ev) {
        if (ev.keyCode == 27) { // escape
            ev.stopPropagation();
            ev.preventDefault();
            this.props.onFinished();
        }
    },

    render: function() {
        return (

                    {JSON.stringify(this.props.mxEvent.event, null, 2)}

        );
    }
});


text:
module Ixtlan
  module Guard
    class AbstractSession

      attr_accessor :permissions, :user, :idle_session_timeout

      def self.create(login, password)
        self.do_create(authenticate(login, password))
      end

      def self.create_remote(login, password)
        self.do_create(authenticate_remote(login, password))
      end

      private

      def self.do_create(user)
        result = new

        if user.valid?
          result.user = user
        else
          result.log = user.to_log # error message
        end
        result
      end

      public

      def log=(msg)
        @log = msg
      end

      def to_log
        if @log
          @log
        else
          "Session(user-id: #{user.id}, idle-session-timeout: #{idle_session_timeout})"
        end
      end

      def valid?
        @log.nil?
      end

      def attributes
        {'idle_session_timeout' => idle_session_timeout, 'permissions' => permissions, 'user' => user}
      end

      protected

      def self.authenticate(login, password)
        raise "not implemented"
      end

      def self.authenticate_remote(login, password)
        raise "not implemented"
      end
    end
  end
end


text:
use std::path::PathBuf;

fn main() {
    // ensure the build script exports the include directory
    let include_dir = std::env::var("DEP_S2N_TLS_INCLUDE").expect("missing DEP_S2N_TLS_INCLUDE");
    let include_dir = PathBuf::from(include_dir);

    // make sure that `s2n.h` is available
    let api = std::fs::read_to_string(include_dir.join("s2n.h")).unwrap();
    assert!(api.contains("s2n_negotiate"));
}


text:
/*
 * c-periphery
 * https://github.com/vsergeev/c-periphery
 * License: MIT
 */

#include "test.h"

#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/wait.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#include "../src/gpio.h"

const char *device;
unsigned int pin_input, pin_output;

void test_arguments(void) {
    gpio_t *gpio;

    ptest();

    /* Allocate GPIO */
    gpio = gpio_new();
    passert(gpio != NULL);

    /* Invalid direction */
    passert(gpio_open(gpio, device, pin_input, 5) == GPIO_ERROR_ARG);

    /* Free GPIO */
    gpio_free(gpio);
}

void test_open_config_close(void) {
    gpio_t *gpio;
    bool value;
    gpio_direction_t direction;
    gpio_edge_t edge;
    char label[32];
    gpio_bias_t bias;
    gpio_drive_t drive;
    bool inverted;

    ptest();

    /* Allocate GPIO */
    gpio = gpio_new();
    passert(gpio != NULL);

    /* Open non-existent GPIO */
    passert(gpio_open(gpio, device, -1, GPIO_DIR_IN) == GPIO_ERROR_OPEN);
    passert(gpio_errno(gpio) == EINVAL);

    /* Open legitimate GPIO */
    passert(gpio_open(gpio, device, pin_output, GPIO_DIR_IN) == 0);

    /* Check properties */
    passert(gpio_line(gpio) == pin_output);
    passert(gpio_fd(gpio) >= 0);
    passert(gpio_chip_fd(gpio) >= 0);

    /* Check default label */
    passert(gpio_label(gpio, label, sizeof(label)) == 0);
    passert(strncmp(label, "periphery", sizeof(label)) == 0);

    /* Invalid direction */
    passert(gpio_set_direction(gpio, 5) == GPIO_ERROR_ARG);
    /* Invalid interrupt edge */
    passert(gpio_set_edge(gpio, 5) == GPIO_ERROR_ARG);
    /* Invalid bias */
    passert(gpio_set_bias(gpio, 5) == GPIO_ERROR_ARG);
    /* Invalid drive */
    passert(gpio_set_drive(gpio, 5) == GPIO_ERROR_ARG);

    /* Set direction out, check direction out, check value low */
    passert(gpio_set_direction(gpio, GPIO_DIR_OUT) == 0);
    passert(gpio_get_direction(gpio, &direction) == 0);
    passert(direction == GPIO_DIR_OUT);
    passert(gpio_read(gpio, &value) == 0);
    passert(value == false);
    /* Set direction out low, check direction out, check value low */
    passert(gpio_set_direction(gpio, GPIO_DIR_OUT_LOW) == 0);
    passert(gpio_get_direction(gpio, &direction) == 0);
    passert(direction == GPIO_DIR_OUT);
    passert(gpio_read(gpio, &value) == 0);
    passert(value == false);
    /* Set direction out high, check direction out, check value high */
    passert(gpio_set_direction(gpio, GPIO_DIR_OUT_HIGH) == 0);
    passert(gpio_get_direction(gpio, &direction) == 0);
    passert(direction == GPIO_DIR_OUT);
    passert(gpio_read(gpio, &value) == 0);
    passert(value == true);

    /* Set drive open drain, check drive open drain */
    passert(gpio_set_drive(gpio, GPIO_DRIVE_OPEN_DRAIN) == 0);
    passert(gpio_get_drive(gpio, &drive) == 0);
    passert(drive == GPIO_DRIVE_OPEN_DRAIN);
    /* Set drive open source, check drive open source */
    passert(gpio_set_drive(gpio, GPIO_DRIVE_OPEN_SOURCE) == 0);
    passert(gpio_get_drive(gpio, &drive) == 0);
    passert(drive == GPIO_DRIVE_OPEN_SOURCE);
    /* Set drive default, check drive default */
    passert(gpio_set_drive(gpio, GPIO_DRIVE_DEFAULT) == 0);
    passert(gpio_get_drive(gpio, &drive) == 0);
    passert(drive == GPIO_DRIVE_DEFAULT);

    /* Set inverted true, check inverted true */
    passert(gpio_set_inverted(gpio, true) == 0);
    passert(gpio_get_inverted(gpio, &inverted) == 0);
    passert(inverted == true);
    /* Set inverted false, check inverted false */
    passert(gpio_set_inverted(gpio, false) == 0);
    passert(gpio_get_inverted(gpio, &inverted) == 0);
    passert(inverted == false);

    /* Attempt to set interrupt edge on output GPIO */
    passert(gpio_set_edge(gpio, GPIO_EDGE_RISING) == GPIO_ERROR_INVALID_OPERATION);
    /* Attempt to read event on output GPIO */
    passert(gpio_read_event(gpio, &edge, NULL) == GPIO_ERROR_INVALID_OPERATION);

    /* Set direction in, check direction in */
    passert(gpio_set_direction(gpio, GPIO_DIR_IN) == 0);
    passert(gpio_get_direction(gpio, &direction) == 0);
    passert(direction == GPIO_DIR_IN);
    passert(gpio_read(gpio, &value) == 0);

    /* Set edge none, check edge none */
    passert(gpio_set_edge(gpio, GPIO_EDGE_NONE) == 0);
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_NONE);
    /* Set edge rising, check edge rising */
    passert(gpio_set_edge(gpio, GPIO_EDGE_RISING) == 0);
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_RISING);
    /* Set edge falling, check edge falling */
    passert(gpio_set_edge(gpio, GPIO_EDGE_FALLING) == 0);
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_FALLING);
    /* Set edge both, check edge both */
    passert(gpio_set_edge(gpio, GPIO_EDGE_BOTH) == 0);
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_BOTH);
    /* Set edge none, check edge none */
    passert(gpio_set_edge(gpio, GPIO_EDGE_NONE) == 0);
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_NONE);

    /* Set bias pull up, check bias pull up */
    passert(gpio_set_bias(gpio, GPIO_BIAS_PULL_UP) == 0);
    passert(gpio_get_bias(gpio, &bias) == 0);
    passert(bias == GPIO_BIAS_PULL_UP);
    /* Set bias pull down, check bias pull down */
    passert(gpio_set_bias(gpio, GPIO_BIAS_PULL_DOWN) == 0);
    passert(gpio_get_bias(gpio, &bias) == 0);
    passert(bias == GPIO_BIAS_PULL_DOWN);
    /* Set bias disable, check bias disable */
    passert(gpio_set_bias(gpio, GPIO_BIAS_DISABLE) == 0);
    passert(gpio_get_bias(gpio, &bias) == 0);
    passert(bias == GPIO_BIAS_DISABLE);
    /* Set bias default, check bias default */
    passert(gpio_set_bias(gpio, GPIO_BIAS_DEFAULT) == 0);
    passert(gpio_get_bias(gpio, &bias) == 0);
    passert(bias == GPIO_BIAS_DEFAULT);

    /* Attempt to set drive on input GPIO */
    passert(gpio_set_drive(gpio, GPIO_DRIVE_OPEN_DRAIN) == GPIO_ERROR_INVALID_OPERATION);

    /* Close GPIO */
    passert(gpio_close(gpio) == 0);

    /* Open GPIO with advanced open */
    gpio_config_t config = {
        .direction = GPIO_DIR_IN,
        .edge = GPIO_EDGE_RISING,
        .bias = GPIO_BIAS_DEFAULT,
        .drive = GPIO_DRIVE_DEFAULT,
        .inverted = false,
        .label = "test123",
    };
    passert(gpio_open_advanced(gpio, device, pin_input, &config) == 0);

    /* Check properties */
    passert(gpio_line(gpio) == pin_input);
    passert(gpio_fd(gpio) >= 0);
    passert(gpio_chip_fd(gpio) >= 0);
    /* Check direction */
    passert(gpio_get_direction(gpio, &direction) == 0);
    passert(direction == GPIO_DIR_IN);
    /* Check edge */
    passert(gpio_get_edge(gpio, &edge) == 0);
    passert(edge == GPIO_EDGE_RISING);
    /* Check bias */
    passert(gpio_get_bias(gpio, &bias) == 0);
    passert(bias == GPIO_BIAS_DEFAULT);
    /* Check drive */
    passert(gpio_get_drive(gpio, &drive) == 0);
    passert(drive == GPIO_DRIVE_DEFAULT);
    /* Check inverted */
    passert(gpio_get_inverted(gpio, &inverted) == 0);
    passert(inverted == false);
    /* Check label */
    passert(gpio_label(gpio, label, sizeof(label)) == 0);
    passert(strncmp(label, "test123", sizeof(label)) == 0);

    /* Close GPIO */
    passert(gpio_close(gpio) == 0);

    /* Free GPIO */
    gpio_free(gpio);
}

/* Threaded poll helper functions */

typedef struct {
    sem_t *sem;
    gpio_t *gpio;
    int timeout_ms;
} gpio_poll_args_t;

void *gpio_poll_thread(void *arg) {
    gpio_poll_args_t *args = (gpio_poll_args_t *)arg;
    gpio_t *gpio = args->gpio;
    int timeout_ms = args->timeout_ms;

    assert(sem_post(args->sem) == 0);

    intptr_t ret = gpio_poll(gpio, timeout_ms);

    return (void *)ret;
}

void gpio_poll_start(pthread_t *thread, gpio_t *gpio, int timeout_ms) {
    sem_t sem;
    gpio_poll_args_t args = {.sem = &sem, .gpio = gpio, .timeout_ms = timeout_ms};

    assert(sem_init(&sem, 0, 0) == 0);
    assert(pthread_create(thread, NULL, &gpio_poll_thread, &args) == 0);
    assert(sem_wait(&sem) == 0);
}

int gpio_poll_join(pthread_t thread) {
    void *ret;

    assert(pthread_join(thread, &ret) == 0);

    return (intptr_t)ret;
}

void test_loopback(void) {
    gpio_t *gpio_in, *gpio_out;
    pthread_t poll_thread;
    bool value;
    gpio_edge_t edge;

    ptest();

    /* Allocate GPIO */
    gpio_in = gpio_new();
    passert(gpio_in != NULL);
    gpio_out = gpio_new();
    passert(gpio_out != NULL);

    /* Open in and out pins */
    passert(gpio_open(gpio_in, device, pin_input, GPIO_DIR_IN) == 0);
    passert(gpio_open(gpio_out, device, pin_output, GPIO_DIR_OUT) == 0);

    /* Drive out low, check in low */
    passert(gpio_write(gpio_out, false) == 0);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == false);

    /* Drive out high, check in high */
    passert(gpio_write(gpio_out, true) == 0);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == true);

    /* Check poll falling 1 -> 0 interrupt */
    passert(gpio_set_edge(gpio_in, GPIO_EDGE_FALLING) == 0);
    gpio_poll_start(&poll_thread, gpio_in, 1000);
    passert(gpio_write(gpio_out, false) == 0);
    passert(gpio_poll_join(poll_thread) == 1);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == false);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_FALLING);

    /* Check poll rising 0 -> 1 interrupt */
    passert(gpio_set_edge(gpio_in, GPIO_EDGE_RISING) == 0);
    gpio_poll_start(&poll_thread, gpio_in, 1000);
    passert(gpio_write(gpio_out, true) == 0);
    passert(gpio_poll_join(poll_thread) == 1);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == true);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_RISING);

    /* Set both edge */
    passert(gpio_set_edge(gpio_in, GPIO_EDGE_BOTH) == 0);

    /* Check poll falling 1 -> 0 interrupt */
    gpio_poll_start(&poll_thread, gpio_in, 1000);
    passert(gpio_write(gpio_out, false) == 0);
    passert(gpio_poll_join(poll_thread) == 1);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == false);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_FALLING);

    /* Check poll rising 0 -> 1 interrupt */
    gpio_poll_start(&poll_thread, gpio_in, 1000);
    passert(gpio_write(gpio_out, true) == 0);
    passert(gpio_poll_join(poll_thread) == 1);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == true);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_RISING);

    /* Check poll timeout */
    passert(gpio_poll(gpio_in, 1000) == 0);

    /* Test gpio_poll_multiple() API with one GPIO */
    gpio_t *gpios[1] = {gpio_in};
    bool gpios_ready[1] = {false};

    /* Check poll falling 1 -> 0 interrupt */
    passert(gpio_write(gpio_out, false) == 0);
    passert(gpio_poll_multiple(gpios, 1, 1000, gpios_ready) == 1);
    passert(gpios_ready[0] == true);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == false);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_FALLING);

    /* Check poll rising 0 -> 1 interrupt */
    passert(gpio_write(gpio_out, true) == 0);
    passert(gpio_poll_multiple(gpios, 1, 1000, gpios_ready) == 1);
    passert(gpios_ready[0] == true);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == true);
    passert(gpio_read_event(gpio_in, &edge, NULL) == 0);
    passert(edge == GPIO_EDGE_RISING);

    /* Check poll timeout */
    passert(gpio_poll_multiple(gpios, 1, 1000, gpios_ready) == 0);
    passert(gpios_ready[0] == false);

    passert(gpio_close(gpio_in) == 0);
    passert(gpio_close(gpio_out) == 0);

    /* Open both GPIOs as inputs */
    passert(gpio_open(gpio_in, device, pin_input, GPIO_DIR_IN) == 0);
    passert(gpio_open(gpio_out, device, pin_output, GPIO_DIR_IN) == 0);

    /* Set bias pull-up, check value is high */
    passert(gpio_set_bias(gpio_in, GPIO_BIAS_PULL_UP) == 0);
    usleep(1000);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == true);

    /* Set bias pull-down, check value is low */
    passert(gpio_set_bias(gpio_in, GPIO_BIAS_PULL_DOWN) == 0);
    usleep(1000);
    passert(gpio_read(gpio_in, &value) == 0);
    passert(value == false);

    passert(gpio_close(gpio_in) == 0);
    passert(gpio_close(gpio_out) == 0);

    /* Free GPIO */
    gpio_free(gpio_in);
    gpio_free(gpio_out);
}

bool getc_yes(void) {
    char buf[4];
    fgets(buf, sizeof(buf), stdin);
    return (buf[0] == 'y' || buf[0] == 'Y');
}

void test_interactive(void) {
    char str[256];
    gpio_t *gpio;

    ptest();

    /* Allocate GPIO */
    gpio = gpio_new();
    passert(gpio != NULL);

    passert(gpio_open(gpio, device, pin_output, GPIO_DIR_OUT) == 0);

    printf("Starting interactive test. Get out your multimeter, buddy!\n");
    printf("Press enter to continue...\n");
    getc(stdin);

    /* Check tostring */
    passert(gpio_tostring(gpio, str, sizeof(str)) > 0);
    printf("GPIO description: %s\n", str);
    printf("GPIO description looks OK? y/n\n");
    passert(getc_yes());

    /* Drive GPIO out low */
    passert(gpio_write(gpio, false) == 0);
    printf("GPIO out is low? y/n\n");
    passert(getc_yes());

    /* Drive GPIO out high */
    passert(gpio_write(gpio, true) == 0);
    printf("GPIO out is high? y/n\n");
    passert(getc_yes());

    /* Drive GPIO out low */
    passert(gpio_write(gpio, false) == 0);
    printf("GPIO out is low? y/n\n");
    passert(getc_yes());

    passert(gpio_close(gpio) == 0);

    /* Free GPIO */
    gpio_free(gpio);
}

int main(int argc, char *argv[]) {
    if (argc < 4) {
        fprintf(stderr, "Usage: %s <GPIO chip device> <GPIO #1> <GPIO #2>\n\n", argv[0]);
        fprintf(stderr, "[1/4] Argument test: No requirements.\n");
        fprintf(stderr, "[2/4] Open/close test: GPIO #2 should be real.\n");
        fprintf(stderr, "[3/4] Loopback test: GPIOs #1 and #2 should be connected with a wire.\n");
        fprintf(stderr, "[4/4] Interactive test: GPIO #2 should be observed with a multimeter.\n\n");
        fprintf(stderr, "Hint: for Raspberry Pi 3,\n");
        fprintf(stderr, "Use GPIO 17 (header pin 11) and GPIO 27 (header pin 13),\n");
        fprintf(stderr, "connect a loopback between them, and run this test with:\n");
        fprintf(stderr, "    %s /dev/gpiochip0 17 27\n\n", argv[0]);
        exit(1);
    }

    device = argv[1];
    pin_input = strtoul(argv[2], NULL, 10);
    pin_output = strtoul(argv[3], NULL, 10);

    test_arguments();
    printf(" " STR_OK "  Arguments test passed.\n\n");
    test_open_config_close();
    printf(" " STR_OK "  Open/close test passed.\n\n");
    test_loopback();
    printf(" " STR_OK "  Loopback test passed.\n\n");
    test_interactive();
    printf(" " STR_OK "  Interactive test passed.\n\n");

    printf("All tests passed!\n");
    return 0;
}


text:
.adminPagination-wrapper {
    text-align: center;
}

.adminPagination {
    position: relative;
    padding: 0;
    margin: -10px 145px;
}

.adminPagination > li > a, .adminPagination > li > span {
    float: none;
    padding: 0;
    margin: 0 20px;
    line-height: 10px;
    background: none;
    border: none;
    font-size: 13px;
    font-weight: 700;
    font-family: "Montserrat", sans-serif;
}

.adminPagination > li > a:focus, .adminPagination > li > a:hover, .adminPagination > li > span:focus, .adminPagination > li > span:hover {
    background: none;
    color: #444;
}

.adminPagination > li.prev > a {
    display: block;
    width: 63px;
    text-align: center;
    line-height: 53px;
    margin: 0;
    position: absolute;
    left: -38px;
    top: 11px;
    background: #00b0ff;
    border-radius: 0;
    font-size: 16px;
}

.adminPagination > li.next > a {
    display: block;
    width: 63px;
    text-align: center;
    line-height: 53px;
    margin: 0;
    position: absolute;
    background: #00b0ff;
    border-radius: 0;
    font-size: 16px;
}


text:
namespace XmrStakGui
{
    partial class About
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(15, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(250, 26);
            this.label1.TabIndex = 0;
            this.label1.Text = "XmrStakGui is a configuration tool for xmr-stak-cpu, \r\nxmr-stak-amd and xmr-stak-nvidia miners.";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(131, 78);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Close";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(15, 43);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(49, 13);
            this.label2.TabIndex = 2;
            this.label2.Text = "Website:";
            //
            // linkLabel1
            //
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(61, 43);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(218, 13);
            this.linkLabel1.TabIndex = 3;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "https://aram-aramyan.github.io/xmr-stak-gui/";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // About
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(340, 111);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "About";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "About";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.LinkLabel linkLabel1;
    }
}


text:
        <video id="cameraVideo" autoplay hidden="[[!cameraOnline_]]"></video>
        <paper-spinner-lite active="[[!cameraOnline_]]"></paper-spinner-lite>

        <iron-a11y-keys keys="up down left right"></iron-a11y-keys>
        <cr-icon-button id="takePhoto" tabindex="1"
            title="[[getTakePhotoLabel_(videomode, takePhotoLabel,
                captureVideoLabel)]]" on-click="takePhoto"
            disabled="[[!cameraOnline_]]"
            iron-icon="[[getTakePhotoIcon_(videomode)]]">
        </cr-icon-button>

        <cr-icon-button hidden="[[!videoModeEnabled]]" id="switchMode"
            tabindex="2" on-click="onTapSwitchMode_"
            title="[[getSwitchModeLabel_(videomode, switchModeToCameraLabel,
                switchModeToVideoLabel)]]" disabled="[[!cameraOnline_]]"
            iron-icon="[[getSwitchModeIcon_(videomode)]]">
        </cr-icon-button>


text:
package org.terasology.logic.behavior.asset;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.abego.treelayout.TreeForTreeLayout;
import org.abego.treelayout.TreeLayout;
import org.abego.treelayout.util.DefaultConfiguration;
import org.abego.treelayout.util.FixedNodeExtentProvider;
import org.terasology.assets.AssetData;
import org.terasology.logic.behavior.BehaviorNodeComponent;
import org.terasology.logic.behavior.BehaviorNodeFactory;
import org.terasology.logic.behavior.nui.RenderableNode;
import org.terasology.logic.behavior.tree.Node;
import org.terasology.registry.CoreRegistry;

import java.awt.geom.Rectangle2D;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author synopia
 */
public class BehaviorTreeData implements AssetData {
    private Map<Node, RenderableNode> renderableNodes = Maps.newHashMap();
    private Node root;
    private RenderableNode renderableRoot;

    public void setRoot(Node root) {
        this.root = root;
    }

    public void setRenderableRoot(RenderableNode renderableRoot) {
        this.renderableRoot = renderableRoot;
    }

    public RenderableNode createNode(Node node) {
        BehaviorNodeComponent nodeComponent = CoreRegistry.get(BehaviorNodeFactory.class).getNodeComponent(node);
        RenderableNode self = new RenderableNode(nodeComponent);
        self.setNode(node);
        renderableNodes.put(node, self);
        return self;
    }

    public void createRenderable() {
        renderableRoot = createRenderable(root);
    }

    public RenderableNode createRenderable(Node node) {
        return node.visit(null, new Node.Visitor<RenderableNode>() {
            @Override
            public RenderableNode visit(RenderableNode parent, Node node) {
                RenderableNode self = createNode(node);
                if (parent != null) {
                    parent.withoutModel().insertChild(-1, self);
                }
                return self;
            }
        });
    }

    public void layout(RenderableNode start) {
        LayoutTree layoutTree;
        if (start == null) {
            layoutTree = new LayoutTree(renderableRoot);
        } else {
            layoutTree = new LayoutTree(start);
        }
        TreeLayout<RenderableNode> layout = new TreeLayout<>(layoutTree, new FixedNodeExtentProvider<RenderableNode>(10, 5), new DefaultConfiguration<RenderableNode>(4, 2));
        Map<RenderableNode, Rectangle2D.Double> bounds = layout.getNodeBounds();
        for (Map.Entry<RenderableNode, Rectangle2D.Double> entry : bounds.entrySet()) {
            RenderableNode node = entry.getKey();
            Rectangle2D.Double rect = entry.getValue();
            node.setPosition((float) rect.getX(), (float) rect.getY());
        }
    }

    public boolean hasRenderable() {
        return renderableRoot != null;
    }

    public Node getRoot() {
        return root;
    }

    public List<RenderableNode> getRenderableNodes() {
        final List<RenderableNode> result = Lists.newArrayList();
        root.visit(null, new Node.Visitor<RenderableNode>() {
            @Override
            public RenderableNode visit(RenderableNode item, Node node) {
                result.add(renderableNodes.get(node));
                return null;
            }
        });
        return result;
    }

    public RenderableNode getRenderableNode(Node node) {
        return renderableNodes.get(node);
    }

    private static final class LayoutTree implements TreeForTreeLayout<RenderableNode> {
        private RenderableNode root;

        private LayoutTree(RenderableNode root) {
            this.root = root;
        }

        @Override
        public RenderableNode getRoot() {
            return root;
        }

        @Override
        public boolean isLeaf(RenderableNode uiWidgets) {
            return uiWidgets.getChildrenCount() == 0;
        }

        @Override
        public boolean isChildOfParent(RenderableNode node, RenderableNode parentNode) {
            return parentNode.children().contains(node);
        }

        @Override
        public Iterable<RenderableNode> getChildren(RenderableNode parentNode) {
            return parentNode.children();
        }

        @Override
        public Iterable<RenderableNode> getChildrenReverse(RenderableNode parentNode) {
            List<RenderableNode> list = Lists.newArrayList(parentNode.children());
            Collections.reverse(list);
            return list;
        }

        @Override
        public RenderableNode getFirstChild(RenderableNode parentNode) {
            return parentNode.getChild(0);
        }

        @Override
        public RenderableNode getLastChild(RenderableNode parentNode) {
            return parentNode.getChild(Math.max(0, parentNode.getChildrenCount() - 1));
        }
    }
}